问:
How to get only songs from itunes library with itlibrary.h
This is the way the docs say to get all media items from library, however I want to get only the songs.

```<code>#import <iTunesLibrary/ITLibrary.h>

ITLibrary *library = [ITLibrary libraryWithAPIVersion:@"1.0" error:&error];
if (library)
{
    tracks = library.allMediaItems; //  <- NSArray of ITLibMediaItem
}
</code>```

I found this answer: How to get all tracks from an album using iTunes.h/Scripting Bridge

I'm not sure how to adapt it to do what I need it to, or maybe it is less complicated now?

答:
tracks = library.allMediaItems; is a NSArray of ITLibMediaItem objects.

According to the doc, it as a property mediaKind that gives it the item is a song (ITLibMediaItemMediaKindSong) or another kind of media.

So, you just have to use the predicate:

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"mediaKind == %d", ITLibMediaItemMediaKindSong]]
</code>```

So to filter (with previous predicate)

```<code>tracks = [library.allMediaItems filteredArrayUsingPredicate:predicate];
</code>```

Body:
This is the way the docs say to get all media items from library, however I want to get only the songs.

#import <iTunesLibrary/ITLibrary.h>

ITLibrary *library = [ITLibrary libraryWithAPIVersion:@"1.0" error:&error];
if (library)
{
    tracks = library.allMediaItems; //  <- NSArray of ITLibMediaItem
}

I found this answer: How to get all tracks from an album using iTunes.h/Scripting Bridge

I'm not sure how to adapt it to do what I need it to, or maybe it is less complicated now?

Body:
tracks = library.allMediaItems; is a NSArray of ITLibMediaItem objects.

According to the doc, it as a property mediaKind that gives it the item is a song (ITLibMediaItemMediaKindSong) or another kind of media.

So, you just have to use the predicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"mediaKind == %d", ITLibMediaItemMediaKindSong]]

So to filter (with previous predicate)

tracks = [library.allMediaItems filteredArrayUsingPredicate:predicate];


来源: stackexchange

问:
How would I call only one variable from a function that contains multiple variables?
So basically I am trying to create a hangman game, and as of right now I'm just trying to pass a variable from one function to another, though I'm confused on how to do so, here is my code:

```<code>import random

print("Welcome to Hangman!")

def wordSelection():
  words = ["test", "random"]
  wordChoice = random.randint(0, 1)
  selectedWord = words[wordChoice]
  print(selectedWord)
  return selectedWord

def guessWord():
  selectedWord = wordSelection()
  print(selectedWord)

wordSelection()
guessWord()
</code>```

The question I have is basically, how am I able to call the variable 'selectedWord' from the wordSelection function and pass it into the guessWord() function?

I tried to at the bottom as you can see, however I just called the whole function again, instead of only specifically getting selectedWord rather than the whole function.

What could I do to ONLY get 'selectedWord' from WordSelection() rather than just getting the whole function - is this possible?

答:
You are returning the selectedWord value from wordSelection() so you can just directly use it in your code. Although, i don't understand what are you trying to accomplish with this as guessWord function is redundant.

You can do something like this :

```<code>guessWord(wordSelection())
</code>```

and define guessWord function like this :

```<code>guessWord(words) :
</code>```

This will pass the value returned by wordSelection() i.e. value of selectedWord in function guessWord().

ContentLicense: CC BY-SA 3.0

Body:
So basically I am trying to create a hangman game, and as of right now I'm just trying to pass a variable from one function to another, though I'm confused on how to do so, here is my code:

import random

print("Welcome to Hangman!")

def wordSelection():
  words = ["test", "random"]
  wordChoice = random.randint(0, 1)
  selectedWord = words[wordChoice]
  print(selectedWord)
  return selectedWord

def guessWord():
  selectedWord = wordSelection()
  print(selectedWord)

wordSelection()
guessWord()

The question I have is basically, how am I able to call the variable 'selectedWord' from the wordSelection function and pass it into the guessWord() function?

I tried to at the bottom as you can see, however I just called the whole function again, instead of only specifically getting selectedWord rather than the whole function.

What could I do to ONLY get 'selectedWord' from WordSelection() rather than just getting the whole function - is this possible?

Body:
You are returning the selectedWord value from wordSelection() so you can just directly use it in your code. Although, i don't understand what are you trying to accomplish with this as guessWord function is redundant.

You can do something like this :

guessWord(wordSelection())

and define guessWord function like this :

guessWord(words) :

This will pass the value returned by wordSelection() i.e. value of selectedWord in function guessWord().


问:
How can I find words in matrix of letters
This is another question I was asked in the telephonic interview:

Given a dictionary and a crossword(2d matrix of characters) find all the dictionary words which can be found in the crossword.

All I could think of was hash the dictionary, find every possible word in the crossword and search the hash. I could not optimize it all.

Must admit Microsoft interview questions are tough :(

Please give me the lines to think on.

答:
What was wrong with your answer?

A dictionary is sorted so I think I'd arrange the dictionary words into a prefix trie. This would help since there are probably lots of words where the prefix is also a word. The sorting helps (minimally) with the build time.

Then walk the crossword looking at all possible words. As you extract the characters of a potential word, you are walking down the trie - so you'll find the first word starting with a certain set of characters, but also be in the right place to continue to find other words starting with the same characters

ContentLicense: CC BY-SA 2.5


问:
read pixel value in bmp file
How can I read the color value of 24bit BMP images at all the pixel [h*w] in C or C++ on Windows [better without any 3rd party library]. I got Dev-C++

A working code will be really appreciated as I've never worked on Image reading & have come to SO after Googling [if you can google better than me, plz provide a link].

答:
I can't comment on the top level answer because I don't have enough stackoverflow rep yet, but I just wanted to point out one very critical bug with that implementation.

Some bitmaps can be written with a negative height, so when you try to allocate your image data buffer, your code will crash with std::bad_alloc. Bitmaps with negative height means that the image data is stored top to bottom instead of the traditional bottom to top. Therefore, a slightly better version of the top level answer is (still not including portability for systems with different endianness and size of bytes):

```<code>unsigned char* readBMP(char* filename)
{
    int i;
    FILE* f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

    // extract image height and width from header
    int width, height;
    memcpy(&width, info + 18, sizeof(int));
    memcpy(&height, info + 22, sizeof(int));

    int heightSign = 1;
    if (height < 0){
        heightSign = -1;
    }

    int size = 3 * width * abs(height);
    unsigned char* data = new unsigned char[size]; // allocate 3 bytes per pixel
    fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
    fclose(f);

    if(heightSign == 1){
        for(i = 0; i < size; i += 3)
        {
            //code to flip the image data here....
        }
    }
    return data;
}
</code>```

Title: read pixel value in bmp file

Body:
I can't comment on the top level answer because I don't have enough stackoverflow rep yet, but I just wanted to point out one very critical bug with that implementation.

Some bitmaps can be written with a negative height, so when you try to allocate your image data buffer, your code will crash with std::bad_alloc. Bitmaps with negative height means that the image data is stored top to bottom instead of the traditional bottom to top. Therefore, a slightly better version of the top level answer is (still not including portability for systems with different endianness and size of bytes):

unsigned char* readBMP(char* filename)
{
    int i;
    FILE* f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

    // extract image height and width from header
    int width, height;
    memcpy(&width, info + 18, sizeof(int));
    memcpy(&height, info + 22, sizeof(int));

    int heightSign = 1;
    if (height < 0){
        heightSign = -1;
    }

    int size = 3 * width * abs(height);
    unsigned char* data = new unsigned char[size]; // allocate 3 bytes per pixel
    fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
    fclose(f);

    if(heightSign == 1){
        for(i = 0; i < size; i += 3)
        {
            //code to flip the image data here....
        }
    }
    return data;
}

ContentLicense: CC BY-SA 4.0


问:
CarrierWave not uploading (after upgrade)
A month back I upgraded my Ruby version on RoR-app from 1.9.3 to 2.3.3. I have been successfully using fog & carrierwave to upload images to Amazon S3 before that but after the upgrade it stopped working. It does not upload my images to S3 any longer, the folders and files are not created there. What makes this so problematic is that I cannot troubleshoot it at all, I get no error messages or anything.

Versions:

fog 1.38.0

carrierwave 1.0.0

ruby 2.3.3

rails 4.1.13

Useful information:

I have tried fog/aws and carrierwave-aws with the same (failing) result

If I change the AWS credentials to something obviously false, the same problem occurs. I.e., it seems like there could be something wrong with the CarrierWave config file, or that it is not loaded or something

The objects (Gift) are being saved properly

I have not done any changes on Amazon, as far as I know.

I have tried to swith to another set of AWS Access key and id but with the same problem.

I am using AssetSync on the same app (with the same credentials) to upload to AWS and this works! I.e. there shouldn't be something wrong with AWS/S3.

initializers/carrierwave.rb

```<code>CarrierWave.configure do |config|
  config.storage = 'fog'
  config.fog_credentials = {
    :provider               => 'AWS',
    :aws_access_key_id      => 'ABC123CODE',
    :aws_secret_access_key  => '+ABC123CODEKEY',
    :region                 => 'eu-central-1'
  }
  config.fog_directory  = 'myapp-se'
  config.cache_dir = "#{Rails.root}/tmp"

  config.fog_attributes = {
    expires: 1.year.from_now.httpdate,
    cache_control: "max-age=#{1.year.to_i}"
  }

  config.ignore_integrity_errors = false
  config.ignore_processing_errors = false
  config.ignore_download_errors = false

end
</code>```

Gift-model (gift.rb) - (related part)

```<code>  mount_uploader :cached_image, GiftImageUploader
  #validates_integrity_of :cached_image
  #validates_processing_of :cached_image
  validates_integrity_of :cached_image
  validates_processing_of :cached_image
  validates_download_of :cached_image

    file = Tempfile.new(["image", ".jpg"])
    file.binmode

    begin
      open(URI.parse(external_image_url), :allow_redirections => :safe) do |data|
        file.write data.read
      end
    rescue Exception => e
      logger.info "Error fetching image for product #{id}: " + e.message
      return false
    end

    file.rewind

    self.cached_image = file
    begin
      self.skip_callbacks = true
      if self.save!
        logger.info "Successfully cached image for product #{id}"
        return true
      else
        logger.info "Soft Error saving product #{id}"
        return false
      end
      self.skip_callbacks = false
    rescue Exception => e
      logger.info "Rescue Error saving product #{id}" + e.message
    end
</code>```

Uploader file

```<code>class GiftImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :fog

  def store_dir
    "cached/gifts/#{model.id}"
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  version :s300 do
    process resize_to_fit: [300, 300]
  end

  version :s200, :from_version => :s300 do
    process resize_to_fit: [200, 200]
  end

  version :s150, :from_version => :s200 do
    process resize_to_fit: [150, 150]
  end

  version :sq150 do
    process resize_to_fill: [150, 150]
  end

  version :s75, :from_version => :s150 do
    process resize_to_fit: [75, 75]
  end

  version :sq75 do
    process resize_to_fill: [75, 75]
  end

end
</code>```

What I need help with:

Since my major issue is that this all fails silently, I cannot even begin to troubleshoot the function. Any suggestion on how I could trial-and-error troubleshoot this app until I can get some information on the error would be highly appreciated.

If you can see anything in the code that would solve the problem would of course be really useful as well!

答: You need to run bundle install command before starting application. If it doesn't work, run bundle update followed by bundle install. It should work, as I also faced similar issue in past.

Body:
A month back I upgraded my Ruby version on RoR-app from 1.9.3 to 2.3.3. I have been successfully using fog & carrierwave to upload images to Amazon S3 before that but after the upgrade it stopped working. It does not upload my images to S3 any longer, the folders and files are not created there. What makes this so problematic is that I cannot troubleshoot it at all, I get no error messages or anything.

Versions:

fog 1.38.0

carrierwave 1.0.0

ruby 2.3.3

rails 4.1.13

Useful information:

I have tried fog/aws and carrierwave-aws with the same (failing) result

If I change the AWS credentials to something obviously false, the same problem occurs. I.e., it seems like there could be something wrong with the CarrierWave config file, or that it is not loaded or something

The objects (Gift) are being saved properly

I have not done any changes on Amazon, as far as I know.

I have tried to swith to another set of AWS Access key and id but with the same problem.

I am using AssetSync on the same app (with the same credentials) to upload to AWS and this works! I.e. there shouldn't be something wrong with AWS/S3.

initializers/carrierwave.rb

CarrierWave.configure do |config|
  config.storage = 'fog'
  config.fog_credentials = {
    :provider               => 'AWS',
    :aws_access_key_id      => 'ABC123CODE',
    :aws_secret_access_key  => '+ABC123CODEKEY',
    :region                 => 'eu-central-1'
  }
  config.fog_directory  = 'myapp-se'
  config.cache_dir = "#{Rails.root}/tmp"

  config.fog_attributes = {
    expires: 1.year.from_now.httpdate,
    cache_control: "max-age=#{1.year.to_i}"
  }

  config.ignore_integrity_errors = false
  config.ignore_processing_errors = false
  config.ignore_download_errors = false

end

Gift-model (gift.rb) - (related part)

  mount_uploader :cached_image, GiftImageUploader
  #validates_integrity_of :cached_image
  #validates_processing_of :cached_image
  validates_integrity_of :cached_image
  validates_processing_of :cached_image
  validates_download_of :cached_image

    file = Tempfile.new(["image", ".jpg"])
    file.binmode

    begin
      open(URI.parse(external_image_url), :allow_redirections => :safe) do |data|
        file.write data.read
      end
    rescue Exception => e
      logger.info "Error fetching image for product #{id}: " + e.message
      return false
    end

    file.rewind

    self.cached_image = file
    begin
      self.skip_callbacks = true
      if self.save!
        logger.info "Successfully cached image for product #{id}"
        return true
      else
        logger.info "Soft Error saving product #{id}"
        return false
      end
      self.skip_callbacks = false
    rescue Exception => e
      logger.info "Rescue Error saving product #{id}" + e.message
    end

Uploader file

class GiftImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :fog

  def store_dir
    "cached/gifts/#{model.id}"
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  version :s300 do
    process resize_to_fit: [300, 300]
  end

  version :s200, :from_version => :s300 do
    process resize_to_fit: [200, 200]
  end

  version :s150, :from_version => :s200 do
    process resize_to_fit: [150, 150]
  end

  version :sq150 do
    process resize_to_fill: [150, 150]
  end

  version :s75, :from_version => :s150 do
    process resize_to_fit: [75, 75]
  end

  version :sq75 do
    process resize_to_fill: [75, 75]
  end

end

What I need help with:

Since my major issue is that this all fails silently, I cannot even begin to troubleshoot the function. Any suggestion on how I could trial-and-error troubleshoot this app until I can get some information on the error would be highly appreciated.

If you can see anything in the code that would solve the problem would of course be really useful as well!


问:
MQTT.js: How to close / connect to another broker after failed connection attempt? (for using bridged mosquitto)
I did set up two mosquitto broker with websocket support and am able to connect to them with mqtt.js

Now I tried to implement a fault-prove version with an array of possible mqtt brokers, which should be tried to connect to in order until a successful connection. If a connection fails, the next broker should be tried... so far so good, but if i try to connect to an offline broker, somehow mqtt.js tries to reconnect endlessly. I am not able to close the connection attempt and connect to the next one.

var client = mqtt.connect("ws://firstbrokerip:9001");

client.on('connect', function() {
 //consoleLog("[BROWSER] MQTT js-Client:"," Connected","green");
 client.subscribe("testchannel");
});

client.on('offline', function() {
 //consoleLog("[BROWSER] MQTT js-Client:", ' Offline',"red");
  client.end();
 client = mqtt.connect("ws://secondbrokerip:9001");
});```

Any ideas of how can I close the connection and connect to the next ?
(Plz don't care about the custom ConsoleLog function)

答:
You don't need to implement fail over, it's baked into the module:

From the mqtt.js doc (https://github.com/mqttjs/MQTT.js#connect)

You can also specify a servers options with content: [{ host:
  'localhost', port: 1883 }, ... ], in that case that array is iterated
  at every connect.

So you pass the connect method options object with a key called servers which is an array of brokers to connect to.

```<code>client = mqtt.connect({
  servers: [
    {
      host: 'firstbroker.ip',
      port: 9001,
      protocol: 'ws'
    },
    {
      host: 'secondbroker.ip',
      port: 9001,
      protocol: 'ws'
    }
  ]
});
</code>```

Body:
I did set up two mosquitto broker with websocket support and am able to connect to them with mqtt.js

Now I tried to implement a fault-prove version with an array of possible mqtt brokers, which should be tried to connect to in order until a successful connection. If a connection fails, the next broker should be tried... so far so good, but if i try to connect to an offline broker, somehow mqtt.js tries to reconnect endlessly. I am not able to close the connection attempt and connect to the next one.

var client = mqtt.connect("ws://firstbrokerip:9001");

client.on('connect', function() {
 //consoleLog("[BROWSER] MQTT js-Client:"," Connected","green");
 client.subscribe("testchannel");
});

client.on('offline', function() {
 //consoleLog("[BROWSER] MQTT js-Client:", ' Offline',"red");
  client.end();
 client = mqtt.connect("ws://secondbrokerip:9001");
});

Any ideas of how can I close the connection and connect to the next ?
(Plz don't care about the custom ConsoleLog function)

Body:
You don't need to implement fail over, it's baked into the module:

From the mqtt.js doc (https://github.com/mqttjs/MQTT.js#connect)

You can also specify a servers options with content: [{ host:
  'localhost', port: 1883 }, ... ], in that case that array is iterated
  at every connect.

So you pass the connect method options object with a key called servers which is an array of brokers to connect to.

client = mqtt.connect({
  servers: [
    {
      host: 'firstbroker.ip',
      port: 9001,
      protocol: 'ws'
    },
    {
      host: 'secondbroker.ip',
      port: 9001,
      protocol: 'ws'
    }
  ]
});


问:
Incorrect DECIMAL value when inserting MySQL
The error I'm getting is:

ERROR 1366 (HY000): Incorrect DECIMAL value: '0' for column '' at row
  -1

I'm trying to normalize a database and ensuring that the data types are correct. Inserting data from BASE_TABLE into a new table named Inventors.

This is the query I'm using to insert. If I take a single row manually from the select query it can correctly insert into the Inventors table.

However, running the query like this I instantly get the error above.

```<code>INSERT INTO
    Inventors(ID,Firstname,Middlename,Lastname,Country,Latitude,Longitude)
SELECT DISTINCT
    Inventor_ID as ID,
    Firstname,
    Middlename,
    Lastname,
    Country,
    cast(Latitude as decimal(11,6)) as Latitude,
    cast(Longitude as decimal(11,6)) as Longitude
FROM
    BASE_TABLE
</code>```

Here is the row which fails to insert in the select query:

```<code>ID          Firstname   Middlename  Lastname    Country     Latitude    Longitude
04308666-3  RICHARD     RICHARD     JUNG                    0.000000    0.000000
</code>```

Inventors create query:

```<code>CREATE TABLE `Inventors` (
  `ID` varchar(55) NOT NULL DEFAULT '',
  `Firstname` varchar(255) DEFAULT NULL,
  `Middlename` varchar(255) DEFAULT NULL,
  `Lastname` varchar(255) DEFAULT NULL,
  `Country` varchar(255) DEFAULT NULL,
  `Latitude` decimal(11,8) DEFAULT NULL,
  `Longitude` decimal(11,8) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

BASE_TABLE create query:

```<code>CREATE TABLE `BASE_TABLE` (
  `Firstname` varchar(255) DEFAULT NULL,
  `Middlename` varchar(255) DEFAULT NULL,
  `Lastname` varchar(255) DEFAULT NULL,
  `Country` varchar(255) DEFAULT NULL,
  `Zipcode` varchar(255) DEFAULT NULL,
  `Latitude` varchar(255) DEFAULT NULL,
  `Longitude` varchar(255) DEFAULT NULL,
  `InvSeq` int(11) DEFAULT NULL,
  `Patent` varchar(255) DEFAULT NULL,
  `AppYear` year(4) DEFAULT NULL,
  `ApplyYear` year(4) DEFAULT NULL,
  `PubYear` year(4) NOT NULL,
  `AppDate` varchar(255) DEFAULT NULL,
  `Assignee` varchar(255) DEFAULT NULL,
  `AsgNum` varchar(255) DEFAULT NULL,
  `Class` varchar(255) DEFAULT NULL,
  `Coauthor` varchar(255) DEFAULT NULL,
  `Invnum` varchar(255) DEFAULT NULL,
  `Invnum_N` varchar(255) DEFAULT NULL,
  `Record_ID` varchar(255) NOT NULL,
  `Inventor_ID` varchar(255) DEFAULT NULL,
  `Match_Level` tinyint(4) DEFAULT NULL,
  `Company_ID` varchar(255) DEFAULT NULL,
  `Classification` varchar(255) DEFAULT NULL,
  `Citing` mediumint(9) DEFAULT NULL,
  `Cited` mediumint(9) DEFAULT NULL,
  PRIMARY KEY (`Record_ID`),
  KEY `Inventor_ID` (`Inventor_ID`),
  KEY `Patent` (`Patent`),
  KEY `Patent_2` (`Patent`,`Inventor_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

Can anyone help me on this issue?

答:
I found the problem. Latitude (VARCHAR) and Longitude (VARCHAR) in BASE_TABLE had the value of an empty string ''. This caused MySQL to cast to an incorrect value for some reason.

I solved this by replacing the empty string with NULL in the select query (See below).

```<code>INSERT INTO
    Inventors
SELECT DISTINCT
    Inventor_ID as ID,
    Firstname,
    Middlename,
    Lastname,
    Country,
    IF(Latitude='',NULL,CAST(Latitude as decimal(11,6))) as Latitude,
    IF(Longitude='',NULL,CAST(Longitude as decimal(11,6))) as Longitude
FROM
    BASE_TABLE
</code>```

Body:
The error I'm getting is:

ERROR 1366 (HY000): Incorrect DECIMAL value: '0' for column '' at row
  -1

I'm trying to normalize a database and ensuring that the data types are correct. Inserting data from BASE_TABLE into a new table named Inventors.

This is the query I'm using to insert. If I take a single row manually from the select query it can correctly insert into the Inventors table.

However, running the query like this I instantly get the error above.

INSERT INTO
    Inventors(ID,Firstname,Middlename,Lastname,Country,Latitude,Longitude)
SELECT DISTINCT
    Inventor_ID as ID,
    Firstname,
    Middlename,
    Lastname,
    Country,
    cast(Latitude as decimal(11,6)) as Latitude,
    cast(Longitude as decimal(11,6)) as Longitude
FROM
    BASE_TABLE

Here is the row which fails to insert in the select query:

ID          Firstname   Middlename  Lastname    Country     Latitude    Longitude
04308666-3  RICHARD     RICHARD     JUNG                    0.000000    0.000000

Inventors create query:

CREATE TABLE `Inventors` (
  `ID` varchar(55) NOT NULL DEFAULT '',
  `Firstname` varchar(255) DEFAULT NULL,
  `Middlename` varchar(255) DEFAULT NULL,
  `Lastname` varchar(255) DEFAULT NULL,
  `Country` varchar(255) DEFAULT NULL,
  `Latitude` decimal(11,8) DEFAULT NULL,
  `Longitude` decimal(11,8) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

BASE_TABLE create query:

CREATE TABLE `BASE_TABLE` (
  `Firstname` varchar(255) DEFAULT NULL,
  `Middlename` varchar(255) DEFAULT NULL,
  `Lastname` varchar(255) DEFAULT NULL,
  `Country` varchar(255) DEFAULT NULL,
  `Zipcode` varchar(255) DEFAULT NULL,
  `Latitude` varchar(255) DEFAULT NULL,
  `Longitude` varchar(255) DEFAULT NULL,
  `InvSeq` int(11) DEFAULT NULL,
  `Patent` varchar(255) DEFAULT NULL,
  `AppYear` year(4) DEFAULT NULL,
  `ApplyYear` year(4) DEFAULT NULL,
  `PubYear` year(4) NOT NULL,
  `AppDate` varchar(255) DEFAULT NULL,
  `Assignee` varchar(255) DEFAULT NULL,
  `AsgNum` varchar(255) DEFAULT NULL,
  `Class` varchar(255) DEFAULT NULL,
  `Coauthor` varchar(255) DEFAULT NULL,
  `Invnum` varchar(255) DEFAULT NULL,
  `Invnum_N` varchar(255) DEFAULT NULL,
  `Record_ID` varchar(255) NOT NULL,
  `Inventor_ID` varchar(255) DEFAULT NULL,
  `Match_Level` tinyint(4) DEFAULT NULL,
  `Company_ID` varchar(255) DEFAULT NULL,
  `Classification` varchar(255) DEFAULT NULL,
  `Citing` mediumint(9) DEFAULT NULL,
  `Cited` mediumint(9) DEFAULT NULL,
  PRIMARY KEY (`Record_ID`),
  KEY `Inventor_ID` (`Inventor_ID`),
  KEY `Patent` (`Patent`),
  KEY `Patent_2` (`Patent`,`Inventor_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Can anyone help me on this issue?

Body:
I found the problem. Latitude (VARCHAR) and Longitude (VARCHAR) in BASE_TABLE had the value of an empty string ''. This caused MySQL to cast to an incorrect value for some reason.

I solved this by replacing the empty string with NULL in the select query (See below).

INSERT INTO
    Inventors
SELECT DISTINCT
    Inventor_ID as ID,
    Firstname,
    Middlename,
    Lastname,
    Country,
    IF(Latitude='',NULL,CAST(Latitude as decimal(11,6))) as Latitude,
    IF(Longitude='',NULL,CAST(Longitude as decimal(11,6))) as Longitude
FROM
    BASE_TABLE


问:
PHP convert Array to Object
var_dump($response);

outputs:

```<code> array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32616923206) ["namespace"]=> string(7) "ly26638" } } }
 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32641864774) ["namespace"]=> string(7) "ly26638" } } }
</code>```

how can I convert $response to an object to operate it like in the following code:

```<code>echo $response->metafields[0]->id;
</code>```

I've tried the code below, but without any result :/

```<code>$object = json_decode(json_encode($response));
</code>```

答:
You can't find the member of an object by '[]'.

The '[]' is for arrays, and the '->' is for objects.

So the reason for the blank output is: metafields[0].

The code below is wrong:

```<code>echo $response->metafields[0]->id;
</code>```

So you should change the key of the array, the key of an array should not be a pure number.

I tried to change the key to 'a13', and with the code of:

```<code>echo $response->metafields->a13->id;
</code>```

I got "32616923206".

That's all. O(∩_∩)O~

Title: PHP convert Array to Object

Body:
var_dump($response);

outputs:

 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32616923206) ["namespace"]=> string(7) "ly26638" } } }
 array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32641864774) ["namespace"]=> string(7) "ly26638" } } }

how can I convert $response to an object to operate it like in the following code:

echo $response->metafields[0]->id;

I've tried the code below, but without any result :/

$object = json_decode(json_encode($response));

Body:
You can't find the member of an object by '[]'.

The '[]' is for arrays, and the '->' is for objects.

So the reason for the blank output is: metafields[0].

The code below is wrong:

echo $response->metafields[0]->id;

So you should change the key of the array, the key of an array should not be a pure number.

I tried to change the key to 'a13', and with the code of:

echo $response->metafields->a13->id;

I got "32616923206".

That's all. O(∩_∩)O~


问:
Trying to implement a custom route in umbraco 7.5.3 but the overrided method FindContent does not get fired
I've trying to retrieve the rendermodel model into my custom hijacked method, but i always get null. The two optional parameters are correct.

This is my custom route :

```<code>RouteTable.Routes.MapRoute(
        "umbracoRoute",
        "token-verification/{action}/{userId}/{code}",
        new
        {
            controller = "ExternalLinkOperations",
            action = "",
            userId = UrlParameter.Optional,
            code = UrlParameter.Optional
        },
        new ConfirmEmailRouteHandler(3290)
        );
</code>```

this is the ConfirmEmailRouteHandler class:

```<code>public class ConfirmEmailRouteHandler: UmbracoVirtualNodeByIdRouteHandler
{
    public ConfirmEmailRouteHandler(int realNodeId) : base(realNodeId)
    {
    }

    protected override IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext, IPublishedContent baseContent)
    {
        return base.FindContent(requestContext, umbracoContext, baseContent);
    }
}
</code>```

and this is the the method in the ExternalLinkOperationsController which inherit from rendermodel:

```<code>[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(RenderModel model, string userId, string code)
{}
</code>```

so Im not getting the model parameter only the two optional parameter, what i could be doing wrong, I also tried to make this

```<code> new UmbracoVirtualNodeByIdRouteHandler(3290)
</code>```

instead of

```<code>new ConfirmEmailRouteHandler(3290),
</code>```

but without success, I'm using umbraco v 7.5.3. Debugging the code in any moment the overrided method FindContent gets fired, only when the constructor.

Thanks in advance for any help

答:
I didn't realized the route property is incorrect, i have RouteTable.Routes.MapRoute, and i am supposed to be using RouteTable.Routes.MapUmbracoRoute

answer by Shannon Deminick here!

Body:
I've trying to retrieve the rendermodel model into my custom hijacked method, but i always get null. The two optional parameters are correct.

This is my custom route :

RouteTable.Routes.MapRoute(
        "umbracoRoute",
        "token-verification/{action}/{userId}/{code}",
        new
        {
            controller = "ExternalLinkOperations",
            action = "",
            userId = UrlParameter.Optional,
            code = UrlParameter.Optional
        },
        new ConfirmEmailRouteHandler(3290)
        );

this is the ConfirmEmailRouteHandler class:

public class ConfirmEmailRouteHandler: UmbracoVirtualNodeByIdRouteHandler
{
    public ConfirmEmailRouteHandler(int realNodeId) : base(realNodeId)
    {
    }

    protected override IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext, IPublishedContent baseContent)
    {
        return base.FindContent(requestContext, umbracoContext, baseContent);
    }
}

and this is the the method in the ExternalLinkOperationsController which inherit from rendermodel:

[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(RenderModel model, string userId, string code)
{}

so Im not getting the model parameter only the two optional parameter, what i could be doing wrong, I also tried to make this

 new UmbracoVirtualNodeByIdRouteHandler(3290)

instead of

new ConfirmEmailRouteHandler(3290),

but without success, I'm using umbraco v 7.5.3. Debugging the code in any moment the overrided method FindContent gets fired, only when the constructor.

Thanks in advance for any help


问:
How to select nth child element in jquery?
I have a structure like

```<code><li id="step1_li">
 <a>...</a>
 <a>...</a>
</li>
</code>```

I want to select 2nd 'a' tag,

i am using like

```<code>$('#step1_li :nth-child(2) a').addClass("hide");
</code>```

But it is not working, please suggest where i am wrong.

答:
you are writing it wrong. it's like in CSS

$('#step1_li  a:nth-child(2)').addClass("hide");

if you want to find an nth  element then you need to attach :nth- to that element, in this case the a element

$('#step1_li  a:nth-child(2)').addClass("hide");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide { color:red;font-weight:bold}</code>```

 ...
 ...

```

Body:
I have a structure like

 ...
 ...

I want to select 2nd 'a' tag,

i am using like

$('#step1_li :nth-child(2) a').addClass("hide");

But it is not working, please suggest where i am wrong.

Body:
you are writing it wrong. it's like in CSS

$('#step1_li  a:nth-child(2)').addClass("hide");

if you want to find an nth  element then you need to attach :nth- to that element, in this case the a element

$('#step1_li  a:nth-child(2)').addClass("hide");

.hide { color:red;font-weight:bold}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="step1_li">
 <a>...</a>
 <a>...</a>
</li>


问:
How to execute powershell script from FAKE - F#MAKE
I am migrating MSBuild code to FAKE - and I am not able to execute powershell script from fake ,below is the code of MSBuild file to be written in FAKE :

```<code><Target Name="VersionConfig">
    <Exec IgnoreExitCode="false" LogStandardErrorAsError="true" StandardErrorImportance="high" Command="powershell -File "$(BuildRoot)\DeployScripts\scripts\AdminScripts\VersionUpdateFile.ps1"  -path "$(BuildSolutionVersioningConfig)" -majorVersion "$(BuildNumberMajor)" -minor "$(BuildNumberMinor)" -build "$(BuildNumber)" -revision "$(BuildNumberRevision)""/>
</Target>
</code>```

How to write this in FAKE , I'm new to FAKE and have not used F# much, so forgive me if this should be obvious.

If anyone can help , that would be really helpful.

Thank You .

答:
The Fake.ProcessHelper namespace in FAKE is what you're looking for. The documentation won't tell you this, but Fake.ProcessHelper is marked with the AutoOpen attribute, which means that all the functions listed in that API reference page I linked are available to you from your FAKE build script, without you needing any explicit open statements to use them. You use it like this:

```<code>let inQuotes s = sprintf "\"%s\"" s

Target "Sample" (fun _ ->
  let retCode =
    ExecProcess
      (fun info ->
        info.Name <- "powershell.exe"  // Don't know if you need full path here
        info.WorkingDirectory <- getBuildParam "BuildRoot"
        info.Arguments <-
          [ "-File"; getBuildParam "BuildRoot" + "\DeployScripts\scripts\AdminScripts\VersionUpdateFile.ps1" |> inQuotes;
            "-path"; getBuildParam "BuildSolutionVersioningConfig" |> inQuotes;
            "-majorVersion"; getBuildParam "BuildNumberMajor" |> inQuotes;
            "-minor"; getBuildParam "BuildNumberMinor" |> inQuotes;
            "-build"; getBuildParam "BuildNumber" |> inQuotes;
            "-revision"; getBuildParam "BuildNumberRevision" |> inQuotes
          ] |> separated " "
      )
      (TimeSpan.FromMinutes 5.0)
  if retCode <> 0 then
    failwith (sprintf "PowerShell exited with non-zero exit code %d" retCode)
)
</code>```

A couple notes:

Notice how I declared a custom inQuotes helper function to make the info.Arguments list look nicer.

More info on the separated function I used.

More info on the getBuildParam function I used.

Body:
I am migrating MSBuild code to FAKE - and I am not able to execute powershell script from fake ,below is the code of MSBuild file to be written in FAKE :

<Target Name="VersionConfig">
    <Exec IgnoreExitCode="false" LogStandardErrorAsError="true" StandardErrorImportance="high" Command="powershell -File "$(BuildRoot)\DeployScripts\scripts\AdminScripts\VersionUpdateFile.ps1"  -path "$(BuildSolutionVersioningConfig)" -majorVersion "$(BuildNumberMajor)" -minor "$(BuildNumberMinor)" -build "$(BuildNumber)" -revision "$(BuildNumberRevision)""/>
</Target>

How to write this in FAKE , I'm new to FAKE and have not used F# much, so forgive me if this should be obvious.

If anyone can help , that would be really helpful.

Thank You .

Body:
The Fake.ProcessHelper namespace in FAKE is what you're looking for. The documentation won't tell you this, but Fake.ProcessHelper is marked with the AutoOpen attribute, which means that all the functions listed in that API reference page I linked are available to you from your FAKE build script, without you needing any explicit open statements to use them. You use it like this:

let inQuotes s = sprintf "\"%s\"" s

Target "Sample" (fun _ ->
  let retCode =
    ExecProcess
      (fun info ->
        info.Name <- "powershell.exe"  // Don't know if you need full path here
        info.WorkingDirectory <- getBuildParam "BuildRoot"
        info.Arguments <-
          [ "-File"; getBuildParam "BuildRoot" + "\DeployScripts\scripts\AdminScripts\VersionUpdateFile.ps1" |> inQuotes;
            "-path"; getBuildParam "BuildSolutionVersioningConfig" |> inQuotes;
            "-majorVersion"; getBuildParam "BuildNumberMajor" |> inQuotes;
            "-minor"; getBuildParam "BuildNumberMinor" |> inQuotes;
            "-build"; getBuildParam "BuildNumber" |> inQuotes;
            "-revision"; getBuildParam "BuildNumberRevision" |> inQuotes
          ] |> separated " "
      )
      (TimeSpan.FromMinutes 5.0)
  if retCode <> 0 then
    failwith (sprintf "PowerShell exited with non-zero exit code %d" retCode)
)

A couple notes:

Notice how I declared a custom inQuotes helper function to make the info.Arguments list look nicer.

More info on the separated function I used.

More info on the getBuildParam function I used.


问:
Java - StringTokenizer
Disclaimer: I just learnt how to do this yesterday, and I am desperate

I have 3 classes (Student, ClassSchedule, ClassEnrolment)

```<code>public class ClassEnrolment {
    ClassSchedule cs;
    Student stud;

    public ClassEnrolment(ClassSchedule cs, Student stud) {
        super();
        this.cs = cs;
        this.stud = stud;
     }
}

-----

public class Student{
    private String name;
    private String matricNo;
    ClassEnrolment classroom;
    ClassSchedule schedule;
}

-----

public class ClassSchedule {
    String classType;
    int index;
    int group;
    String day;
    String time;
    String venue;
    String remark;
    String courseCode;
}
</code>```

I am trying to read/write a text file (database). I am having issues with 3 lines inside "/////////////////".

I am aware that the attributes declared in ClassEnrolment are not int nor string. How should I do this? How do I bring ClassSchedule and Student as part of StringTokenizer?

The textfile stores index from ClassSchedule and matricNo from Student. I have a feeling I am doing this wrongly.

```<code>    public static ArrayList readEnrolment(String filename) throws IOException {
    ArrayList stringArray = (ArrayList) read(filename);
    ArrayList alr = new ArrayList();

    for (int i = 0; i < stringArray.size(); i++) {
        String st = (String) stringArray.get(i);
        StringTokenizer star = new StringTokenizer(st, SEPARATOR);

        ///////////////////////////////////////////////////
        int cs = Integer.parseInt(star.nextToken().trim());
        String stud = star.nextToken().trim();
        ClassEnrolment enrolment = new ClassEnrolment(cs, stud);
        //////////////////////////////////////////////////
        alr.add(enrolment);
    }
    return alr;
}

public static void saveEnrolment(String filename, List al) throws IOException {
    List alw = new ArrayList();

    for (int i = 0; i < al.size(); i++) {
        ClassEnrolment enrolment = (ClassEnrolment) al.get(i);
        StringBuilder st = new StringBuilder();
        st.append(enrolment.getCs2());
        st.append(SEPARATOR);
        st.append(enrolment.getStud2());
        alw.add(st.toString());
    }
    write(filename, alw);
}
</code>```

答:
Your problem here is an issue of Serialization. You could very well declare your classEnrolment as Serializable(do not forget the serialUUID) and let the classic java serialization process to write your objects as bytes in your file.

However, what you are trying here is to conceive a custom serializer for your class. I'd advise you to use generics in the likes of :

```<code>public interface Serializer<T> {

    byte[] write(T objectToSerialize);

    //to build a factory/service around it
    boolean canDeserialize(byte[] serializedObject);

    T read(byte[] serializedObject);
}
</code>```

So that your methods read/writeEnrollment will simply be creating a Serializer<ClassEnrollment> and letting it do its job (which will probably create a Serializer<Student> and a Serializer<ClassSchedule>) .

For the matter of the Serialization process, I have to say that the StringTokenizer is a legacy class from JDK 1 whose use is discouraged by its own javadoc :

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

And if you want to Serialize objects of potentially different classes than just your ClassEnrollment, it would be nice to be able to distinguish the class used. There are many ways to do it, and as one commenter said, json serialization would fare very well.

Title: Java - StringTokenizer

Body:
Disclaimer: I just learnt how to do this yesterday, and I am desperate

I have 3 classes (Student, ClassSchedule, ClassEnrolment)

public class ClassEnrolment {
    ClassSchedule cs;
    Student stud;

    public ClassEnrolment(ClassSchedule cs, Student stud) {
        super();
        this.cs = cs;
        this.stud = stud;
     }
}

-----

public class Student{
    private String name;
    private String matricNo;
    ClassEnrolment classroom;
    ClassSchedule schedule;
}

-----

public class ClassSchedule {
    String classType;
    int index;
    int group;
    String day;
    String time;
    String venue;
    String remark;
    String courseCode;
}

I am trying to read/write a text file (database). I am having issues with 3 lines inside "/////////////////".

I am aware that the attributes declared in ClassEnrolment are not int nor string. How should I do this? How do I bring ClassSchedule and Student as part of StringTokenizer?

The textfile stores index from ClassSchedule and matricNo from Student. I have a feeling I am doing this wrongly.

    public static ArrayList readEnrolment(String filename) throws IOException {
    ArrayList stringArray = (ArrayList) read(filename);
    ArrayList alr = new ArrayList();

    for (int i = 0; i < stringArray.size(); i++) {
        String st = (String) stringArray.get(i);
        StringTokenizer star = new StringTokenizer(st, SEPARATOR);

        ///////////////////////////////////////////////////
        int cs = Integer.parseInt(star.nextToken().trim());
        String stud = star.nextToken().trim();
        ClassEnrolment enrolment = new ClassEnrolment(cs, stud);
        //////////////////////////////////////////////////
        alr.add(enrolment);
    }
    return alr;
}

public static void saveEnrolment(String filename, List al) throws IOException {
    List alw = new ArrayList();

    for (int i = 0; i < al.size(); i++) {
        ClassEnrolment enrolment = (ClassEnrolment) al.get(i);
        StringBuilder st = new StringBuilder();
        st.append(enrolment.getCs2());
        st.append(SEPARATOR);
        st.append(enrolment.getStud2());
        alw.add(st.toString());
    }
    write(filename, alw);
}

Body:
Your problem here is an issue of Serialization. You could very well declare your classEnrolment as Serializable(do not forget the serialUUID) and let the classic java serialization process to write your objects as bytes in your file.

However, what you are trying here is to conceive a custom serializer for your class. I'd advise you to use generics in the likes of :

public interface Serializer<T> {

    byte[] write(T objectToSerialize);

    //to build a factory/service around it
    boolean canDeserialize(byte[] serializedObject);

    T read(byte[] serializedObject);
}

So that your methods read/writeEnrollment will simply be creating a Serializer<ClassEnrollment> and letting it do its job (which will probably create a Serializer<Student> and a Serializer<ClassSchedule>) .

For the matter of the Serialization process, I have to say that the StringTokenizer is a legacy class from JDK 1 whose use is discouraged by its own javadoc :

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

And if you want to Serialize objects of potentially different classes than just your ClassEnrollment, it would be nice to be able to distinguish the class used. There are many ways to do it, and as one commenter said, json serialization would fare very well.


答:
```<code>$( "li a:nth-child(2)" ).addClass("hide");
</code>```

Use this....

Title: How to select nth child element in jquery?

Body:
$( "li a:nth-child(2)" ).addClass("hide");

Use this....


问:
Months with less than 31 days omitted from list
Consider the following code that was working perfectly yesterday, but now today (30th March), it has stopped working...

```<code><form class="date">
<select name="date" onchange="this.form.submit()">

<?php
  for ($i = 0; $i <= 60; ++$i) {
    $time = strtotime(sprintf('+%d months', $i));
    $value = date('Y-m', $time);
    $label = date('F Y', $time);
    $nowvalue = date('Y-m');
    $nowlabel = date('F Y');
        if(isset($_GET['date'])) {
          if(strcmp($value,$_GET['date']) == 0) {
             //If 0, $value and $_GET['date'] are the same: The option is selected
             printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
             printf('<option value="%s">%s</option>', $value, $label);
          }
        } else {
          if($value == $nowvalue) {
            printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
            printf('<option value="%s">%s</option>', $value, $label);
          }
    }
  }
  ?>
</select>
</form>
</code>```

This outputs a select list of upcoming months, that onchange, reloads the page with a different query in the URL for the calendar on that page to react on.

If i manually update the query in the URL, it works fine, but this select list is repeating dates, have a look at the image below...

This cant be a coincidence that all of the months with the shortest days are missing, or in fact have been replaced with the same name as the month before?

Does anyone have an idea why this might be happening?

答:
As John Conde pointed out, this is because todays dates (the 31st) plus one month is actual May 1st, and April is skipped.

I did the following to set the date to the 1st of the month, then plus one month...

```<code><?php
  for ($i = 0; $i <= 60; ++$i) {
    $firstofthismonth = '01-' . date('m-Y');
    $time = strtotime(sprintf($firstofthismonth . '+%d months', $i));
    $value = date('Y-m', $time);
    $label = date('F Y', $time);
    $nowvalue = date('Y-m');
    $nowlabel = date('F Y');
        if(isset($_GET['date'])) {
          if(strcmp($value,$_GET['date']) == 0) {
             //If 0, $value and $_GET['date'] are the same: The option is selected
             printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
             printf('<option value="%s">%s</option>', $value, $label);
          }
        } else {
          if($value == $nowvalue) {
            printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
            printf('<option value="%s">%s</option>', $value, $label);
          }
    }
  }
  ?>
</code>```

Body:
Consider the following code that was working perfectly yesterday, but now today (30th March), it has stopped working...

<form class="date">
<select name="date" onchange="this.form.submit()">

<?php
  for ($i = 0; $i <= 60; ++$i) {
    $time = strtotime(sprintf('+%d months', $i));
    $value = date('Y-m', $time);
    $label = date('F Y', $time);
    $nowvalue = date('Y-m');
    $nowlabel = date('F Y');
        if(isset($_GET['date'])) {
          if(strcmp($value,$_GET['date']) == 0) {
             //If 0, $value and $_GET['date'] are the same: The option is selected
             printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
             printf('<option value="%s">%s</option>', $value, $label);
          }
        } else {
          if($value == $nowvalue) {
            printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
            printf('<option value="%s">%s</option>', $value, $label);
          }
    }
  }
  ?>
</select>
</form>

This outputs a select list of upcoming months, that onchange, reloads the page with a different query in the URL for the calendar on that page to react on.

If i manually update the query in the URL, it works fine, but this select list is repeating dates, have a look at the image below...

This cant be a coincidence that all of the months with the shortest days are missing, or in fact have been replaced with the same name as the month before?

Does anyone have an idea why this might be happening?

Body:
As John Conde pointed out, this is because todays dates (the 31st) plus one month is actual May 1st, and April is skipped.

I did the following to set the date to the 1st of the month, then plus one month...

<?php
  for ($i = 0; $i <= 60; ++$i) {
    $firstofthismonth = '01-' . date('m-Y');
    $time = strtotime(sprintf($firstofthismonth . '+%d months', $i));
    $value = date('Y-m', $time);
    $label = date('F Y', $time);
    $nowvalue = date('Y-m');
    $nowlabel = date('F Y');
        if(isset($_GET['date'])) {
          if(strcmp($value,$_GET['date']) == 0) {
             //If 0, $value and $_GET['date'] are the same: The option is selected
             printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
             printf('<option value="%s">%s</option>', $value, $label);
          }
        } else {
          if($value == $nowvalue) {
            printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
            printf('<option value="%s">%s</option>', $value, $label);
          }
    }
  }
  ?>


问:
How to set date field in join query ruby on rails
I have below query in which I want to check the date.

The actual working query is like:

```<code>Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {is_publish: true})
</code>```

But when I try to set date field it says:

query:

```<code>Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {"is_publish = ?, available_due_date_time > ?", true,
Time.zone.now})
</code>```

Error:

```<code>SyntaxError: (irb):82: syntax error, unexpected ',', expecting =>
 available_due_date_time > ?", true, Time.zone.now})
                              ^
(irb):82: Can't assign to true
able_due_date_time > ?", true, Time.zone.now})
                              ^
(irb):82: syntax error, unexpected '}', expecting &. or :: or '[' or '.'
ime > ?", true, Time.zone.now})
                              ^
</code>```

Update:

I tried:

query:

```<code>Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {"is_publish = ? AND available_due_date_time > ?", true,
Time.zone.now})
</code>```

But still the error is same.

How to set date in these type of query? Any source for learning are also recommended.

答:
Try this:

```<code>.where(joined_private_schools: {user_id: 73}).where('lesson_plans.is_publish = ? AND lesson_plans.available_due_date_time > ?', true, Time.zone.now)
</code>```

Edit

Also, check the Active Record Query Interface. You can find there a lot of information to perform most of the queries you'll need.

Body:
I have below query in which I want to check the date.

The actual working query is like:

Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {is_publish: true})

But when I try to set date field it says:

query:

Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {"is_publish = ?, available_due_date_time > ?", true,
Time.zone.now})

Error:

SyntaxError: (irb):82: syntax error, unexpected ',', expecting =>
 available_due_date_time > ?", true, Time.zone.now})
                              ^
(irb):82: Can't assign to true
able_due_date_time > ?", true, Time.zone.now})
                              ^
(irb):82: syntax error, unexpected '}', expecting &. or :: or '[' or '.'
ime > ?", true, Time.zone.now})
                              ^

Update:

I tried:

query:

Quiz.joins(lesson_plan: [private_class: [private_school:
:joined_private_schools]]).where(joined_private_schools: {user_id: 73},
lesson_plans: {"is_publish = ? AND available_due_date_time > ?", true,
Time.zone.now})

But still the error is same.

How to set date in these type of query? Any source for learning are also recommended.

Body:
Try this:

.where(joined_private_schools: {user_id: 73}).where('lesson_plans.is_publish = ? AND lesson_plans.available_due_date_time > ?', true, Time.zone.now)

Edit

Also, check the Active Record Query Interface. You can find there a lot of information to perform most of the queries you'll need.


问:
wordpress 3.3 relative paths in CSS
I want to add an image to be a background of the header, the thing is that I don't want to add an absolute path since I'm doing this on my pc and them is to upload to my server.

should the <?php bloginfo('template_directory'); ?> work in the css? It is not working here.

code:

```<code>#branding {
    background: url("<?php bloginfo('template_directory'); ?>/images/background2.jpg") repeat-x repeat-y;
    height: 150px;
}
</code>```

答:
Somehow @developdaly solution did not work for me, but this helped:</p>

```<code>.img-div {
  background-image: url("wp-content/themes/your-theme/assets/images/your-img.jpg");
}
</code>```

Title: wordpress 3.3 relative paths in CSS

Body:
I want to add an image to be a background of the header, the thing is that I don't want to add an absolute path since I'm doing this on my pc and them is to upload to my server.

should the <?php bloginfo('template_directory'); ?> work in the css? It is not working here.

code:

#branding {
    background: url("<?php bloginfo('template_directory'); ?>/images/background2.jpg") repeat-x repeat-y;
    height: 150px;
}

Body:
Somehow @developdaly solution did not work for me, but this helped:

.img-div {
  background-image: url("wp-content/themes/your-theme/assets/images/your-img.jpg");
}


问:
Tooltip not displaying entire content for first two area charts
Not sure where I'm doing wrong,I'm not able to load contents inside kendo chart on hover --only for the first two area charts from top.
The chart at the last is however loading all the template data inside the tooltips.
Please find the dojo link..

Kendo dojo

```<code>tooltip: {
                visible: true,
                template:kendo.template(
                  '<div class="row">'+
                  '<div><h1>BRK-2212-002</h1> <h1>Breakdown</h1></div>'+
                   '<span class="border-box">Closed- #=dataItem#  </span>'+
                  '</div>'

                )

            }
</code>```

答:
It actually loads just fine. The problem is that text inside tooltip is white and therefore it looks empty.

If you add color for tooltip div

```<code>.row {
   color: black;
}
</code>```

should be able to see text. Not quite sure why different css rules are being applied.

Body:
Not sure where I'm doing wrong,I'm not able to load contents inside kendo chart on hover --only for the first two area charts from top.
The chart at the last is however loading all the template data inside the tooltips.
Please find the dojo link..

Kendo dojo

tooltip: {
                visible: true,
                template:kendo.template(
                  '
'+
                  '

BRK-2212-002

Breakdown

'+
                   'Closed- #=dataItem#  '+
                  '
'

                )

            }

Body:
It actually loads just fine. The problem is that text inside tooltip is white and therefore it looks empty.

If you add color for tooltip div

.row {
   color: black;
}

should be able to see text. Not quite sure why different css rules are being applied.


问:
List get distorted on scrolling
I am using custom ListView and when i scroll my list the image field of each listitem get replaced by some other image of some other listitem.

Can you please tell me some property of listview to prevent this.

Actually when we scroll the list the items those are not visible will perhaps
needs to  be populated again by list adapter each time during scroll.

Thanks in Advance

答:
Are you using lazy load mechanism in this???

If yes, then before the actual image is fetched from the url, you need to set a stock image to the image view of your list item.

If not then the convertView can populate the older bitmap or drawble set to the image view of any other image view.

Title: List get distorted on scrolling


答:
You can use aggregation to count the matching rows for each seller:

```<code>SELECT sellerId
FROM `sku`
WHERE id IN (3, 4, 10)
GROUP BY sellerId
HAVING COUNT(DISTINCT id) = 3;
</code>```

If you want the original rows, you can use this query to bring in the appropriate rows for the matching sellerIds.

Title: 'AND' condition for (id array) in mysql

Body:
I have an mysql table like this.

+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+
| id | sku      | sellerID | name                                                                      | mode | created             |
+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+
|  1 | Sample   |        1 | SampleItem                                                                |    1 | 2016-05-20 12:04:33 |
|  2 | Sample   |        2 | Sample1                                                                   |    1 | 2016-06-14 12:23:24 |
|  3 | SDGS046  |        1 | Shivaprasad                                                               |    2 | 2016-06-18 05:26:27 |
|  4 | PAWA006  |        1 | Panda Baby Walker Music                                                   |    2 | 2016-06-18 06:19:10 |
|  5 | PAWA005  |        1 | WonderKart Panda Walker for Kids (colour may vary)                        |    2 | 2016-06-18 06:24:23 |
|  6 | WKBR1301 |        1 | Planet of Toys New Born Toddler Protable Rocker                           |    2 | 2016-06-18 06:26:30 |
|  7 | PAKS001  |        1 | Panda Baby Musical Swing With Multiple Age Settings | 4 Stages | (Orange) |    2 | 2016-06-18 06:28:19 |
|  8 | WKGS046  |        1 | The Flyers Bay Flyer's Bay Ultra Durable Big Wheel Scooter (Silver)       |    2 | 2016-06-18 06:57:25 |
|  9 | MABS001  |        1 | Mastela Booster to Toddler 6M+ Seat (DarkGray)                            |    2 | 2016-06-20 06:25:00 |
| 10 | WKGS546  |        1 | Saffire Kids Scooter with Tractor Wheels Green                            |    2 | 2016-06-20 06:26:50 |
+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+

I want get data by query like.

SELECT * FROM `sku` WHERE `sellerID` = 1 AND id = 3 AND id = 4 AND id = 10;

but m trying this like

SELECT * FROM sku WHERE sellerID = 1 AND id IN (3,4,10);

it returns rows, if id(3,4,10) any available in table, but i want return row, if every id(3 and 4 and 10) available in table.

I want to pass an array to check AND Condition. Please suggest me if there is any solution available.

Body:
You can use aggregation to count the matching rows for each seller:

SELECT sellerId
FROM `sku`
WHERE id IN (3, 4, 10)
GROUP BY sellerId
HAVING COUNT(DISTINCT id) = 3;

If you want the original rows, you can use this query to bring in the appropriate rows for the matching sellerIds.


问:
Android Firebase Messaging: How Update UI from onMessageReceived()
I have successfully implemented Firebase messaging in my app. Works great in the background and onMessageReceived() gets called when the app is in the foreground (yippee!).

The issue I have is that I need to update the UI dynamically and I am stuck on the best way to achieve this. I don't want to send the user an in-app notification (as the sample code shows), I'm not sure I want to send a broadcast, all I want to do is to access the MainActivity in order to call a method already there, however I have no reference to the MainActivity in the service.

```<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getNotification().getBody() != null) {
        Log.d(LOG_TAG, "Message received: " + remoteMessage.getNotification().getBody());
    } else {
        Log.d(LOG_TAG, "Message received: " + remoteMessage.getData().get("message"));
    }

    // Call method in MainActivity
    // <<< What goes Here?>>>>

}
</code>```

This seems a simple use case but I can't find anything online to help.

Thanks in advance

答:
I believe you should send a Local Broadcast with the data and register a receiver wherever you want that data to be utilised. This is a very good design pattern(Observer) as it decouples your Activity from the Service.

If the activity wants to do something with the data it will, else it won't. They are both separate entities and it would be much easier to maintain this code in the future, as far as I know.

Hope this helped.

Body:
I have successfully implemented Firebase messaging in my app. Works great in the background and onMessageReceived() gets called when the app is in the foreground (yippee!).

The issue I have is that I need to update the UI dynamically and I am stuck on the best way to achieve this. I don't want to send the user an in-app notification (as the sample code shows), I'm not sure I want to send a broadcast, all I want to do is to access the MainActivity in order to call a method already there, however I have no reference to the MainActivity in the service.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getNotification().getBody() != null) {
        Log.d(LOG_TAG, "Message received: " + remoteMessage.getNotification().getBody());
    } else {
        Log.d(LOG_TAG, "Message received: " + remoteMessage.getData().get("message"));
    }

    // Call method in MainActivity
    // <<< What goes Here?>>>>

}

This seems a simple use case but I can't find anything online to help.

Thanks in advance


问:
Creating Button and OnClick Event from c# side - asp.net
im creating a button from c# side like this:

```<code>content += "<button class='btn btn-info' runat='server' style='margin-left:4%' id='Like" + dr[0] + "' onclick='likeClick'>";
</code>```

And the event is really simple i just want to see if its working:

```<code>protected void likeClick(object sender, EventArgs e)
{
    content = sender.ToString();
}
</code>```

But when i click the button it doesn't trigger the event, I put a break point in the event and I debugged but it didn't start the fucntion. I opened Inspect Element in the browser and clicked the button. It showed me this:

What am I doing wrong here?

答:
I understand that you want to create a Button server control dynamically. The way, you are creating is wrong. You have to instantiate a Button object, declare the Click event and add it to your page. Also, since it is a dynamically created control, it will required to be re-created on every postback. Here is a sample code on similar scenario:

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:PlaceHolder runat="server" ID="phControl" />
    </form>
</body>
</html>

    protected void Page_Load(object sender, EventArgs e)
    {
        Button btnButton = new Button();
        btnButton.Style.Add("margin-left", "4%");
        btnButton.ID = "like"+ dr[0];
        btnButton.Text = "Like";
        btnButton.Click += BtnButton_Click;
        phControl.Controls.Add(btnButton);
    }

    private void BtnButton_Click(object sender, EventArgs e)
    {
        string content = sender.ToString();
        Response.Write(content);
    }
</code>```

Body:
im creating a button from c# side like this:

content += "<button class='btn btn-info' runat='server' style='margin-left:4%' id='Like" + dr[0] + "' onclick='likeClick'>";

And the event is really simple i just want to see if its working:

protected void likeClick(object sender, EventArgs e)
{
    content = sender.ToString();
}

But when i click the button it doesn't trigger the event, I put a break point in the event and I debugged but it didn't start the fucntion. I opened Inspect Element in the browser and clicked the button. It showed me this:

What am I doing wrong here?

Body:
I understand that you want to create a Button server control dynamically. The way, you are creating is wrong. You have to instantiate a Button object, declare the Click event and add it to your page. Also, since it is a dynamically created control, it will required to be re-created on every postback. Here is a sample code on similar scenario:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:PlaceHolder runat="server" ID="phControl" />
    </form>
</body>
</html>

    protected void Page_Load(object sender, EventArgs e)
    {
        Button btnButton = new Button();
        btnButton.Style.Add("margin-left", "4%");
        btnButton.ID = "like"+ dr[0];
        btnButton.Text = "Like";
        btnButton.Click += BtnButton_Click;
        phControl.Controls.Add(btnButton);
    }

    private void BtnButton_Click(object sender, EventArgs e)
    {
        string content = sender.ToString();
        Response.Write(content);
    }


问:
how to pass array of model from one actvtiy to another in android
```<code>public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}
</code>```

this is my Datamodel:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}
</code>```

main activtiy

```<code>public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}
</code>```

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

答:
```<code>     ArrayList<DataModel> modelArrayList = new ArrayList<>(); //Use your model array here
     DataModel _modeDataModel=new DataModel(MainActivity.this);
    _modeDataModel.setCid("1");
    _modeDataModel.setName("Anil");
     modelArrayList.add(_modeDataModel);

     //Call like this way
     Bundle bundle = new Bundle();
            bundle.putExtra("channel", modelArrayList);
            Intent intent = new Intent(MainActivity.this,SecondActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);

      public class SecondActivity extends AppCompatActivity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                Bundle getBundle = this.getIntent().getExtras();
                ArrayList<DataModel> channelsList = (ArrayList<DataModel>) getBundle.getParcelableArrayList("channel");
            }
        }
</code>```

Body:
public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}

this is my Datamodel:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}

main activtiy

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,


问:
Open terminal here in Mac OS finder
Is there something similar to the "Open Command Window Here" Windows Powertoy for Mac OS? I've found a couple plugins through a google search but wanted to see what works best for developers out there.</p>

答:
This:

https://github.com/jbtule/cdto#cd-to

It's a small app that you drag into the Finder toolbar, the icon fits in very nicely. It works with Terminal, xterm (under X11), iterm.

OwnerDisplayName: Abdullah Jibaly

Title: Open terminal here in Mac OS finder

LastEditorDisplayName: sblundy

OwnerDisplayName: REDACTED


问:
Why do browsers block some ports?
I'm playing around with websockets and it appears, that all browsers with native websocket support I tested with (Safari, Chrome) block some ports. If I try to connect to my server over port 80, everyting works fine. If I try other ports, like 81, 82 or 1000, the connection is prematurely closed because there's nothing on the other end. That's the expected behaviour and it works beautifully.

However, with some ports (such as 20, 37 or 79), the Chrome developer console simply says WebSocket port 79 blocked but my JS code doesn't receive any information about this (not even some sort of timeout). Safari is a little more verbose and comments SECURITY_ERR: DOM Exception 18: An attempt was made to break through the security policy of the user agent.

So my questions are these:

How can I reliably detect that a port is blocked?
Do I have to set a timeout and check that manually? That doesn't seem to be the smartest way to go about it, although it might be the only way to do it cross-browser.

Where can I find a list of the blocked ports?
My Google search didn't turn up anything useful, unfortunately.

Why are these ports blocked in the first place?

Thanks in advance!

答:
Okay, I found the answer. Sometimes you just don't see the forest for the trees.

First off, handling cases of blocked ports is trivial. A simple try/catch does the trick. I was simply confused by the way Chrome displayed that exception and didn't recognize it as such right away (I usually use Firefox).

Secondly, the WebSockets API Specification explicitly states that

If port is a port to which the user agent is configured to block access, then throw a SECURITY_ERR exception. (User agents typically block access to well-known ports like SMTP.)

What ports exactly are meant by that appears to be up to the browser's Websocket implementation. My tests have shown that Chrome and Safari block the following ports (only ports below 1024 were tested):

1: TCPMUX

7: Echo Protocol

9: Discard Protocol

11: systat service

13: Daytime Protocol

15: Netstat service

17: Quote of the Day

19: Character Generator Protocol

20: FTP

21: FTP

22: SSH

23: Telnet

25: SMTP

37: TIME protocol

42: nameserver/WINS

43: WHOIS

53: DNS

77: RJE Service

79: Finger

87: link

95: supdup

101: NIC host name

102: ISO-TSAP

103: gppitnp

104: ACR/NEMA

109: POP2

110: POP3

111: SunRPC

113: ident

115: SFTP

117: UUCP Path Service

119: NNTP

123: NTP

135: Microsoft EPMAP

139: NetBIOS Session Service

143: IMAP

179: BGP

389: LDAP

465: Cisco protocol

512: comsat

513: rlogin

514: Syslog

515: Line Printer Daemon

526: tempo

530: RPC

531: IRC

532: netnews

540: UUCP

556: RFS

563: NNTPS

587: SMTP

601: unknown

636: LDAPS

993: IMAPS

995: POP3S

The associated services are taken from the list of TCP and UDP port numbers on Wikipeda.

Title: Why do browsers block some ports?


问:
Brace initialization prevents non-const use of temporary
I want to create a temporary copy of a const object and use it in a non-const way:

```<code>struct S {
    S& f() { return *this; }
};

int main() {
    const S a{};
    S{a}.f(); // Error on this line
    return 0;
}
</code>```

Using msvc (Visual Studio 2017, C++14), I get this error:

Error C2662   'S &S::f(void)': cannot convert 'this' pointer from 'const S' to 'S &'

If I change the brace initialization to classic initialization, it works:

```<code>S{a}.f(); // Does not work
S(a).f(); // Works
</code>```

Both variants compile fine in gcc. Am I missing something or is this a compiler bug?

答:
It looks like a compiler bug, or the result of a weird optimization, because this  variation of original code that only make ctors and dtor with side effects compiles fine using MSVC:

```<code>#include <iostream>

struct S {
    S(const S& other) {
        std::cout << "Copy ctor " << &other << " -> " << this << std::endl;
    }
    S() {
        std::cout << "Default ctor " << this << std::endl;
    }
    ~S() {
        std::cout << "Dtor " << this << std::endl;
    }
    S& f() { return *this; }
};

int main() {
    const S a{};
    std::cout << &a << std::endl;
    S{a}.f();
    return 0;
}
</code>```

Compilation is successful and output is:

Default ctor 0306FF07
Copy ctor 0306FF07 -> 0306FF06
Dtor 0306FF06
Dtor 0306FF07
```

Body:
I want to create a temporary copy of a const object and use it in a non-const way:

struct S {
    S& f() { return *this; }
};

int main() {
    const S a{};
    S{a}.f(); // Error on this line
    return 0;
}

Using msvc (Visual Studio 2017, C++14), I get this error:

Error C2662   'S &S::f(void)': cannot convert 'this' pointer from 'const S' to 'S &'

If I change the brace initialization to classic initialization, it works:

S{a}.f(); // Does not work
S(a).f(); // Works

Both variants compile fine in gcc. Am I missing something or is this a compiler bug?

Body:
It looks like a compiler bug, or the result of a weird optimization, because this  variation of original code that only make ctors and dtor with side effects compiles fine using MSVC:

#include <iostream>

struct S {
    S(const S& other) {
        std::cout << "Copy ctor " << &other << " -> " << this << std::endl;
    }
    S() {
        std::cout << "Default ctor " << this << std::endl;
    }
    ~S() {
        std::cout << "Dtor " << this << std::endl;
    }
    S& f() { return *this; }
};

int main() {
    const S a{};
    std::cout << &a << std::endl;
    S{a}.f();
    return 0;
}

Compilation is successful and output is:

Default ctor 0306FF07
Copy ctor 0306FF07 -> 0306FF06
Dtor 0306FF06
Dtor 0306FF07


答:
$(document).ready(function(){
  $("#step1_li a:nth-child(2)").hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li id="step1_li">
 <a>1</a>
 <a>2</a>
 <a>3</a>
</li></code>```

Body:
I have a structure like

 ...
 ...

I want to select 2nd 'a' tag,

i am using like

$('#step1_li :nth-child(2) a').addClass("hide");

But it is not working, please suggest where i am wrong.

Body:
$(document).ready(function(){
  $("#step1_li a:nth-child(2)").hide();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li id="step1_li">
 <a>1</a>
 <a>2</a>
 <a>3</a>
</li>


问:
Batch insert causing failure
I have a task where I need to insert a lot of data into the database using hibernate. I am currently testing with inserting 500,000 entities which each have one relation, so 1,000,000 inserts in total.
Based on this guide I have created the following code which actually works. All the data is inserted and committed without errors.

```<code>import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.*;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class StackoverflowExample {
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private SessionContext sessionContext;

    @EJB
    private XmlProcessorFactory xmlProcessorFactory;

    @EJB
    private TaskManagerBean taskManagerBean;

    public void processFile(String[] args, Task task) throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException, IOException, TransformerException, ParseException, XMLStreamException, NotSupportedException {
        UserTransaction tx = null;

        XmlProcessor instance = xmlProcessorFactory.getInstance(new File("data.xml"));

        XmlElement nextElement = instance.getNextElement();
        int i = 0;
        int batchSize = 50;
        entityManager.setProperty("hibernate.jdbc.batch_size", batchSize);
        tx = sessionContext.getUserTransaction();
        tx.begin();
        while (nextElement != null) {
            Entry entry = new Entry(nextElement.getUserReference(), nextElement.getXml());

            entityManager.persist(entry);

            if (i % batchSize == 0) {
                entityManager.flush();
                entityManager.clear();
            }

            nextElement = instance.getNextElement();
            i++;
        }

        task.setStatus(status);
        task.setEndTime(now());
        // This gives the OutOfMemoryError
        entityManager.merge(task);

        tx.commit();
    }
}
</code>```

This will fail in the line where I call taskManagerBean.update() with the following error:

```<code>2017-03-31 08:49:30,212 ERROR [org.jboss.as.ejb3.invocation] (EJB default - 3) WFLYEJB0034:
EJB Invocation failed on component TaskManagerBean for method public void
TaskManagerBean.update(Task,TaskStatus):
javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException:
could not load an entity: [Task#3]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:159)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:256)
    ...
    at TaskManagerBean$$$view18.update(Unknown Source)
    at StoreEntriesBean.processFile(StoreEntriesBean.java:117)
    ...
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    ...
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:254)
    ... 104 more
Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    ...
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161)
    ... 135 more
Caused by: java.sql.SQLException: Error
    at org.jboss.jca.adapters.jdbc.WrappedConnection.checkException(WrappedConnection.java:1972)
    ...
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    ... 155 more
Caused by: java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOfRange(Arrays.java:3664)
    ...
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
</code>```

Runtime.getRuntime().freeMemory() returns 71540896 right before the error.

I start Wildfly with -Xmx2048m and a quick glance at memory usage shows that it only uses less than half of it.

I have tried committing the inserted Entries after every 1,000 inserts. This triggers the TaskManagerBean and it will fail the same way after a few updates.
In a few occasions I have also seen this error after I finished the huge batch job and the owning entity was to be updated.

I have tried with a file with just 5,000 entries and the entire process works fine.

Is this a bug in the MySQL driver or am I doing something wrong here?

答:
The call to EntityManger.merge() is what causes the error.
I am not 100 % familiar with Hibernate but apparently merge will in this case fetch the entire relation from Task to Entry, which in this case was a collection with 500,000 entries - even though this relation is Lasy loaded.

I replaced merge with a Entity.find(Task.class, taskId) and set the status on that instance instead and that solved my problem.

In the meantime I have introduced Java Batch Processing which I can only recommend. It avoids having to write batch jobs yourself.

Title: Batch insert causing failure

Body:
I have a task where I need to insert a lot of data into the database using hibernate. I am currently testing with inserting 500,000 entities which each have one relation, so 1,000,000 inserts in total.
Based on this guide I have created the following code which actually works. All the data is inserted and committed without errors.

import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.*;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class StackoverflowExample {
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private SessionContext sessionContext;

    @EJB
    private XmlProcessorFactory xmlProcessorFactory;

    @EJB
    private TaskManagerBean taskManagerBean;

    public void processFile(String[] args, Task task) throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException, IOException, TransformerException, ParseException, XMLStreamException, NotSupportedException {
        UserTransaction tx = null;

        XmlProcessor instance = xmlProcessorFactory.getInstance(new File("data.xml"));

        XmlElement nextElement = instance.getNextElement();
        int i = 0;
        int batchSize = 50;
        entityManager.setProperty("hibernate.jdbc.batch_size", batchSize);
        tx = sessionContext.getUserTransaction();
        tx.begin();
        while (nextElement != null) {
            Entry entry = new Entry(nextElement.getUserReference(), nextElement.getXml());

            entityManager.persist(entry);

            if (i % batchSize == 0) {
                entityManager.flush();
                entityManager.clear();
            }

            nextElement = instance.getNextElement();
            i++;
        }

        task.setStatus(status);
        task.setEndTime(now());
        // This gives the OutOfMemoryError
        entityManager.merge(task);

        tx.commit();
    }
}

This will fail in the line where I call taskManagerBean.update() with the following error:

2017-03-31 08:49:30,212 ERROR [org.jboss.as.ejb3.invocation] (EJB default - 3) WFLYEJB0034:
EJB Invocation failed on component TaskManagerBean for method public void
TaskManagerBean.update(Task,TaskStatus):
javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException:
could not load an entity: [Task#3]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:159)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:256)
    ...
    at TaskManagerBean$$$view18.update(Unknown Source)
    at StoreEntriesBean.processFile(StoreEntriesBean.java:117)
    ...
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    ...
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:254)
    ... 104 more
Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    ...
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161)
    ... 135 more
Caused by: java.sql.SQLException: Error
    at org.jboss.jca.adapters.jdbc.WrappedConnection.checkException(WrappedConnection.java:1972)
    ...
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    ... 155 more
Caused by: java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOfRange(Arrays.java:3664)
    ...
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)

Runtime.getRuntime().freeMemory() returns 71540896 right before the error.

I start Wildfly with -Xmx2048m and a quick glance at memory usage shows that it only uses less than half of it.

I have tried committing the inserted Entries after every 1,000 inserts. This triggers the TaskManagerBean and it will fail the same way after a few updates.
In a few occasions I have also seen this error after I finished the huge batch job and the owning entity was to be updated.

I have tried with a file with just 5,000 entries and the entire process works fine.

Is this a bug in the MySQL driver or am I doing something wrong here?


问:
How to make single instance of Activity with different data passed through Intents in Android?
I want to make an Activity which should be created only once and then it should be updated based on certain values. First I tried to pass data through Intent but since I have made that activity as singleTask it do not get the new Intent object and uses the previous one.

What can be the way of passing the data to an Activity that is singleTask and needs to be updated on certain values?

答:
What entity generates the new values? If it is a Service then your Activity can establish a communication channel, so the Service can notify the Activity with new data.

More info here.


问:
How to use the pixel array from an image in sfml
I am new to sfml and want to process each pixel of an image separately.

The best way I see is to iterate over the the array of all pixels in this image. Sfml gives the handy function sf::Image::getPixelsPtr() for this. Unfortunately I can't make sense of the returned array.

I don't understand the documentation for this, how exactly can I access the color values of a certain pixel in this array?

答:
const Uint8* sf::Image::getPixelsPtr (       )   const

The returned value points to an array of RGBA pixels made of 8 bits integers components. The size of the array is width * height * 4 (getSize().x * getSize().y * 4). Warning: the returned pointer may become invalid if you modify the image, so you should never store it for too long. If the image is empty, a null pointer is returned.

From what I understand, the image is in 8-bit RGBA, and they're giving you a Uint8 pointer at the beginning of the image, which would be the 'R' of the first pixel.

// code edited. was saying 'sd' i changed to 'sf'
const UInt8* pByteBuffer = sf::Image::getPixelsPtr();

size_t numPixels = getSize().x + getSize().y;
for (int i = 0 ; i < numPixels; ++i)
    {
    UInt8 red   = pByteBuffer[4 * i];
    UInt8 green = pByteBuffer[4 * i + 1];
    UInt8 blue  = pByteBuffer[4 * i + 2];
    UInt8 alpha = pByteBuffer[4 * i + 3];
    }
```

<p>If you want to iterate on PIXELS as a whole rather than on single colors within pixels, you can reinterpret_cast the pointer they're giving you:</p>

<pre class="lang-cpp prettyprint-override"><code>const UInt8* pByteBuffer = sf::Image::getPixelsPtr();
const UInt32* pPixelBuffer = reinterpret_cast<const UInt32*>(pByteBuffer);

size_t numPixels = getSize().x * getSize().y;
for (int i = 0; i < numPixels; ++i)
    {
    uint32_t pixel = pPixelBuffer[i];
    }
</code>```

Body:
const Uint8* sf::Image::getPixelsPtr (       )   const

The returned value points to an array of RGBA pixels made of 8 bits integers components. The size of the array is width * height * 4 (getSize().x * getSize().y * 4). Warning: the returned pointer may become invalid if you modify the image, so you should never store it for too long. If the image is empty, a null pointer is returned.

From what I understand, the image is in 8-bit RGBA, and they're giving you a Uint8 pointer at the beginning of the image, which would be the 'R' of the first pixel.

// code edited. was saying 'sd' i changed to 'sf'
const UInt8* pByteBuffer = sf::Image::getPixelsPtr();

size_t numPixels = getSize().x + getSize().y;
for (int i = 0 ; i < numPixels; ++i)
    {
    UInt8 red   = pByteBuffer[4 * i];
    UInt8 green = pByteBuffer[4 * i + 1];
    UInt8 blue  = pByteBuffer[4 * i + 2];
    UInt8 alpha = pByteBuffer[4 * i + 3];
    }

If you want to iterate on PIXELS as a whole rather than on single colors within pixels, you can reinterpret_cast the pointer they're giving you:

const UInt8* pByteBuffer = sf::Image::getPixelsPtr();
const UInt32* pPixelBuffer = reinterpret_cast<const UInt32*>(pByteBuffer);

size_t numPixels = getSize().x * getSize().y;
for (int i = 0; i < numPixels; ++i)
    {
    uint32_t pixel = pPixelBuffer[i];
    }


问:
Does click lib provide a way to print the builtin help message?
I am using the click lib.

In my code , sometimes I want to print help msg ,
But the only way I know is :

```<code>python xxx --help
</code>```

But I want to print the help msg in my code using a certain function , for example:

```<code>click.print_help_msg()
</code>```

Is there a function like this ?

答:
I modified the sample on click's documentation and came up with this, I haven't used it before though, or tested the below code.

```<code>@click.command()
@click.option('--help')
def help():
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo(get_help_message())

def get_help_message():
    return "I AM A HELP MESSAGE!"
</code>```

Would something like this not work?

Body:
I am using the click lib.

In my code , sometimes I want to print help msg ,
But the only way I know is :

python xxx --help

But I want to print the help msg in my code using a certain function , for example:

click.print_help_msg()

Is there a function like this ?

Body:
I modified the sample on click's documentation and came up with this, I haven't used it before though, or tested the below code.

@click.command()
@click.option('--help')
def help():
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo(get_help_message())

def get_help_message():
    return "I AM A HELP MESSAGE!"

Would something like this not work?


问:
Products list with search field and selection field in wizard in odoo 9
Can we get product list with search field and selection field in wizard with click of button?

```<code>return {
        'type': 'ir.actions.act_window',
        'view_type': 'tree',
        'view_mode': 'tree',
        'res_model': 'product.product',
        'views': [(False, 'tree')],
        'name': 'Bulk Products',
        'target': 'new',
        }
</code>```

It only shows product list without search and selection field.

答:
i assume your want to open wizard and in wizard you need product.product selection field to select product

to do that first you need to create wizard
and in wizard .py file create field

```<code>product_id = fields.Many2one('product.product', string="product")
</code>```

and put this field in wizard's xml file in form view.

so the product list with search more option will appeared

Body:
Can we get product list with search field and selection field in wizard with click of button?

return {
        'type': 'ir.actions.act_window',
        'view_type': 'tree',
        'view_mode': 'tree',
        'res_model': 'product.product',
        'views': [(False, 'tree')],
        'name': 'Bulk Products',
        'target': 'new',
        }

It only shows product list without search and selection field.

Body:
i assume your want to open wizard and in wizard you need product.product selection field to select product

to do that first you need to create wizard
and in wizard .py file create field

product_id = fields.Many2one('product.product', string="product")

and put this field in wizard's xml file in form view.

so the product list with search more option will appeared