问:
How to convert a date to milliseconds
I want to convert String myDate = "2014/10/29 18:10:45" to
long ms (i.e. currentinmlilies)? I look for it on Google, but I can only find how to convert ms to date.

Note: To make it clear, I want to get the ms from the date in 1970/1/1 format.

答:
The 2017 answer is: Use the date and time classes introduced in Java 8 (and also backported to Java 6 and 7 in the ThreeTen Backport).

If you want to interpret the date-time string in the computer’s time zone:

```<code>    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atZone(ZoneId.systemDefault())
            .toInstant()
            .toEpochMilli();
</code>```

If another time zone, fill that zone in instead of ZoneId.systemDefault(). If UTC, use

```<code>    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atOffset(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();
</code>```

Title: How to convert a date to milliseconds

Body:
The 2017 answer is: Use the date and time classes introduced in Java 8 (and also backported to Java 6 and 7 in the ThreeTen Backport).

If you want to interpret the date-time string in the computer’s time zone:

    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atZone(ZoneId.systemDefault())
            .toInstant()
            .toEpochMilli();

If another time zone, fill that zone in instead of ZoneId.systemDefault(). If UTC, use

    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atOffset(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();


来源: stackexchange

问:
How to stop CKEditor producing \r\n characters automatically when data is sanitized in PHP?
I am having a problem regarding data coming from CKEditor textarea field. I am using CKEditor 4.4.1. Whenever I try to submit the content of CKEditor it generates characters \r\n again and again. But it happening only when I am sanitizing my incoming data. Here is my function which sanitizes the incoming content -

```<code>// filter user input
public function filter_data($input)
{
    // if magic quotes are on
    if(get_magic_quotes_gpc())
    {
        $input = stripslashes($input);
    }
    $sanitized_data = mysqli_real_escape_string($this->con, trim($input));
    return $sanitized_data;
}
</code>```

And this is how I am calling the above function -

```<code>$post_content = $users_obj->filter_data($_POST['txtpostcontent']);
</code>```

And then I am getting following output in CKEditor -

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

\r\n\r\n

\r\n\r\n

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

\r\n\r\n
</code>```

But when I don't call the above function then everything is fine and there is no characters like \r\n in my content.

So I want to know how can I stop these characters from being produced automatically by keeping my sanitizing function on? Is there any way I can sanitized my content and also don't get these characters as well? Thanks.

答:
I have fixed the problem and it turns out to be a very simple setting. In config.js I simply set:

```<code>config.FormatOutput = false ;
</code>```

And it works no more stupid \r\n inserted into my html

ContentLicense: CC BY-SA 4.0

Body:
I am having a problem regarding data coming from CKEditor textarea field. I am using CKEditor 4.4.1. Whenever I try to submit the content of CKEditor it generates characters \r\n again and again. But it happening only when I am sanitizing my incoming data. Here is my function which sanitizes the incoming content -

// filter user input
public function filter_data($input)
{
    // if magic quotes are on
    if(get_magic_quotes_gpc())
    {
        $input = stripslashes($input);
    }
    $sanitized_data = mysqli_real_escape_string($this->con, trim($input));
    return $sanitized_data;
}

And this is how I am calling the above function -

$post_content = $users_obj->filter_data($_POST['txtpostcontent']);

And then I am getting following output in CKEditor -

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

\r\n\r\n

\r\n\r\n

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

\r\n\r\n

But when I don't call the above function then everything is fine and there is no characters like \r\n in my content.

So I want to know how can I stop these characters from being produced automatically by keeping my sanitizing function on? Is there any way I can sanitized my content and also don't get these characters as well? Thanks.

Body:
I have fixed the problem and it turns out to be a very simple setting. In config.js I simply set:

config.FormatOutput = false ;

And it works no more stupid \r\n inserted into my html

ContentLicense: CC BY-SA 3.0


问:
Google Speech API Python Exception: Specify FLAC encoding to match file header?
I'm running the example code for Google Speech API Python published here: https://googlecloudplatform.github.io/google-cloud-python/stable/speech-usage.html

I'm going for the Asynchronous Recognition method (which only allows the use LINEAR16 encoding):

Imports the Google Cloud client library

```<code>  from google.cloud import speech

  client = speech.Client()
  sample = client.sample(source_uri='gs://my-bucket/example.flac',
                    encoding=speech.Encoding.LINEAR16,
                    sample_rate=44100)
  operation = sample.async_recognize(language_code='es-CL',max_alternatives=2)

   retry_count = 100
   while retry_count > 0 and not operation.complete:
   retry_count -= 1
   time.sleep(10)
   operation.poll()  # API call

   operation.complete

   for result in operation.results:
        for alternative in result.alternatives:
        print('=' * 20)
        print(alternative.transcript)
        print(alternative.confidence)
</code>```

This is the error I'm getting:
google.gax.errors.RetryError: GaxError(Exception occurred in retry method that was not classified as transient, caused by <_Rendezvous of RPC that terminated with (StatusCode.INVALID_ARGUMENT, Specify FLAC encoding to match file header.)>)

How can I solve this? I'm not getting this issue when using the Synchronous Method.

答:
From your code (and the Google code you linked to) it looks like you're specifying the encoding as LINEAR16 but using a FLAC file.  If you need to use the async API then you'll have to convert the .flac file to a raw LINEAR PCM file.  So the second line should look more like this:

```<code>sample = client.sample(source_uri='gs://my-bucket/example.raw',
                encoding=speech.Encoding.LINEAR16,
                sample_rate=44100)
</code>```

To convert from FLAC to LINEAR16 you'll need to use another tool, like sox.
See this page for more information on converting the file format.  The command is probably something like:

```<code>sox example.flac example.raw
</code>```

Body:
I'm running the example code for Google Speech API Python published here: https://googlecloudplatform.github.io/google-cloud-python/stable/speech-usage.html

I'm going for the Asynchronous Recognition method (which only allows the use LINEAR16 encoding):

Imports the Google Cloud client library

  from google.cloud import speech

  client = speech.Client()
  sample = client.sample(source_uri='gs://my-bucket/example.flac',
                    encoding=speech.Encoding.LINEAR16,
                    sample_rate=44100)
  operation = sample.async_recognize(language_code='es-CL',max_alternatives=2)

   retry_count = 100
   while retry_count > 0 and not operation.complete:
   retry_count -= 1
   time.sleep(10)
   operation.poll()  # API call

   operation.complete

   for result in operation.results:
        for alternative in result.alternatives:
        print('=' * 20)
        print(alternative.transcript)
        print(alternative.confidence)

This is the error I'm getting:
google.gax.errors.RetryError: GaxError(Exception occurred in retry method that was not classified as transient, caused by <_Rendezvous of RPC that terminated with (StatusCode.INVALID_ARGUMENT, Specify FLAC encoding to match file header.)>)

How can I solve this? I'm not getting this issue when using the Synchronous Method.

Body:
From your code (and the Google code you linked to) it looks like you're specifying the encoding as LINEAR16 but using a FLAC file.  If you need to use the async API then you'll have to convert the .flac file to a raw LINEAR PCM file.  So the second line should look more like this:

sample = client.sample(source_uri='gs://my-bucket/example.raw',
                encoding=speech.Encoding.LINEAR16,
                sample_rate=44100)

To convert from FLAC to LINEAR16 you'll need to use another tool, like sox.
See this page for more information on converting the file format.  The command is probably something like:

sox example.flac example.raw


问:
kotlin and @Valid Spring annotation
I have an entity:

```<code>class SomeInfo(
        @NotNull @Pattern(regexp = Constraints.EMAIL_REGEX) var value: String) {
    var id: Long? = null
}
</code>```

And controller method:

```<code>@RequestMapping(value = "/some-info", method = RequestMethod.POST)
public Id create(@Valid @RequestBody SomeInfo someInfo) {
       ...
    }
</code>```

@Valid annotation doesn't work.

It seems Spring needs a default parameterless constructor and fancy code above becomes in something ugly (but working) like this:

```<code>class SomeInfo() {

    constructor(value: String) {
            this.value = value
        }

        @NotNull @Pattern(regexp = Constraints.EMAIL_REGEX)
        lateinit var value: String

        var id: Long? = null
    }
</code>```

Any good practice to make it less wordy?

Thanks.

答:
As an alternative to Michal's answer, annotating the getter also works.

```<code>class SomeInfo(
    @get:NotNull
    @get:Pattern(regexp = Constraints.EMAIL_REGEX)
    var value: String
) {
    var id: Long? = null
}
</code>```

The annoying part is, that not using @get: or @field: will annotate the constructor parameter. This is still valid kotlin code (so you don't get an error). It's just useless in these use cases.

Title: kotlin and @Valid Spring annotation

Body:
I have an entity:

class SomeInfo(
        @NotNull @Pattern(regexp = Constraints.EMAIL_REGEX) var value: String) {
    var id: Long? = null
}

And controller method:

@RequestMapping(value = "/some-info", method = RequestMethod.POST)
public Id create(@Valid @RequestBody SomeInfo someInfo) {
       ...
    }

@Valid annotation doesn't work.

It seems Spring needs a default parameterless constructor and fancy code above becomes in something ugly (but working) like this:

class SomeInfo() {

    constructor(value: String) {
            this.value = value
        }

        @NotNull @Pattern(regexp = Constraints.EMAIL_REGEX)
        lateinit var value: String

        var id: Long? = null
    }

Any good practice to make it less wordy?

Thanks.

Body:
As an alternative to Michal's answer, annotating the getter also works.

class SomeInfo(
    @get:NotNull
    @get:Pattern(regexp = Constraints.EMAIL_REGEX)
    var value: String
) {
    var id: Long? = null
}

The annoying part is, that not using @get: or @field: will annotate the constructor parameter. This is still valid kotlin code (so you don't get an error). It's just useless in these use cases.


问:
MySql and creating Foreign keys
```<code>    -- MySQL Script generated by MySQL Workbench
-- Sun Apr  2 17:50:54 2017
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema SintalDB
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema SintalDB
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `SintalDB` DEFAULT CHARACTER SET utf8 COLLATE utf8_slovenian_ci ;
USE `SintalDB` ;

-- -----------------------------------------------------
-- Table `SintalDB`.`User`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`User` (
  `PK_User` INT NOT NULL,
  `Name` VARCHAR(15) NOT NULL,
  `Surname` VARCHAR(25) NOT NULL,
  `Phone_Nr` VARCHAR(13) NOT NULL,
  `Email` VARCHAR(90) NOT NULL,
  `Car_Reg_Nr` VARCHAR(10) NULL,
  `Username` VARCHAR(20) NOT NULL,
  `Password` VARCHAR(20) NOT NULL,
  `Servis_Input_Rights` TINYINT(1) NOT NULL,
  `Servis_Output_Rights` TINYINT(1) NOT NULL,
  `Servis_Delete_Rights` TINYINT(1) NOT NULL,
  `Admin_Rights` TINYINT(1) NOT NULL,
  PRIMARY KEY (`PK_User`))
ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`City`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`City` (
  `PK_City` INT NOT NULL,
  `Name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`PK_City`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Company`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Company` (
  `PK_Company` INT NOT NULL,
  `Name` VARCHAR(25) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `Address_Nr` VARCHAR(4) NOT NULL,
  `FK_City` INT NOT NULL,
  PRIMARY KEY (`PK_Company`),
  INDEX `FK_City_Company_fkn_idx` (`FK_City` ASC),
  CONSTRAINT `FK_City_Company_fkn`
    FOREIGN KEY (`FK_City`)
    REFERENCES `SintalDB`.`City` (`PK_City`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Facility`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Facility` (
  `PK_Facility_AD` VARCHAR(6) NOT NULL,
  `Name` VARCHAR(60) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `Address_Nr` VARCHAR(4) NOT NULL,
  `FK_City` INT NOT NULL,
  `FK_Company_Affiliation` INT NOT NULL,
  PRIMARY KEY (`PK_Facility_AD`),
  INDEX `FK_City_Facility_fkn_idx` (`FK_City` ASC),
  INDEX `FK_Company_Affiliation_Facility_fkn_idx` (`FK_Company_Affiliation` ASC),
  CONSTRAINT `FK_City_Facility_fkn`
    FOREIGN KEY (`FK_City`)
    REFERENCES `SintalDB`.`City` (`PK_City`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Company_Affiliation_Facility_fkn`
    FOREIGN KEY (`FK_Company_Affiliation`)
    REFERENCES `SintalDB`.`Company` (`PK_Company`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Servis`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Servis` (
  `PK_Servis_Nr` VARCHAR(11) NOT NULL,
  `FK_Facility_AD` VARCHAR(6) NOT NULL,
  `Description` VARCHAR(255) NOT NULL,
  `Date_Recived` DATETIME NOT NULL,
  `FK_User_Commited` INT NULL,
  `Date_Commited` DATETIME NULL,
  `FK_User_Done` INT NULL,
  `Date_Done` DATETIME NULL,
  PRIMARY KEY (`PK_Servis_Nr`),
  INDEX `FK_User_Servis_fkn_idx` (`FK_User_Commited` ASC, `FK_User_Done` ASC),
  INDEX `FK_Facility_Servis_fkn_idx` (`FK_Facility_AD` ASC),
  CONSTRAINT `FK_User_Servis_fkn`
    FOREIGN KEY (`FK_User_Commited` , `FK_User_Done`)
    REFERENCES `SintalDB`.`User` (`PK_User` , `PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Facility_Servis_fkn`
    FOREIGN KEY (`FK_Facility_AD`)
    REFERENCES `SintalDB`.`Facility` (`PK_Facility_AD`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`ServisNote`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`ServisNote` (
  `PK_ServisNote` INT NOT NULL,
  `Note` VARCHAR(255) NOT NULL,
  `FK_User_Note` INT NOT NULL,
  `Date_Created` DATETIME NOT NULL,
  `FK_Servis_Nr` VARCHAR(11) NOT NULL,
  PRIMARY KEY (`PK_ServisNote`),
  INDEX `FK_Servis_ServisNote_fkn_idx` (`FK_Servis_Nr` ASC),
  INDEX `FK_User_ServisNote_fkn_idx` (`FK_User_Note` ASC),
  CONSTRAINT `FK_Servis_ServisNote_fkn`
    FOREIGN KEY (`FK_Servis_Nr`)
    REFERENCES `SintalDB`.`Servis` (`PK_Servis_Nr`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_User_ServisNote_fkn`
    FOREIGN KEY (`FK_User_Note`)
    REFERENCES `SintalDB`.`User` (`PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
</code>```

this is my sql file and I get error after i run sql file

Error Code: 1215. Cannot add foreign key constraint

17:52:08  CREATE TABLE IF NOT EXISTS SintalDB.Servis (

  PK_Servis_Nr VARCHAR(11) NOT NULL,   FK_Facility_AD VARCHAR(6) NOT
  NULL,   Description VARCHAR(255) NOT NULL,   Date_Recived DATETIME
  NOT NULL,   FK_User_Commited INT NULL,   Date_Commited DATETIME
  NULL,   FK_User_Done INT NULL,   Date_Done DATETIME NULL,

  PRIMARY KEY (PK_Servis_Nr),   INDEX FK_User_Servis_fkn_idx
  (FK_User_Commited ASC, FK_User_Done ASC),   INDEX
  FK_Facility_Servis_fkn_idx (FK_Facility_AD ASC),   CONSTRAINT
  FK_User_Servis_fkn     FOREIGN KEY (FK_User_Commited ,
  FK_User_Done)     REFERENCES SintalDB.User (PK_User ,
  PK_User)     ON DELETE NO ACTION     ON UPDATE NO ACTION,

  CONSTRAINT FK_Facility_Servis_fkn     FOREIGN KEY (FK_Facility_AD)
  REFERENCES SintalDB.Facility (PK_Facility_AD)     ON DELETE NO
  ACTION     ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET
  = utf8 COLLATE = utf8_slovenian_ci    Error Code: 1215. Cannot add foreign key constraint 0.063 sec

答:
Check this: Adding foreign key on multiple columns

I think you must add two foreign key for made reference to the same column.
You can replace your code for this and test.

```<code>-- -----------------------------------------------------
-- Table `SintalDB`.`Servis`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Servis` (
  `PK_Servis_Nr` VARCHAR(11) NOT NULL,
  `FK_Facility_AD` VARCHAR(6) NOT NULL,
  `Description` VARCHAR(255) NOT NULL,
  `Date_Recived` DATETIME NOT NULL,
  `FK_User_Commited` INT NULL,
  `Date_Commited` DATETIME NULL,
  `FK_User_Done` INT NULL,
  `Date_Done` DATETIME NULL,
  PRIMARY KEY (`PK_Servis_Nr`),
  INDEX `FK_User_Servis_fkn_idx` (`FK_User_Commited` ASC, `FK_User_Done` ASC),
  INDEX `FK_Facility_Servis_fkn_idx` (`FK_Facility_AD` ASC),
  CONSTRAINT `FK_User_Servis_fkn`
    FOREIGN KEY (`FK_User_Commited`)
    REFERENCES `SintalDB`.`User` (`PK_User` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_User_Servis_2_fkn`
    FOREIGN KEY (`FK_User_Done`)
    REFERENCES `SintalDB`.`User` (`PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Facility_Servis_fkn`
    FOREIGN KEY (`FK_Facility_AD`)
    REFERENCES `SintalDB`.`Facility` (`PK_Facility_AD`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;
</code>```

Title: MySql and creating Foreign keys

Body:
    -- MySQL Script generated by MySQL Workbench
-- Sun Apr  2 17:50:54 2017
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema SintalDB
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema SintalDB
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `SintalDB` DEFAULT CHARACTER SET utf8 COLLATE utf8_slovenian_ci ;
USE `SintalDB` ;

-- -----------------------------------------------------
-- Table `SintalDB`.`User`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`User` (
  `PK_User` INT NOT NULL,
  `Name` VARCHAR(15) NOT NULL,
  `Surname` VARCHAR(25) NOT NULL,
  `Phone_Nr` VARCHAR(13) NOT NULL,
  `Email` VARCHAR(90) NOT NULL,
  `Car_Reg_Nr` VARCHAR(10) NULL,
  `Username` VARCHAR(20) NOT NULL,
  `Password` VARCHAR(20) NOT NULL,
  `Servis_Input_Rights` TINYINT(1) NOT NULL,
  `Servis_Output_Rights` TINYINT(1) NOT NULL,
  `Servis_Delete_Rights` TINYINT(1) NOT NULL,
  `Admin_Rights` TINYINT(1) NOT NULL,
  PRIMARY KEY (`PK_User`))
ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`City`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`City` (
  `PK_City` INT NOT NULL,
  `Name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`PK_City`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Company`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Company` (
  `PK_Company` INT NOT NULL,
  `Name` VARCHAR(25) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `Address_Nr` VARCHAR(4) NOT NULL,
  `FK_City` INT NOT NULL,
  PRIMARY KEY (`PK_Company`),
  INDEX `FK_City_Company_fkn_idx` (`FK_City` ASC),
  CONSTRAINT `FK_City_Company_fkn`
    FOREIGN KEY (`FK_City`)
    REFERENCES `SintalDB`.`City` (`PK_City`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Facility`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Facility` (
  `PK_Facility_AD` VARCHAR(6) NOT NULL,
  `Name` VARCHAR(60) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `Address_Nr` VARCHAR(4) NOT NULL,
  `FK_City` INT NOT NULL,
  `FK_Company_Affiliation` INT NOT NULL,
  PRIMARY KEY (`PK_Facility_AD`),
  INDEX `FK_City_Facility_fkn_idx` (`FK_City` ASC),
  INDEX `FK_Company_Affiliation_Facility_fkn_idx` (`FK_Company_Affiliation` ASC),
  CONSTRAINT `FK_City_Facility_fkn`
    FOREIGN KEY (`FK_City`)
    REFERENCES `SintalDB`.`City` (`PK_City`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Company_Affiliation_Facility_fkn`
    FOREIGN KEY (`FK_Company_Affiliation`)
    REFERENCES `SintalDB`.`Company` (`PK_Company`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`Servis`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Servis` (
  `PK_Servis_Nr` VARCHAR(11) NOT NULL,
  `FK_Facility_AD` VARCHAR(6) NOT NULL,
  `Description` VARCHAR(255) NOT NULL,
  `Date_Recived` DATETIME NOT NULL,
  `FK_User_Commited` INT NULL,
  `Date_Commited` DATETIME NULL,
  `FK_User_Done` INT NULL,
  `Date_Done` DATETIME NULL,
  PRIMARY KEY (`PK_Servis_Nr`),
  INDEX `FK_User_Servis_fkn_idx` (`FK_User_Commited` ASC, `FK_User_Done` ASC),
  INDEX `FK_Facility_Servis_fkn_idx` (`FK_Facility_AD` ASC),
  CONSTRAINT `FK_User_Servis_fkn`
    FOREIGN KEY (`FK_User_Commited` , `FK_User_Done`)
    REFERENCES `SintalDB`.`User` (`PK_User` , `PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Facility_Servis_fkn`
    FOREIGN KEY (`FK_Facility_AD`)
    REFERENCES `SintalDB`.`Facility` (`PK_Facility_AD`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

-- -----------------------------------------------------
-- Table `SintalDB`.`ServisNote`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`ServisNote` (
  `PK_ServisNote` INT NOT NULL,
  `Note` VARCHAR(255) NOT NULL,
  `FK_User_Note` INT NOT NULL,
  `Date_Created` DATETIME NOT NULL,
  `FK_Servis_Nr` VARCHAR(11) NOT NULL,
  PRIMARY KEY (`PK_ServisNote`),
  INDEX `FK_Servis_ServisNote_fkn_idx` (`FK_Servis_Nr` ASC),
  INDEX `FK_User_ServisNote_fkn_idx` (`FK_User_Note` ASC),
  CONSTRAINT `FK_Servis_ServisNote_fkn`
    FOREIGN KEY (`FK_Servis_Nr`)
    REFERENCES `SintalDB`.`Servis` (`PK_Servis_Nr`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_User_ServisNote_fkn`
    FOREIGN KEY (`FK_User_Note`)
    REFERENCES `SintalDB`.`User` (`PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

this is my sql file and I get error after i run sql file

Error Code: 1215. Cannot add foreign key constraint

17:52:08  CREATE TABLE IF NOT EXISTS SintalDB.Servis (

  PK_Servis_Nr VARCHAR(11) NOT NULL,   FK_Facility_AD VARCHAR(6) NOT
  NULL,   Description VARCHAR(255) NOT NULL,   Date_Recived DATETIME
  NOT NULL,   FK_User_Commited INT NULL,   Date_Commited DATETIME
  NULL,   FK_User_Done INT NULL,   Date_Done DATETIME NULL,

  PRIMARY KEY (PK_Servis_Nr),   INDEX FK_User_Servis_fkn_idx
  (FK_User_Commited ASC, FK_User_Done ASC),   INDEX
  FK_Facility_Servis_fkn_idx (FK_Facility_AD ASC),   CONSTRAINT
  FK_User_Servis_fkn     FOREIGN KEY (FK_User_Commited ,
  FK_User_Done)     REFERENCES SintalDB.User (PK_User ,
  PK_User)     ON DELETE NO ACTION     ON UPDATE NO ACTION,

  CONSTRAINT FK_Facility_Servis_fkn     FOREIGN KEY (FK_Facility_AD)
  REFERENCES SintalDB.Facility (PK_Facility_AD)     ON DELETE NO
  ACTION     ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET
  = utf8 COLLATE = utf8_slovenian_ci    Error Code: 1215. Cannot add foreign key constraint 0.063 sec

Body:
Check this: Adding foreign key on multiple columns

I think you must add two foreign key for made reference to the same column.
You can replace your code for this and test.

-- -----------------------------------------------------
-- Table `SintalDB`.`Servis`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `SintalDB`.`Servis` (
  `PK_Servis_Nr` VARCHAR(11) NOT NULL,
  `FK_Facility_AD` VARCHAR(6) NOT NULL,
  `Description` VARCHAR(255) NOT NULL,
  `Date_Recived` DATETIME NOT NULL,
  `FK_User_Commited` INT NULL,
  `Date_Commited` DATETIME NULL,
  `FK_User_Done` INT NULL,
  `Date_Done` DATETIME NULL,
  PRIMARY KEY (`PK_Servis_Nr`),
  INDEX `FK_User_Servis_fkn_idx` (`FK_User_Commited` ASC, `FK_User_Done` ASC),
  INDEX `FK_Facility_Servis_fkn_idx` (`FK_Facility_AD` ASC),
  CONSTRAINT `FK_User_Servis_fkn`
    FOREIGN KEY (`FK_User_Commited`)
    REFERENCES `SintalDB`.`User` (`PK_User` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_User_Servis_2_fkn`
    FOREIGN KEY (`FK_User_Done`)
    REFERENCES `SintalDB`.`User` (`PK_User`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `FK_Facility_Servis_fkn`
    FOREIGN KEY (`FK_Facility_AD`)
    REFERENCES `SintalDB`.`Facility` (`PK_Facility_AD`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_slovenian_ci;


问:
string is not a member of std for specific files
So I've created a mini personal library containing a bunch of files which have a bunch of methods relating to a specific topic (e.g. string manipulation, math, time, etc.). This is what the, for the lack of a better term, main container file looks like:

```<code>#include <iostream>
#include <fstream>
#include <conio.h> //_getch() ("Pauses" the program)
#include <stdlib.h> //atoi (Converts string to integer)
#include <io.h>
#include <stdio.h>
#include <vector>
#include <string> //I have also tried including cstring and string.h, but that didn't help
#include <sstream>
#include <windows.h>
#include <ctime>
#include <math.h>
#include <cmath>
#include <algorithm>

#include "SDL2/SDL.h"
#include "SDL2/SDL_ttf.h"

#include "numbers.cpp"
#include "strings.cpp"
#include "time.cpp"
#include "SDL.cpp"
#include "console.cpp"
#include "files.cpp"
</code>```

In case anyone's unable to tell, all of the files I made is everything below and including numbers.cpp. The rest are C++ libraries or the 2 SDL files in the middle.

std::string works in all of the files up to console.cpp. There any std::string, whether it be an argument, variable of function declaration, gives me the 'string is not a member of std' error.
If I exclude console.cpp from my build targets and project, files.cpp has the same error whenever I try to use std::string. But if I put SDL.cpp, for example, after console.cpp and before files.cpp, its std::strings work fine.

None of the files have any #include in them except SDL.cpp, which only includes some header files which also don't have any include files

I guess it might be important that I do have the following in my compiler linker options:

```<code>-lmingw32 -lSDL2main -lSDL2 -lSDL2_ttf
</code>```

I also have a search directory to the SDL2 include folder, but I don't think that that is the issue.
The build type is Static Library (That may be the problem, but it also has the same issues when I build as GUI application, dynamic library or native. I don't know much about build types, fairly new to C++) and I'm using the Code Blocks IDE.

I've already searched for a solution in other similar questions, but all those just forgot to either include string or put it in the wrong place... Thanks in advance for your help, and apologies for the lengthy question and if I've left out any important information.

答: Solved - Problem was because I was including .cpp files. Changing them to header files made it work.</p>

Body:
So I've created a mini personal library containing a bunch of files which have a bunch of methods relating to a specific topic (e.g. string manipulation, math, time, etc.). This is what the, for the lack of a better term, main container file looks like:

#include <iostream>
#include <fstream>
#include <conio.h> //_getch() ("Pauses" the program)
#include <stdlib.h> //atoi (Converts string to integer)
#include <io.h>
#include <stdio.h>
#include <vector>
#include <string> //I have also tried including cstring and string.h, but that didn't help
#include <sstream>
#include <windows.h>
#include <ctime>
#include <math.h>
#include <cmath>
#include <algorithm>

#include "SDL2/SDL.h"
#include "SDL2/SDL_ttf.h"

#include "numbers.cpp"
#include "strings.cpp"
#include "time.cpp"
#include "SDL.cpp"
#include "console.cpp"
#include "files.cpp"

In case anyone's unable to tell, all of the files I made is everything below and including numbers.cpp. The rest are C++ libraries or the 2 SDL files in the middle.

std::string works in all of the files up to console.cpp. There any std::string, whether it be an argument, variable of function declaration, gives me the 'string is not a member of std' error.
If I exclude console.cpp from my build targets and project, files.cpp has the same error whenever I try to use std::string. But if I put SDL.cpp, for example, after console.cpp and before files.cpp, its std::strings work fine.

None of the files have any #include in them except SDL.cpp, which only includes some header files which also don't have any include files

I guess it might be important that I do have the following in my compiler linker options:

-lmingw32 -lSDL2main -lSDL2 -lSDL2_ttf

I also have a search directory to the SDL2 include folder, but I don't think that that is the issue.
The build type is Static Library (That may be the problem, but it also has the same issues when I build as GUI application, dynamic library or native. I don't know much about build types, fairly new to C++) and I'm using the Code Blocks IDE.

I've already searched for a solution in other similar questions, but all those just forgot to either include string or put it in the wrong place... Thanks in advance for your help, and apologies for the lengthy question and if I've left out any important information.


问:
Angular2 - Change template of dynamic component / reload module
I have a dynamic component which receives its template in runtime and is compiled on the fly with the compileModuleAndAllComponentsSync method of Compiler from '@angular/core'.

Here is the code I use to get the componentFactory of the runtime component (please see the Plunker for complete code, all the interesting stuff is in runtime-content.component.ts)

```<code>private createComponentFactorySync(compiler: Compiler, metadata: Component): ComponentFactory<any> {
    let decoratedCmp = Component(metadata)(RuntimeComponent);

    @NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
    class RuntimeComponentModule { }

    let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);

    return module.componentFactories.find(f => f.componentType === decoratedCmp);
}
</code>```

It all works fine and the dynamic template is working fine the first time it is compiled. For my use case however I need to be able to change the template and recompile several times. But the second time I try to compile I get the error

"Type RuntimeComponent is part of the declarations of 2 modules: RuntimeComponentModule and RuntimeComponentModule!"

This of course makes sense since it does compile into another module of the same type. So my idea has been to try to unload the previously created module but cannot find any way to do that.

Anyone have an idea to acheive what I'm trying to do? Maybe by unloading the module or perhaps in another way. I have provided a working plunker to show the problem. Press the 'compile' button which will compile the dynamic template which will work fine (pressing the 'Inc' button increases the value). Pressing compile a second time will raise the error described above and the component stops working.

Plunker

答:
I would solve your problem by using compiler.clearCacheFor method:

```<code>compiler.clearCacheFor(decoratedCmp);
</code>```

Plunker Example

See also

https://angular.io/docs/ts/latest/api/core/index/Compiler-class.html#!#clearCacheFor-anchor

Body:
I have a dynamic component which receives its template in runtime and is compiled on the fly with the compileModuleAndAllComponentsSync method of Compiler from '@angular/core'.

Here is the code I use to get the componentFactory of the runtime component (please see the Plunker for complete code, all the interesting stuff is in runtime-content.component.ts)

private createComponentFactorySync(compiler: Compiler, metadata: Component): ComponentFactory<any> {
    let decoratedCmp = Component(metadata)(RuntimeComponent);

    @NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
    class RuntimeComponentModule { }

    let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);

    return module.componentFactories.find(f => f.componentType === decoratedCmp);
}

It all works fine and the dynamic template is working fine the first time it is compiled. For my use case however I need to be able to change the template and recompile several times. But the second time I try to compile I get the error

"Type RuntimeComponent is part of the declarations of 2 modules: RuntimeComponentModule and RuntimeComponentModule!"

This of course makes sense since it does compile into another module of the same type. So my idea has been to try to unload the previously created module but cannot find any way to do that.

Anyone have an idea to acheive what I'm trying to do? Maybe by unloading the module or perhaps in another way. I have provided a working plunker to show the problem. Press the 'compile' button which will compile the dynamic template which will work fine (pressing the 'Inc' button increases the value). Pressing compile a second time will raise the error described above and the component stops working.

Plunker

Body:
I would solve your problem by using compiler.clearCacheFor method:

compiler.clearCacheFor(decoratedCmp);

Plunker Example

See also

https://angular.io/docs/ts/latest/api/core/index/Compiler-class.html#!#clearCacheFor-anchor


问:
I have the encode function for an ascii cipher, but need help to how to decode it
I am working on a puzzle which involves decoding a cipher. I have been given the function used to encode the ciphertext, but I am not sure how I can reverse engineer this to find the decode function.

This is the function, in JavaScript:

```<code>function encodeText(ascii,x,y,z) {
    for (i=0; i<ascii.length; i++) {
        if(i%3==0){
            ascii[i]= (ascii[i]+x) % 256;
        }
        if(i%3==1){
            ascii[i]=(ascii[i]+y) % 256;
        }
        if(i%3==2){
            ascii[i]=(ascii[i]+z) % 256;
        }
    }
    return ascii;
}
</code>```

I am aware that it returns an array of numbers, which is the cipher text I have been presented with.

Help is greatly appreciated!

答:
This is a Vigenère Cipher with a key of length three (x, y, z).

ascii[i] and x are both smaller than 256, but (ascii[i]+x) might result in a number larger than 255. That is why the modulo operator flips it back into the range 0-255.

The decryption would look like (ascii[i] - x + 256) % 256.

ascii[i] - x is a direct opposite of ascii[i] + x, so I assume this is clear. ascii[i] may be a number smaller than x. In that case, ascii[i] - x might be less than zero. The problem is that -5 % 256 is -5 and not 251 (example). So, we need to move all possible results to the positive numbers that then apply the modulo operation.

For example, (74 - 80 + 256) is 250 and 250 % 256 is still 250. Furthermore, (84 - 80 + 256) is 260 and 260 % 256 is 4 which is the difference.

A Caesar Cipher and a Vigenère Cipher are usually broken by frequency analysis. Your instance of a Vigenère Cipher consists of three Caesar Ciphers. The key space is 256*256*256 = 16,777,216 which is too big to iterate over and read every possible recovered plaintext.

You should know what language the plaintext is in. If you have that, then you can split your ciphertext in three strings. The 1st, the 4th, the 7th and so on characters go into the first string. The 2nd, the 5th, the 8th and so on characters go into the second string. The 3rd, the 6th, the 9th and so on character go into the third string. Now, you can do on each of those three resulting strings a Frequency analysis and compare the results to the letter frequency of your target language (english example).

If the ciphertext is sufficiently long, you should be able to determine which encrypted letters are e and n. When you have that, the shift is linear. Let's say that the letter that you identified as e has an ordinal value of 43. If you look into an ASCII table, the actual lowercase e has an ordinal value of 101. That would mean that you have to calculate 43 - 101 = -58. Since this has to be positive, we can add 256 to get x = 198. You should repeat that process for y (second string) and z (third string), too.

Body:
I am working on a puzzle which involves decoding a cipher. I have been given the function used to encode the ciphertext, but I am not sure how I can reverse engineer this to find the decode function.

This is the function, in JavaScript:

function encodeText(ascii,x,y,z) {
    for (i=0; i<ascii.length; i++) {
        if(i%3==0){
            ascii[i]= (ascii[i]+x) % 256;
        }
        if(i%3==1){
            ascii[i]=(ascii[i]+y) % 256;
        }
        if(i%3==2){
            ascii[i]=(ascii[i]+z) % 256;
        }
    }
    return ascii;
}

I am aware that it returns an array of numbers, which is the cipher text I have been presented with.

Help is greatly appreciated!


问:
how can I create word count output in python just by using reduce function?
I have the following list of tuples: [('a', 1), ('a', 1), ('b', 1), ('c',1), ('a', 1), ('c', 1)]

I would like to know if I can utilize python's reduce function to aggregate them and produce the following output : [('a', 3), ('b', 1), ('c', 2)]

Or if there are other ways, I would like to know as well (loop is fine)

答:
The alternative approach using defaultdict subclass and sum function:

```<code>import collections

l = [('a', 1), ('a', 1), ('b', 1), ('c',1), ('a', 1), ('c', 1)]
d = collections.defaultdict(list)
for t in l:
    d[t[0]].append(t[1])

result = [(k,sum(v)) for k,v in d.items()]
print(result)
</code>```

The output:

```<code>[('b', 1), ('a', 3), ('c', 2)]
</code>```

Body:
The alternative approach using defaultdict subclass and sum function:

import collections

l = [('a', 1), ('a', 1), ('b', 1), ('c',1), ('a', 1), ('c', 1)]
d = collections.defaultdict(list)
for t in l:
    d[t[0]].append(t[1])

result = [(k,sum(v)) for k,v in d.items()]
print(result)

The output:

[('b', 1), ('a', 3), ('c', 2)]


问:
Rails: Update to ancestry parent not persisted
I tried to change the parent of all siblings of an ancestry model (code from the activity model):

```<code>def change_parents_of_siblings
  to_change = self.siblings.where.not(id: self.id)
  to_change.each do |sib|
    sib.update!(parent: self)
  end
end
</code>```

If I print all the ids inside the function (like sib.id, ...) to the console it seems to work. But after the function call none of these changes are persisted. For example:

```<code>@activity1 = Activity.create(name:"test1")
@activity2 = Activity.create(name:"test2", parent_id: @activity1.id )
@activity15 = Activity.create(name:"test1.5", parent_id: @activity1.id)
@activity15.change_parents_of_siblings

expect(@activity2.parent_id).to eq(@activity15.id)
</code>```

fails.

答:
After taking a bath I found the problem myself.

The change_parents_of_siblings method changed the ancestry in the database. BUt this is not recognized by Rails as a change on the model.

So I had to call @activity2.reload before using it again.

Sorry for taking your time.

Body:
I tried to change the parent of all siblings of an ancestry model (code from the activity model):

def change_parents_of_siblings
  to_change = self.siblings.where.not(id: self.id)
  to_change.each do |sib|
    sib.update!(parent: self)
  end
end

If I print all the ids inside the function (like sib.id, ...) to the console it seems to work. But after the function call none of these changes are persisted. For example:

@activity1 = Activity.create(name:"test1")
@activity2 = Activity.create(name:"test2", parent_id: @activity1.id )
@activity15 = Activity.create(name:"test1.5", parent_id: @activity1.id)
@activity15.change_parents_of_siblings

expect(@activity2.parent_id).to eq(@activity15.id)

fails.


问:
Array of Structs - Hash Table
I have a problem with this struct and I don't understand why doesn't work. I create a struct with 3 values and I want array with this SIZE = 100. But I'm confused with the malloc and how it works in this scenario.</p>

```<code>#define SIZE 100

typedef struct entry {
    long id;
    int r1;
    int r2;
    int r3;
};

typedef struct entry * THash; //[SIZE];

THash init ()
{
    int i;
    THash  t = malloc(SIZE*sizeof(struct entry));

for(i = 0; i<SIZE; i++){
    t[i] = malloc(sizeof(struct entry));
    t[i].id = -1;
    t[i].r1 = -1;
    t[i].r2 = -1;
    t[i].r3 = -1;

}
return t;
}
</code>```

答:
So what you are doing in your current program is, as Ajay pointed out in a comment, allocating the memory twice.
Let's analyze the two different mallocs in your code to see what they are doing better so you can understand what's happening :)
The first malloc, that is:

```<code>THash  t = malloc(SIZE*sizeof(struct entry));
</code>```

is taking the dimensions of your structure using the amazing (and life saving) C function sizeof and allocating the space needed by the structure 100 times. That is it is taking a pointer in the memory and allocating the memory from that point forward until the amount needed by 100 structures is reached. It is then storing the pointer in t making it, effectively, an array.

You can then simply access your array and its content by using t[0], t[1] etc, as if it was a simple array.

What you are doing with your second malloc, that is

```<code>t[i] = malloc(sizeof(struct entry));
</code>```

is reallocating some space that you have already allocated and trying to assign a pointer to the newly allocated region to the pointer to the structure (this is quite messy, I know) in fact, if you try to compile your code you'll get the following error and the function will not compile:

```<code>error: assigning to 'struct entry' from incompatible type 'void *'
    t[i] = malloc(sizeof(struct entry));
         ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

So, in order to make the function work, you simply need to remove the second malloc. I hope I made myself enough clear to what the function is doing in your situation but feel free to ask more question if you need further explanations

Title: Array of Structs - Hash Table

Body:
I have a problem with this struct and I don't understand why doesn't work. I create a struct with 3 values and I want array with this SIZE = 100. But I'm confused with the malloc and how it works in this scenario.

#define SIZE 100

typedef struct entry {
    long id;
    int r1;
    int r2;
    int r3;
};

typedef struct entry * THash; //[SIZE];

THash init ()
{
    int i;
    THash  t = malloc(SIZE*sizeof(struct entry));

for(i = 0; i<SIZE; i++){
    t[i] = malloc(sizeof(struct entry));
    t[i].id = -1;
    t[i].r1 = -1;
    t[i].r2 = -1;
    t[i].r3 = -1;

}
return t;
}

Body:
So what you are doing in your current program is, as Ajay pointed out in a comment, allocating the memory twice.
Let's analyze the two different mallocs in your code to see what they are doing better so you can understand what's happening :)
The first malloc, that is:

THash  t = malloc(SIZE*sizeof(struct entry));

is taking the dimensions of your structure using the amazing (and life saving) C function sizeof and allocating the space needed by the structure 100 times. That is it is taking a pointer in the memory and allocating the memory from that point forward until the amount needed by 100 structures is reached. It is then storing the pointer in t making it, effectively, an array.

You can then simply access your array and its content by using t[0], t[1] etc, as if it was a simple array.

What you are doing with your second malloc, that is

t[i] = malloc(sizeof(struct entry));

is reallocating some space that you have already allocated and trying to assign a pointer to the newly allocated region to the pointer to the structure (this is quite messy, I know) in fact, if you try to compile your code you'll get the following error and the function will not compile:

error: assigning to 'struct entry' from incompatible type 'void *'
    t[i] = malloc(sizeof(struct entry));
         ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

So, in order to make the function work, you simply need to remove the second malloc. I hope I made myself enough clear to what the function is doing in your situation but feel free to ask more question if you need further explanations


问:
Django where should I put my CSS file
Where should I put my css file if I have only one file (style.css) ?

I use sass for my project and I convert all my sass files to only one css file.

But I don't know where I have to put this file.. because normally I would create a static folder for each app but I think that makes no sense if I have only one file...

答:
You just need to put the CSS file somewhere and tell HTML were to find using the link tag.
For example, if the file is in the folder "style" the tag will be.

```<code><link rel="stylesheet" href="/style/file.css" />
</code>```

Usually the main css style fail was in the root folder or in a style folder.

Title: Django where should I put my CSS file

Body:
You just need to put the CSS file somewhere and tell HTML were to find using the link tag.
For example, if the file is in the folder "style" the tag will be.

<link rel="stylesheet" href="/style/file.css" />

Usually the main css style fail was in the root folder or in a style folder.


问:
Change cell if other cell contains text vba
I used to have the following code and it used to work but for some reason it no longer works.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim test As Range
Dim KeyCells As Range
Dim i As String

    Set KeyCells = Range("AF3:AF5000")
    test = Target.Rows.Count

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        For i = Target.Row To (Target.Row + (Target.Rows.Count - 1))
            If Not ActiveSheet.Cells(i, 32) = "" Then
                ActiveSheet.Cells(i, 20).Value = "Closed"
            End If
        Next

    End If
End sub
</code>```

Basically if there is data in any cells of column AF then the cell align with the information in column T would mark Closed. For example if AF65 <>"" then T65.value ="Closed"

Any idea why it no longer works or if there is another possibility for a macro?

答:
Get rid of the redundant code and non-specific worksheet references. For example, a Worksheet_Change can be triggered when that worksheet is not the Activesheet; putting in Activesheet when it is not required only confuses the issue.

You also are not disabling events so your sub is going to try to run on top of itself.

This should be closer to what you are attempting to perform.

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("AF3:AF5000"), Target.Parent.UsedRange) Is Nothing Then
        On Error GoTo safe_exit
        Application.EnableEvents = False
        Dim trgt As Range
        For Each trgt In Intersect(Target, Range("AF3:AF5000"), Target.Parent.UsedRange)
            If CBool(Len(trgt.Value2)) Then
                trgt.Offset(0, -12) = "Closed"
            Else
                trgt.Offset(0, -12) = vbNullString
            End If
        Next trgt
    End If

safe_exit:
    Application.EnableEvents = True
End Sub
</code>```

If your original sub just 'stopped working' then put Application.EnableEvents = True into the VBE's Immediate window and tap [enter]. It is possible that your earlier code crashed with event handling disabled.

Body:
I used to have the following code and it used to work but for some reason it no longer works.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim test As Range
Dim KeyCells As Range
Dim i As String

    Set KeyCells = Range("AF3:AF5000")
    test = Target.Rows.Count

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        For i = Target.Row To (Target.Row + (Target.Rows.Count - 1))
            If Not ActiveSheet.Cells(i, 32) = "" Then
                ActiveSheet.Cells(i, 20).Value = "Closed"
            End If
        Next

    End If
End sub

Basically if there is data in any cells of column AF then the cell align with the information in column T would mark Closed. For example if AF65 <>"" then T65.value ="Closed"

Any idea why it no longer works or if there is another possibility for a macro?

Body:
Get rid of the redundant code and non-specific worksheet references. For example, a Worksheet_Change can be triggered when that worksheet is not the Activesheet; putting in Activesheet when it is not required only confuses the issue.

You also are not disabling events so your sub is going to try to run on top of itself.

This should be closer to what you are attempting to perform.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("AF3:AF5000"), Target.Parent.UsedRange) Is Nothing Then
        On Error GoTo safe_exit
        Application.EnableEvents = False
        Dim trgt As Range
        For Each trgt In Intersect(Target, Range("AF3:AF5000"), Target.Parent.UsedRange)
            If CBool(Len(trgt.Value2)) Then
                trgt.Offset(0, -12) = "Closed"
            Else
                trgt.Offset(0, -12) = vbNullString
            End If
        Next trgt
    End If

safe_exit:
    Application.EnableEvents = True
End Sub

If your original sub just 'stopped working' then put Application.EnableEvents = True into the VBE's Immediate window and tap [enter]. It is possible that your earlier code crashed with event handling disabled.


问:
Gherkins of Gherkins
I am using cucumber and selenium, I have my Gherkin files. Is there any way that in cucumber I can use Gherkins of Gherkins. Where I have one step def and for that step def I can define a kind of sub-step defs in another Gherkins file.

Example:

```<code>Given I login to amazon
And I search for book "core java"
And I select core java book
And I add it in cart
And I place order
</code>```

Instead of writing these many step defs is there any way where I can say like:

```<code>Given I login to Amazon
And I place order for book "core java"
</code>```

in my main feature file I just define the above two lines where my sub-steps are in some other feature file.

答:
Calling steps from another step is not supported in Gherkin.

What you can do is to create a helper method that you can call from multiple steps. This will most likely remove the urge to call a step from another step as it will be easy to call this common helper instead. And as calling a step from another step in Gherkin isn't supported, you don't really have that choice.

Title: Gherkins of Gherkins

Body:
I am using cucumber and selenium, I have my Gherkin files. Is there any way that in cucumber I can use Gherkins of Gherkins. Where I have one step def and for that step def I can define a kind of sub-step defs in another Gherkins file.

Example:

Given I login to amazon
And I search for book "core java"
And I select core java book
And I add it in cart
And I place order

Instead of writing these many step defs is there any way where I can say like:

Given I login to Amazon
And I place order for book "core java"

in my main feature file I just define the above two lines where my sub-steps are in some other feature file.


问:
ListView not displayed in Fragment (Android)
So im following this tutorial http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/  on how to parse a JSON Api and displays data into Listview

I tried to adapt the code in my fragment , in onCreateView method , but the Listview is not displayed (blank fragment). And i dont know why.

I imported all the required libs

Actor.java

```<code>public class Actors {

private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;

public Actors() {
    // TODO Auto-generated constructor stub
}

public Actors(String name, String description, String dob, String country,
              String height, String spouse, String children, String image) {
    super();
    this.name = name;
    this.description = description;
    this.dob = dob;
    this.country = country;
    this.height = height;
    this.spouse = spouse;
    this.children = children;
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getHeight() {
    return height;
}

public void setHeight(String height) {
    this.height = height;
}

public String getSpouse() {
    return spouse;
}

public void setSpouse(String spouse) {
    this.spouse = spouse;
}

public String getChildren() {
    return children;
}

public void setChildren(String children) {
    this.children = children;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

}
</code>```

ActorAdapter.java

```<code>import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import info.androidhive.navigationdrawer.R;

public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;

public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    actorList = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // convert view = design
    View v = convertView;
    if (v == null) {
        holder = new ViewHolder();
        v = vi.inflate(Resource, null);
        holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
        holder.tvName = (TextView) v.findViewById(R.id.tvName);
        holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
        holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
        holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
        holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
        holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
        holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    holder.imageview.setImageResource(R.drawable.imgadd);
    new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
    holder.tvName.setText(actorList.get(position).getName());
    holder.tvDescription.setText(actorList.get(position).getDescription());
    holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
    holder.tvCountry.setText(actorList.get(position).getCountry());
    holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
    holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
    holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
    return v;

}

static class ViewHolder {
    public ImageView imageview;
    public TextView tvName;
    public TextView tvDescription;
    public TextView tvDOB;
    public TextView tvCountry;
    public TextView tvHeight;
    public TextView tvSpouse;
    public TextView tvChildren;

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}
}
</code>```

Articles.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:src="@drawable/imgadd" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tom Cruise"
            android:textColor="#166CED"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/tvDateOfBirth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="Date of Birth: July 3, 1962" />

        <TextView
            android:id="@+id/tvHeight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Height: 1.80 m"
            android:textColor="#D64530"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/tvCountry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="United States" />

    </LinearLayout>

</LinearLayout>

<TextView
    android:id="@+id/tvDescriptionn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#009A57"
    android:text="Description" />

<TextView
    android:id="@+id/tvSpouse"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Spouse: Katie Holmes" />

<TextView
    android:id="@+id/tvChildren"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />

</LinearLayout>
</code>```

Fragment_accueil.xml (my fragment layout)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical"
tools:context="info.androidhive.navigationdrawer.fragment.AccueilFragment">

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/articles">

</ListView>

</LinearLayout>
</code>```

fragment_accueil.java (my fragment activity)

```<code>//import.....
public class AccueilFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;
int score = 0;
TextView t1, t2, t3,t4;
ImageView img;

private OnFragmentInteractionListener mListener;

public AccueilFragment() {
}

public static AccueilFragment newInstance(String param1, String param2) {
    AccueilFragment fragment = new AccueilFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_accueil, container, false);

    t1 = (TextView) view.findViewById(R.id.tvName);
    t2 = (TextView) view.findViewById(R.id.tvDateOfBirth);
    t3 = (TextView) view.findViewById(R.id.tvHeight);
    t3 = (TextView) view.findViewById(R.id.tvCountry);
    img = (ImageView) view.findViewById(R.id.ivImage);
    ArrayList actorsList = new ArrayList<Actors>();

    ListView listview = (ListView) view.findViewById(R.id.list);
    ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);

    listview.setAdapter(adapter);

    new getData().execute();

    return view;

}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

class getData extends AsyncTask<String, String, String> {

    HttpURLConnection urlConnection;

    @Override
    protected String doInBackground(String... args) {

        StringBuilder result = new StringBuilder();

        try {
            URL url = new URL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }

        return result.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jsono = new JSONObject(result);
            JSONArray jarray = jsono.getJSONArray("actors");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

                Actors actor = new Actors();

                actor.setName(object.getString("name"));
                actor.setDescription(object.getString("description"));
                actor.setDob(object.getString("dob"));
                actor.setCountry(object.getString("country"));
                actor.setHeight(object.getString("height"));
                actor.setSpouse(object.getString("spouse"));
                actor.setChildren(object.getString("children"));
                actor.setImage(object.getString("image"));

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
public interface OnFragmentInteractionListener {

    void onFragmentInteraction(Uri uri);
}

}
</code>```

What's the problem and how to fix that ? thanks

答:
Are you adding the ListView in your fragment that you want it to be displayed for example:

```<code>public class FragmentMain extends Fragment
{
    private ListView listView; //Define the list view up here.

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Set the listview equal to the fragment name
    listView = inflater.inflate(R.layout.fragment_name, container, false);

    }
}
</code>```

This should work, let me know if otherwize :)

Body:
So im following this tutorial http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/  on how to parse a JSON Api and displays data into Listview

I tried to adapt the code in my fragment , in onCreateView method , but the Listview is not displayed (blank fragment). And i dont know why.

I imported all the required libs

Actor.java

public class Actors {

private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;

public Actors() {
    // TODO Auto-generated constructor stub
}

public Actors(String name, String description, String dob, String country,
              String height, String spouse, String children, String image) {
    super();
    this.name = name;
    this.description = description;
    this.dob = dob;
    this.country = country;
    this.height = height;
    this.spouse = spouse;
    this.children = children;
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getHeight() {
    return height;
}

public void setHeight(String height) {
    this.height = height;
}

public String getSpouse() {
    return spouse;
}

public void setSpouse(String spouse) {
    this.spouse = spouse;
}

public String getChildren() {
    return children;
}

public void setChildren(String children) {
    this.children = children;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

}

ActorAdapter.java

import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import info.androidhive.navigationdrawer.R;

public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;

public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    actorList = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // convert view = design
    View v = convertView;
    if (v == null) {
        holder = new ViewHolder();
        v = vi.inflate(Resource, null);
        holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
        holder.tvName = (TextView) v.findViewById(R.id.tvName);
        holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
        holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
        holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
        holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
        holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
        holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    holder.imageview.setImageResource(R.drawable.imgadd);
    new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
    holder.tvName.setText(actorList.get(position).getName());
    holder.tvDescription.setText(actorList.get(position).getDescription());
    holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
    holder.tvCountry.setText(actorList.get(position).getCountry());
    holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
    holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
    holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
    return v;

}

static class ViewHolder {
    public ImageView imageview;
    public TextView tvName;
    public TextView tvDescription;
    public TextView tvDOB;
    public TextView tvCountry;
    public TextView tvHeight;
    public TextView tvSpouse;
    public TextView tvChildren;

}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}
}

Articles.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:src="@drawable/imgadd" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tom Cruise"
            android:textColor="#166CED"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/tvDateOfBirth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="Date of Birth: July 3, 1962" />

        <TextView
            android:id="@+id/tvHeight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Height: 1.80 m"
            android:textColor="#D64530"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/tvCountry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#D64530"
            android:text="United States" />

    </LinearLayout>

</LinearLayout>

<TextView
    android:id="@+id/tvDescriptionn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#009A57"
    android:text="Description" />

<TextView
    android:id="@+id/tvSpouse"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Spouse: Katie Holmes" />

<TextView
    android:id="@+id/tvChildren"
    android:layout_width="wrap_content" android:textColor="#166CED"
    android:layout_height="wrap_content"
    android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />

</LinearLayout>

Fragment_accueil.xml (my fragment layout)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical"
tools:context="info.androidhive.navigationdrawer.fragment.AccueilFragment">

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/articles">

</ListView>

</LinearLayout>

fragment_accueil.java (my fragment activity)

//import.....
public class AccueilFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;
int score = 0;
TextView t1, t2, t3,t4;
ImageView img;

private OnFragmentInteractionListener mListener;

public AccueilFragment() {
}

public static AccueilFragment newInstance(String param1, String param2) {
    AccueilFragment fragment = new AccueilFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_accueil, container, false);

    t1 = (TextView) view.findViewById(R.id.tvName);
    t2 = (TextView) view.findViewById(R.id.tvDateOfBirth);
    t3 = (TextView) view.findViewById(R.id.tvHeight);
    t3 = (TextView) view.findViewById(R.id.tvCountry);
    img = (ImageView) view.findViewById(R.id.ivImage);
    ArrayList actorsList = new ArrayList<Actors>();

    ListView listview = (ListView) view.findViewById(R.id.list);
    ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);

    listview.setAdapter(adapter);

    new getData().execute();

    return view;

}

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

class getData extends AsyncTask<String, String, String> {

    HttpURLConnection urlConnection;

    @Override
    protected String doInBackground(String... args) {

        StringBuilder result = new StringBuilder();

        try {
            URL url = new URL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }

        return result.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jsono = new JSONObject(result);
            JSONArray jarray = jsono.getJSONArray("actors");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

                Actors actor = new Actors();

                actor.setName(object.getString("name"));
                actor.setDescription(object.getString("description"));
                actor.setDob(object.getString("dob"));
                actor.setCountry(object.getString("country"));
                actor.setHeight(object.getString("height"));
                actor.setSpouse(object.getString("spouse"));
                actor.setChildren(object.getString("children"));
                actor.setImage(object.getString("image"));

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
public interface OnFragmentInteractionListener {

    void onFragmentInteraction(Uri uri);
}

}

What's the problem and how to fix that ? thanks

Body:
Are you adding the ListView in your fragment that you want it to be displayed for example:

public class FragmentMain extends Fragment
{
    private ListView listView; //Define the list view up here.

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Set the listview equal to the fragment name
    listView = inflater.inflate(R.layout.fragment_name, container, false);

    }
}

This should work, let me know if otherwize :)


问:
ArrayList's instantiating of the inner T[] array
I've found out that if you have a generic class with an array that depends of type parameter of that class, you can't initialize that array in a usual way:

```<code>class Foo<T>  {
    private T[] a;

    Foo()  {
       a=new T[5]; //doesn't compile
    }
}
</code>```

You can only do something like this:

```<code>class Foo<T>  {
        private T[] a;

        Foo(T[] a)  {
           this.a=a;
        }
    }
</code>```

But this code is possible:

```<code>ArrayList<Integer> list=new ArrayList<>();
</code>```

Why? How does the ArrayList overcome that thing? I've looked into its code but couldn't figure it out. It seems like it just stores things in Object[] array which seems wrong.

答:
The array inside ArrayList is always of type Object[], because you can store anything inside such an array. The type argument enables type safety none the less on a method level and this is what matters.

Edit to address the topic of type erasure as requested:

Type erasure in Java means that generic type arguments are only present during compile time, where it matters most to ensure type safety. Generics have been implemented this way to keep newer versions of Java compatible to older ones.

The drawback of this is that one can never instantiate a generic type, because it is never known at runtime.

Body:
I've found out that if you have a generic class with an array that depends of type parameter of that class, you can't initialize that array in a usual way:

class Foo<T>  {
    private T[] a;

    Foo()  {
       a=new T[5]; //doesn't compile
    }
}

You can only do something like this:

class Foo<T>  {
        private T[] a;

        Foo(T[] a)  {
           this.a=a;
        }
    }

But this code is possible:

ArrayList<Integer> list=new ArrayList<>();

Why? How does the ArrayList overcome that thing? I've looked into its code but couldn't figure it out. It seems like it just stores things in Object[] array which seems wrong.


问:
Filter column / row data in matrix through user input - matlab
I have an N x 3 matrix (double) with values in third column going in the interval 1:4, and only those four values. This matrix is saved as 'data', and will be used for further analysis after this filtering with the same name.

How can I through user input (not popup) sort the rows with several conditions, eg I want to filter for rows with third column values with numbers 1 and 3 (or 1 and 2, or 1 and 2 and 4, or only 3 and so on)?

I also have to take care of displaying an error message on invalid input (eg input is empty or invalid number like '6' as well as combinations of wrong inputs like filtering for '1', '2' and '7') and letting the user retry the input.

I am using matlab.

The matrix could look something like this

```<code>42.34 0.73713 1
25.387 0.8774 1
57.187 0.388 2
37.458 0.7095 2
34.227 0.6929 2
47.837 0.61363 2
30.852 0.65929 2
51.329 0.50498 3
29.501 0.77894 3
34.895 0.80504 3
26.243 0.73048 3
22.311 0.65362 3
14.769 0.17958 4
17.326 0.23037 4
41.557 0.38979 4
</code>```

Body:
I have an N x 3 matrix (double) with values in third column going in the interval 1:4, and only those four values. This matrix is saved as 'data', and will be used for further analysis after this filtering with the same name.

How can I through user input (not popup) sort the rows with several conditions, eg I want to filter for rows with third column values with numbers 1 and 3 (or 1 and 2, or 1 and 2 and 4, or only 3 and so on)?

I also have to take care of displaying an error message on invalid input (eg input is empty or invalid number like '6' as well as combinations of wrong inputs like filtering for '1', '2' and '7') and letting the user retry the input.

I am using matlab.

The matrix could look something like this

42.34 0.73713 1
25.387 0.8774 1
57.187 0.388 2
37.458 0.7095 2
34.227 0.6929 2
47.837 0.61363 2
30.852 0.65929 2
51.329 0.50498 3
29.501 0.77894 3
34.895 0.80504 3
26.243 0.73048 3
22.311 0.65362 3
14.769 0.17958 4
17.326 0.23037 4
41.557 0.38979 4

Body:
I this could work. The input could be a number or a vector, for example 1, [1 2] or [1:3]

filter=[];

while isempty(filter) || ~isvector(filter) || ischar(filter)
    filter=input('Enter rows to filter: ')
end

index=[];

m=[[42.34 0.73713 1];
[25.387 0.8774 1];
[57.187 0.388 2];
[37.458 0.7095 2];
[34.227 0.6929 2];
[47.837 0.61363 2];
[30.852 0.65929 2];
[51.329 0.50498 3];
[29.501 0.77894 3];
[34.895 0.80504 3];
[26.243 0.73048 3];
[22.311 0.65362 3];
[14.769 0.17958 4];
[17.326 0.23037 4];
[41.557 0.38979 4]]

for i=1:numel(filter)
    index=[index find(m(:,3)==filter(i))'];
end

m2=m(index,:)

You can change the matrix definition for any matrix loaded as you stated in your question.


问:
How to overwrite Woocommerce template using Avada Child Theme
I need to overwrite my-account Woocommerce template. In order to do so using child theme I tried the following solutions:

copied my-account.php file from woocommerce/templates into wp-content/themes/Avada-Child-Theme/woocommerce/myaccount

in line 9 (just below comments) of my-account.php added this line:

```<code>die('test');
</code>```

no expected result (message 'test').

Also tried the above with my-account.php file located in

wp-content/themes/Avada-Child-Theme/woocommerce/templates/myaccount

no expected result.

Also tried the above with folder:

```<code>wp-content/themes/Avada/woocommerce/myaccount
</code>```

no expected result.

Also tried the above within folder:

```<code> wp-content/plugins/woocommerce/templates/myaccount
</code>```

and this worked, but it is not a good practice.

What I am doing wrong?

I am using WP 4.1, Woocommerce 2.2.10 and Avada Theme 3.7.2 with Avada Child Theme installed and active.

Regarding point 1. on System Status Woocommerce page I see this:

```<code>Avada/woocommerce/cart/cart.php,
Avada/woocommerce/cart/shipping-calculator.php,
Avada/woocommerce/checkout/form-checkout.php,
Avada/woocommerce/checkout/review-order.php,
Avada/woocommerce/checkout/thankyou.php,
Avada/woocommerce/content-product.php,
Avada/woocommerce/loop/loop-start.php,
Avada/woocommerce/loop/pagination.php,
Avada/woocommerce/myaccount/form-edit-address.php,
Avada-Child-Theme/woocommerce/myaccount/my-account.php,
Avada/woocommerce/single-product/add-to-cart/variable.php,
Avada/woocommerce/single-product/product-image.php,
Avada/woocommerce/single-product/product-thumbnails.php,
Avada/woocommerce/single-product/short-description.php,
Avada/woocommerce/single-product/tabs/description.php,
Avada/woocommerce/single-product/title.php
</code>```

So, it seems to be ok, but my changes do not affect the template. I also tried to make other changes, like adding some text inside p html tag - no effect.

Please help!

EDIT:

I generated list of active plugins:

```<code>` [0]=>  string(29) "gravityforms/gravityforms.php"
  [1]=>  string(27) "LayerSlider/layerslider.php"
  [2]=>  string(25) "duplicator/duplicator.php"
  [3]=>  string(27) "fusion-core/fusion-core.php"
  [4]=>  string(58) "gravity-forms-css-ready-selector/gf-readyclasses-addon.php"
  [5]=>  string(23) "revslider/revslider.php"
  [6]=>  string(21) "woochimp/woochimp.php"
  [7]=>  string(49) "woocommerce-customizer/woocommerce-customizer.php"
  [8]=>  string(71) "woocommerce-gravityforms-product-addons/gravityforms-product-addons.php"
  [9]=>  string(51) "woocommerce-pdf-invoice/woocommerce-pdf-invoice.php"
  [10]=>  string(65) "woocommerce-points-and-rewards/woocommerce-points-and-rewards.php"
  [11]=>  string(61) "woocommerce-product-details-customiser/details-customiser.php"
  [12]=>  string(27) "woocommerce/woocommerce.php"
  [13]=>  string(39) "woothemes-updater/woothemes-updater.php"`
</code>```

答:
Since the theme Avada is always up to date with the latest and also upcoming releases of WooCommerce they setup a compatability folder for the release about to be old. At the time of this writing 2.7 is about to come out and Avada has created a folder called compatability inside the folder woocommerce. Under that folder the version about to be old is represented with a folder, in this instance a folder named 2.6 exists by default.

Inside the class Avada_WooCommerce you can find the filter called woocommerce_template_path that is hooked into by Avada, defining a function that checks if the current version is 2.7 or 2.6 and returning the path to the template folder. Since 2.7 is not yet released, 2.6 is running and for that, the folder is set to woocommerce/compatability/2.6.

So if you are running 2.6 and want to override the templates in your child-theme, create a folder in your child-theme folder that is called woocommerce/compatability/2.6 and place your overriding templates there.

If you then upgrade to WooCommerce 2.7 when it comes out, remember to place the overriding templates in the usual folder, woocommerce.

Took me some time to figure out and I hope it helps!

Body:
I need to overwrite my-account Woocommerce template. In order to do so using child theme I tried the following solutions:

copied my-account.php file from woocommerce/templates into wp-content/themes/Avada-Child-Theme/woocommerce/myaccount

in line 9 (just below comments) of my-account.php added this line:

die('test');

no expected result (message 'test').

Also tried the above with my-account.php file located in

wp-content/themes/Avada-Child-Theme/woocommerce/templates/myaccount

no expected result.

Also tried the above with folder:

wp-content/themes/Avada/woocommerce/myaccount

no expected result.

Also tried the above within folder:

 wp-content/plugins/woocommerce/templates/myaccount

and this worked, but it is not a good practice.

What I am doing wrong?

I am using WP 4.1, Woocommerce 2.2.10 and Avada Theme 3.7.2 with Avada Child Theme installed and active.

Regarding point 1. on System Status Woocommerce page I see this:

Avada/woocommerce/cart/cart.php,
Avada/woocommerce/cart/shipping-calculator.php,
Avada/woocommerce/checkout/form-checkout.php,
Avada/woocommerce/checkout/review-order.php,
Avada/woocommerce/checkout/thankyou.php,
Avada/woocommerce/content-product.php,
Avada/woocommerce/loop/loop-start.php,
Avada/woocommerce/loop/pagination.php,
Avada/woocommerce/myaccount/form-edit-address.php,
Avada-Child-Theme/woocommerce/myaccount/my-account.php,
Avada/woocommerce/single-product/add-to-cart/variable.php,
Avada/woocommerce/single-product/product-image.php,
Avada/woocommerce/single-product/product-thumbnails.php,
Avada/woocommerce/single-product/short-description.php,
Avada/woocommerce/single-product/tabs/description.php,
Avada/woocommerce/single-product/title.php

So, it seems to be ok, but my changes do not affect the template. I also tried to make other changes, like adding some text inside p html tag - no effect.

Please help!

EDIT:

I generated list of active plugins:

` [0]=>  string(29) "gravityforms/gravityforms.php"
  [1]=>  string(27) "LayerSlider/layerslider.php"
  [2]=>  string(25) "duplicator/duplicator.php"
  [3]=>  string(27) "fusion-core/fusion-core.php"
  [4]=>  string(58) "gravity-forms-css-ready-selector/gf-readyclasses-addon.php"
  [5]=>  string(23) "revslider/revslider.php"
  [6]=>  string(21) "woochimp/woochimp.php"
  [7]=>  string(49) "woocommerce-customizer/woocommerce-customizer.php"
  [8]=>  string(71) "woocommerce-gravityforms-product-addons/gravityforms-product-addons.php"
  [9]=>  string(51) "woocommerce-pdf-invoice/woocommerce-pdf-invoice.php"
  [10]=>  string(65) "woocommerce-points-and-rewards/woocommerce-points-and-rewards.php"
  [11]=>  string(61) "woocommerce-product-details-customiser/details-customiser.php"
  [12]=>  string(27) "woocommerce/woocommerce.php"
  [13]=>  string(39) "woothemes-updater/woothemes-updater.php"`


问:
SVN: Merging two branches together
We have multiple developers working on a project. We're employing a feature-branch method of branching in which we do the following:

All maintenance work and bug fixes are done on the trunk

All new functionality is done on a new branch

Branch is updated regularly (via merging changes from trunk to branch)

However, we've run into a situation that 2 branches [we'll call them feature-branch-1 and feature-branch-2] need to be merged together. What is the best way to accomplish this? Part of me thinks we should create a new branch. Then, merge that branch with the first feature branch [feature-branch-1]. And then merge with the second feature branch [feature-branch-2] and take care of the conflicts (which will most likely be the project files).

Is there a better way?

Thanks guys!

答:
I assume you regularly merge the trunk and the branches, don't you? If so, after that merge, the trunk and the branches are the same and you can just drop one of the branches and continue using the other one. </p>

<p>If you don't want to merge to the trunk, you can still merge one branch into the second and continue using the second. </p>

ContentLicense: CC BY-SA 2.5

Title: SVN: Merging two branches together

Body:
I assume you regularly merge the trunk and the branches, don't you? If so, after that merge, the trunk and the branches are the same and you can just drop one of the branches and continue using the other one.

If you don't want to merge to the trunk, you can still merge one branch into the second and continue using the second.


问:
JavaScript Palindrome
I found a solution on how to write palindrome in StackOverFlow. This is the code snippet:

```<code>function palindrome(str) {
    var len = str.length;
    for ( var i = 0; i < Math.floor(len/2); i++ ) {
        if (str[i] !== str[len - 1 - i]) {   //Problem in this line
            return false;
        }
    }
    return true;
}
</code>```

I understand every line except the one I have here. Can anyone please break it down for me? Thanks in advance!

答:
str[i] represents the (i+1)th character in str. If str is a palindrome then this character must be equal to the character that is i positions from the end of the string (by definition).

The last character in a string is at position len - 1 (since len was defined as being the length of the string, and indexes start counting from 0). So you need to subtract i from that to arrive at the position where the character sits that should be the same as str[i]. Hence str[len - 1 - i]

The comparison is made with !==, i.e. not-equal. In that case we know for sure we do not have a palindrome and can exit with false.

Title: JavaScript Palindrome

Body:
I found a solution on how to write palindrome in StackOverFlow. This is the code snippet:

function palindrome(str) {
    var len = str.length;
    for ( var i = 0; i < Math.floor(len/2); i++ ) {
        if (str[i] !== str[len - 1 - i]) {   //Problem in this line
            return false;
        }
    }
    return true;
}

I understand every line except the one I have here. Can anyone please break it down for me? Thanks in advance!


问:
Draw table over image in HTML to save my life
I'm trying to make a HTML page, but I don't know anything about devlopment.

I need to transform this image into an html page, replacing the black blocks with dinamic texts.

I tryed to learn html tables, divs, etc... but its not for me, really.

This page need to be centered on browser, because I'll send it on e-mails.

Can someone help me, please?

答: I think you really need to step back and take the time to learn some basics about working with html.  I notice you say you need to email the page, does that mean you're really trying to build just an email template rather than a website?  The two are similar, but have some different considerations.  Either way, I'd suggest looking at a site similar to http://ccm.net/faq/173-how-to-create-your-own-website to try and understand the very basics first, as otherwise your question is really very broad. </p>


问:
Python equivalent of the MATLAB psf2otf function
Is there a Python equivalent to the MATLAB psf2otf function?

This is a link to the MATLAB function's documentation.

EDIT:

A document found online with more information on this:
https://arxiv.org/abs/1809.04187

答:
The phypher library has functions that achieve the same thing:

https://github.com/aboucaud/pypher/blob/master/pypher/pypher.py