问:
Similarity between arrays of cirteria's ratings
I have a dictionary dataset with many items and it's ratings for a fixed set of criterias (in example, 3 criterias):

```<code>item1 = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 1 }
item2 = { "Criteria1" : 0, "Criteria2" : 1, "Criteria3" : 5 }
item3 = { "Criteria1" : 4, "Criteria2" : 2, "Criteria3" : 1 }
</code>```

I must find the best way to define the most similar items to a user item.
For example:

```<code>useritem = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 2 }
</code>```

Could be result in:

```<code>similarity = { "item1": 0.95, "item2": 0.17, "item3": 0.91 }
</code>```

Cosine's similarity is a way to achieve this?
If so, i found scikit learn that do this in python. How can I transform the item's dictionary in a ndarray to use with cosine similarity?

Tks

答:
You can use DictVectorizer for converting the dicts to features matrix of shape [n_samples, n_features] and then easily apply cosine_similarity on it.</p>

```<code>item1 = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 1 }
item2 = { "Criteria1" : 0, "Criteria2" : 1, "Criteria3" : 5 }
item3 = { "Criteria1" : 4, "Criteria2" : 2, "Criteria3" : 1 }

useritem = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 2 }

from sklearn.feature_extraction import DictVectorizer
from sklearn.metrics.pairwise import cosine_similarity

vectorizer = DictVectorizer(sparse=False)

inputData = vectorizer.fit_transform([item1, item2, item3])
toCheckData = vectorizer.transform([useritem])

similarity = cosine_similarity(inputData, toCheckData)
# Output: similarity
  array([[ 0.98524468],
         [ 0.40967325],
         [ 0.98765833]])
</code>```

Body:
I have a dictionary dataset with many items and it's ratings for a fixed set of criterias (in example, 3 criterias):

item1 = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 1 }
item2 = { "Criteria1" : 0, "Criteria2" : 1, "Criteria3" : 5 }
item3 = { "Criteria1" : 4, "Criteria2" : 2, "Criteria3" : 1 }

I must find the best way to define the most similar items to a user item.
For example:

useritem = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 2 }

Could be result in:

similarity = { "item1": 0.95, "item2": 0.17, "item3": 0.91 }

Cosine's similarity is a way to achieve this?
If so, i found scikit learn that do this in python. How can I transform the item's dictionary in a ndarray to use with cosine similarity?

Tks

Body:
You can use DictVectorizer for converting the dicts to features matrix of shape [n_samples, n_features] and then easily apply cosine_similarity on it.

item1 = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 1 }
item2 = { "Criteria1" : 0, "Criteria2" : 1, "Criteria3" : 5 }
item3 = { "Criteria1" : 4, "Criteria2" : 2, "Criteria3" : 1 }

useritem = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 2 }

from sklearn.feature_extraction import DictVectorizer
from sklearn.metrics.pairwise import cosine_similarity

vectorizer = DictVectorizer(sparse=False)

inputData = vectorizer.fit_transform([item1, item2, item3])
toCheckData = vectorizer.transform([useritem])

similarity = cosine_similarity(inputData, toCheckData)
# Output: similarity
  array([[ 0.98524468],
         [ 0.40967325],
         [ 0.98765833]])


来源: stackexchange

问:
How to access parent component class in child component
I am trying to style parent component class in child component using css . How to access parent class in the child component in angular 2</p>

答:
You can get closest classof your child element any class and reach to your required parent element/class

```<code>constructor(private el: ElementRef) {
}

ngAfterViewInit{
     let parentElement=this.el.nativeElement.closest(".yourparentClassName")[0];
     console.log(parentElement);
     if(parentElement.length>0)
     {
         //apply your style here
         parentElement.style.width=200;
     }
}
</code>```

Note: closest may not work for IE and Firefox, so you have to write logic in function where it return you closest element.

ContentLicense: CC BY-SA 3.0

Body:
You can get closest classof your child element any class and reach to your required parent element/class

constructor(private el: ElementRef) {
}

ngAfterViewInit{
     let parentElement=this.el.nativeElement.closest(".yourparentClassName")[0];
     console.log(parentElement);
     if(parentElement.length>0)
     {
         //apply your style here
         parentElement.style.width=200;
     }
}

Note: closest may not work for IE and Firefox, so you have to write logic in function where it return you closest element.


问:
Where does Messenger save photos when I take a photo using my Windows webcam?
My lady and I want to be safe she won't be sharing her photos with the world when she takes one using her webcam on Windows system. Is there a file saved in the Users files or are we ok to let her use a strangers computer to take "those" photos?</p>

答: If you want to be safe on a Windows system, i recommend not to even take photo on webcam or have on disk. It is far more than controlling a folder. Take account viruses, trojans, agent softwares, malwares and so on.</p>


问:
Treat a string as a file in python
In the interest of not rewriting an open source library,  I want to treat a string of text as a file in python 3.

Suppose I have the file contents as a string:

```<code>not_a_file = 'there is a lot of blah blah in this so-called file'
</code>```

I want to treat this variable, i.e. the contents of a file, as a  path-like object that way I can use it in python's open() function.

Here is a simple example which shows my dilemma:

```<code>not_a_file = 'there is a lot of blah blah in this so-called file'
file_ptr = open(not_a_file, 'r')
</code>```

Clearly the example doesn't work because not_a_file is not a path-like object.  I don't want to write a file nor create any temporary directories for portability purposes.

With that said, I need is to solve this mystery:

```<code>not_a_file = 'there is a lot of blah blah in this so-called file'
... Something goes here ...
file_ptr = open(also_not_a_file, 'r')
</code>```

What I've Tried So Far

I've looked into StringIO and tried using that as a path-like object and no dice:

import StringIO
output = StringIO.StringIO()
output.write('First line.\n')
file_ptr = open(output,'r')

Well this doesn't work because StringIO isn't a path-like object.

I've tried tempfile in a similar fashion with no success.

import tempfile
tp = tempfile.TemporaryFile()
tp.write(b'there is a lot of blah blah in this so-called file')
open(tp,'r')

Finally I tried mmap to see if I can write the string into memory and then open the memory pointer with open with no success.

Any help is appreciated! :-)

Edit 1: What I'm thinking of to possibly solve problem

So pathlib.PurePath can work with open() if PurePath is initialized to a file.  Perhaps I can create an instance of a class that inherits PurePath and when read by open(), it reads my string.  Let me give an example:

```<code>from pathlib import PurePath

not_a_file = 'there is a lot of blah blah in this so-called file'
class Magic(PurePath):
    def __init__(self, string_input):
        self.file_content = string_input
        PurePath.__init__(self, 'Something magical goes here')
    #some more magic happens in this class

also_not_a_file = Magic(not_a_file)
fp = open(also_not_a_file,'r')
print(fp.readlines()) # 'there is a lot of blah blah in this so-called file'
</code>```

答:
With what I can tell from your comments and recent edits, you want a file that can be opened using the open statement. (I'll leave my other answer be since it's the more correct approach to this type of question)

You can use tempfile to solve your problem, it basically is doing this: create your file, do stuff to your file, then delete your file upon closure.

```<code>import os
from tempfile import NamedTemporaryFile

f = NamedTemporaryFile(mode='w+', delete=False)
f.write("there is a lot of blah blah in this so-called file")
f.close()
with open(f.name, "r") as new_f:
    print(new_f.read())

os.unlink(f.name) # delete the file after
</code>```

Title: Treat a string as a file in python

Body:
In the interest of not rewriting an open source library,  I want to treat a string of text as a file in python 3.

Suppose I have the file contents as a string:

not_a_file = 'there is a lot of blah blah in this so-called file'

I want to treat this variable, i.e. the contents of a file, as a  path-like object that way I can use it in python's open() function.

Here is a simple example which shows my dilemma:

not_a_file = 'there is a lot of blah blah in this so-called file'
file_ptr = open(not_a_file, 'r')

Clearly the example doesn't work because not_a_file is not a path-like object.  I don't want to write a file nor create any temporary directories for portability purposes.

With that said, I need is to solve this mystery:

not_a_file = 'there is a lot of blah blah in this so-called file'
... Something goes here ...
file_ptr = open(also_not_a_file, 'r')

What I've Tried So Far

I've looked into StringIO and tried using that as a path-like object and no dice:

import StringIO
output = StringIO.StringIO()
output.write('First line.\n')
file_ptr = open(output,'r')

Well this doesn't work because StringIO isn't a path-like object.

I've tried tempfile in a similar fashion with no success.

import tempfile
tp = tempfile.TemporaryFile()
tp.write(b'there is a lot of blah blah in this so-called file')
open(tp,'r')

Finally I tried mmap to see if I can write the string into memory and then open the memory pointer with open with no success.

Any help is appreciated! :-)

Edit 1: What I'm thinking of to possibly solve problem

So pathlib.PurePath can work with open() if PurePath is initialized to a file.  Perhaps I can create an instance of a class that inherits PurePath and when read by open(), it reads my string.  Let me give an example:

from pathlib import PurePath

not_a_file = 'there is a lot of blah blah in this so-called file'
class Magic(PurePath):
    def __init__(self, string_input):
        self.file_content = string_input
        PurePath.__init__(self, 'Something magical goes here')
    #some more magic happens in this class

also_not_a_file = Magic(not_a_file)
fp = open(also_not_a_file,'r')
print(fp.readlines()) # 'there is a lot of blah blah in this so-called file'

Body:
With what I can tell from your comments and recent edits, you want a file that can be opened using the open statement. (I'll leave my other answer be since it's the more correct approach to this type of question)

You can use tempfile to solve your problem, it basically is doing this: create your file, do stuff to your file, then delete your file upon closure.

import os
from tempfile import NamedTemporaryFile

f = NamedTemporaryFile(mode='w+', delete=False)
f.write("there is a lot of blah blah in this so-called file")
f.close()
with open(f.name, "r") as new_f:
    print(new_f.read())

os.unlink(f.name) # delete the file after


问:
how can we use uglify for multiple file outputs
Is it possible to compile each file separeately in uglify js instaed of uglifying in to one single file.

uglifyjs assets/src/js/ *js  -o assets/dist/js/ *.min.js -c

like this

答:
```<code>module.exports = function(grunt) {

    grunt.config.set('uglify', {
        options: {
            mangle: false,
            sourceMap: false,
            screwIE8: true,
            compress: {
                unused: false,
                drop_console: true
            }
        },

    uglifyjsfiles:{
            files: grunt.file.expandMapping(['.tmp/public/js/app/**/*.js'], '', {
                rename: function(destBase, destPath) {
                    return destBase+destPath.replace('.js', '.min.js');
                }
            })
    },

 });

    grunt.loadNpmTasks('grunt-contrib-uglify');
};
</code>```

Now run grunt uglify:uglifyjsfiles

Body:
module.exports = function(grunt) {

    grunt.config.set('uglify', {
        options: {
            mangle: false,
            sourceMap: false,
            screwIE8: true,
            compress: {
                unused: false,
                drop_console: true
            }
        },

    uglifyjsfiles:{
            files: grunt.file.expandMapping(['.tmp/public/js/app/**/*.js'], '', {
                rename: function(destBase, destPath) {
                    return destBase+destPath.replace('.js', '.min.js');
                }
            })
    },

 });

    grunt.loadNpmTasks('grunt-contrib-uglify');
};

Now run grunt uglify:uglifyjsfiles


问:
How to reuse the code of the containing app for action extension?
I want to reuse the code of the containing app for action extension with objective c. In the documentation it is written that you cant launch the main/containing app. So how to implement the partial functionality of the app in action extension with reusing the code. Any help is appreciated.</p>

答: Add the file that contains the desired functionality to the extension target. You can change this in a few ways. You can manually add that file to the Compiled Sources section for the target under Build Phases. Or you can select the file and inspect its Target Membership in the File Inspector pane on the right hand side.


问:
Eloquent updateOrInsert
I would like the eloquent to be able to auto-feed the created_at and updated_at fields, using the following commands below</p>

```<code>                DB::table('partida')->updateOrInsert(
                    [
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id
                    ],
                    [
                        'partida_id' => $key,
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id,
                        'partida_data' => (string)$value->partida_data,
                        'placar_mandante' => $value->placar_oficial_mandante,
                        'placar_visitante' => $value->placar_oficial_visitante,
                        'local' => (string)$value->local
                    ]
                );
</code>```

答:
What you want is a part Eloquent. Though you are using Query Builder

If you want to continue using Query Builder I suggest you append the following in your array.

```<code>                DB::table('partida')->updateOrInsert(
                [
                    'rodada' => $values->rodada,
                    'mandante_fk' => $value->clube_casa_id,
                    'visitante_fk' => $value->clube_visitante_id,
                    'created_at' =>  \Carbon\Carbon::now(),
                    'updated_at' => \Carbon\Carbon::now()
                ],
                [
                    'partida_id' => $key,
                    'rodada' => $values->rodada,
                    'mandante_fk' => $value->clube_casa_id,
                    'visitante_fk' => $value->clube_visitante_id,
                    'partida_data' => (string)$value->partida_data,
                    'placar_mandante' => $value->placar_oficial_mandante,
                    'placar_visitante' => $value->placar_oficial_visitante,
                    'local' => (string)$value->local,
                    'created_at' =>  \Carbon\Carbon::now(),
                    'updated_at' => \Carbon\Carbon::now()
                ]
            );
</code>```

Title: Eloquent updateOrInsert

Body:
I would like the eloquent to be able to auto-feed the created_at and updated_at fields, using the following commands below

                DB::table('partida')->updateOrInsert(
                    [
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id
                    ],
                    [
                        'partida_id' => $key,
                        'rodada' => $values->rodada,
                        'mandante_fk' => $value->clube_casa_id,
                        'visitante_fk' => $value->clube_visitante_id,
                        'partida_data' => (string)$value->partida_data,
                        'placar_mandante' => $value->placar_oficial_mandante,
                        'placar_visitante' => $value->placar_oficial_visitante,
                        'local' => (string)$value->local
                    ]
                );

Body:
What you want is a part Eloquent. Though you are using Query Builder

If you want to continue using Query Builder I suggest you append the following in your array.

                DB::table('partida')->updateOrInsert(
                [
                    'rodada' => $values->rodada,
                    'mandante_fk' => $value->clube_casa_id,
                    'visitante_fk' => $value->clube_visitante_id,
                    'created_at' =>  \Carbon\Carbon::now(),
                    'updated_at' => \Carbon\Carbon::now()
                ],
                [
                    'partida_id' => $key,
                    'rodada' => $values->rodada,
                    'mandante_fk' => $value->clube_casa_id,
                    'visitante_fk' => $value->clube_visitante_id,
                    'partida_data' => (string)$value->partida_data,
                    'placar_mandante' => $value->placar_oficial_mandante,
                    'placar_visitante' => $value->placar_oficial_visitante,
                    'local' => (string)$value->local,
                    'created_at' =>  \Carbon\Carbon::now(),
                    'updated_at' => \Carbon\Carbon::now()
                ]
            );


问:
Angular Schema form - Override the input type of a field
Consider the schema

```<code>{
  "type": "object",
  "title": "Comment",
  "properties": {
    "name": {
      "title": "Name",
      "type": "string"
    },
    "gender":{
        "title":"Gender",
        "type":"string",
        "enum":["m","f"]
    },
    "comment": {
      "title": "Comment",
      "type": "string",
      "maxLength": 20,
      "validationMessage": "Don't be greedy!"
    }
  },
  "required": [
    "name",
    "email",
    "comment"
  ]
}
</code>```

How can I override the html form type of gender from select to some another type(like input type text) without using the x-schema-form property and without rewriting the whole fields for the form (using the "*" and just altering the required fields). I tried the following form definition but the field repeats.

```<code>[
  "*",
  {
      "key":"gender",
      "type":"text"
  },
  {
    "type": "submit",
    "style": "btn-info",
    "title": "OK"
  }
]
</code>```

The above definition will show two gender fields, one of type select and other of type text. My requirement is to display only one gender of type text where the gender of type select is displayed.

答: As of v1.0.0-alpha.1 the ability to use the key "..." has been added to allow adding the remaining undefined schema property keys in the form definition.</p>

Body:
Consider the schema

{
  "type": "object",
  "title": "Comment",
  "properties": {
    "name": {
      "title": "Name",
      "type": "string"
    },
    "gender":{
        "title":"Gender",
        "type":"string",
        "enum":["m","f"]
    },
    "comment": {
      "title": "Comment",
      "type": "string",
      "maxLength": 20,
      "validationMessage": "Don't be greedy!"
    }
  },
  "required": [
    "name",
    "email",
    "comment"
  ]
}

How can I override the html form type of gender from select to some another type(like input type text) without using the x-schema-form property and without rewriting the whole fields for the form (using the "*" and just altering the required fields). I tried the following form definition but the field repeats.

[
  "*",
  {
      "key":"gender",
      "type":"text"
  },
  {
    "type": "submit",
    "style": "btn-info",
    "title": "OK"
  }
]

The above definition will show two gender fields, one of type select and other of type text. My requirement is to display only one gender of type text where the gender of type select is displayed.


问:
Copy table data from one object to another object AX 2012
I'm trying to do a Job which used to Copy and insert Journal Names from one entity to another entity. Below code able to handle only fields only I hardcoded. But I'm trying to do a code which will be useful in future i.e if we add new custom field to the table. My code should able to copy data of that newly custom field added.

```<code>static void sa_CopyData(Args _args)
{
    LedgerJournalName   tblLedgerJournalNameSource, tblLedgerJournalNameDesination;
    NumberSequenceTable tblNST, tblNSTCopy;
    NumberSequenceScope tblNSS;
    Counter             countIN, countOUT;
    DataAreaId          sourceEntity, destinationEntity;

    sourceEntity    = 'CNUS';
    destinationEntity = 'CNEN';
    //Journal Names creation
    changeCompany(sourceEntity)
    {
        tblLedgerJournalNameSource = null;
        while select * from tblLedgerJournalNameSource
            where tblLedgerJournalNameSource.dataAreaId == sourceEntity
        {
            ++countIN;
            tblNSTcopy = null; tblNST = null; tblNSS = null;

            select * from tblNSTcopy
            where tblNSTCopy.RecId == tblLedgerJournalNameSource.NumberSequenceTable;

            changeCompany(destinationEntity)
            {
                tblNST = null; tblNSS = null; tblLedgerJournalNameDesination = null;

                select * from tblNST
                    join tblNSS
                    where tblNST.NumberSequenceScope == tblNSS.RecId
                    && tblNST.NumberSequence == tblNSTCopy.NumberSequence
                    && tblNSS.DataArea == destinationEntity;

                //Insert only if Journal name is not exists
                if(!(LedgerJournalName::find(tblLedgerJournalNameSource.JournalName)))
                {
                    ttsBegin;
                    tblLedgerJournalNameDesination.initValue();
                    tblLedgerJournalNameDesination.JournalName = tblLedgerJournalNameSource.JournalName;
                    tblLedgerJournalNameDesination.Name = tblLedgerJournalNameSource.Name;
                    tblLedgerJournalNameDesination.JournalType = tblLedgerJournalNameSource.JournalType;
                    tblLedgerJournalNameDesination.ApproveActive = tblLedgerJournalNameSource.ApproveActive;
                    tblLedgerJournalNameDesination.ApproveGroupId = tblLedgerJournalNameSource.ApproveGroupId;
                    tblLedgerJournalNameDesination.NoAutoPost = tblLedgerJournalNameSource.NoAutoPost;
                    tblLedgerJournalNameDesination.WorkflowApproval = tblLedgerJournalNameSource.WorkflowApproval;
                    tblLedgerJournalNameDesination.Configuration = tblLedgerJournalNameSource.Configuration;
                    if (!tblNST.RecId)
                    {
                        info(strFmt('Number Sequence is not updated for %1 > Entity %2', tblLedgerJournalNameDesination.JournalName, destinationEntity));
                    }
                    tblLedgerJournalNameDesination.NumberSequenceTable = tblNST.recid;
                    tblLedgerJournalNameDesination.NewVoucher = tblLedgerJournalNameSource.NewVoucher;
                    tblLedgerJournalNameDesination.BlockUserGroupId = tblLedgerJournalNameSource.BlockUserGroupId;
                    tblLedgerJournalNameDesination.FixedOffsetAccount = tblLedgerJournalNameSource.FixedOffsetAccount;
                    tblLedgerJournalNameDesination.OffsetAccountType = tblLedgerJournalNameSource.OffsetAccountType;
                    tblLedgerJournalNameDesination.OffsetLedgerDimension = tblLedgerJournalNameSource.OffsetLedgerDimension;
                    tblLedgerJournalNameDesination.LedgerJournalInclTax = tblLedgerJournalNameSource.LedgerJournalInclTax;
                    tblLedgerJournalNameDesination.insert();
                    ttsCommit;
                    ++countOUT;
                }
            }
        }
    }

    info(strFmt('Journal Names Creation > Read: %1, Inserted: %2', countIN, countOUT));
}
</code>```

Please let me know if you have any suggestions.

答:
Use buf2buf(from, to). https://msdn.microsoft.com/en-us/library/global.buf2buf.aspx

It does not perform an insert, so after you do buf2buf() you can modify any fields you want in the target before doing an insert.

You could do tblLedgerJournalNameDesination.data(tblLedgerJournalNameSource); but that also copies system fields, which you most likely do not want.

You can also look at the source code behind Global::buf2Buf(from, to) and modify that logic if you want.

Body:
I'm trying to do a Job which used to Copy and insert Journal Names from one entity to another entity. Below code able to handle only fields only I hardcoded. But I'm trying to do a code which will be useful in future i.e if we add new custom field to the table. My code should able to copy data of that newly custom field added.

static void sa_CopyData(Args _args)
{
    LedgerJournalName   tblLedgerJournalNameSource, tblLedgerJournalNameDesination;
    NumberSequenceTable tblNST, tblNSTCopy;
    NumberSequenceScope tblNSS;
    Counter             countIN, countOUT;
    DataAreaId          sourceEntity, destinationEntity;

    sourceEntity    = 'CNUS';
    destinationEntity = 'CNEN';
    //Journal Names creation
    changeCompany(sourceEntity)
    {
        tblLedgerJournalNameSource = null;
        while select * from tblLedgerJournalNameSource
            where tblLedgerJournalNameSource.dataAreaId == sourceEntity
        {
            ++countIN;
            tblNSTcopy = null; tblNST = null; tblNSS = null;

            select * from tblNSTcopy
            where tblNSTCopy.RecId == tblLedgerJournalNameSource.NumberSequenceTable;

            changeCompany(destinationEntity)
            {
                tblNST = null; tblNSS = null; tblLedgerJournalNameDesination = null;

                select * from tblNST
                    join tblNSS
                    where tblNST.NumberSequenceScope == tblNSS.RecId
                    && tblNST.NumberSequence == tblNSTCopy.NumberSequence
                    && tblNSS.DataArea == destinationEntity;

                //Insert only if Journal name is not exists
                if(!(LedgerJournalName::find(tblLedgerJournalNameSource.JournalName)))
                {
                    ttsBegin;
                    tblLedgerJournalNameDesination.initValue();
                    tblLedgerJournalNameDesination.JournalName = tblLedgerJournalNameSource.JournalName;
                    tblLedgerJournalNameDesination.Name = tblLedgerJournalNameSource.Name;
                    tblLedgerJournalNameDesination.JournalType = tblLedgerJournalNameSource.JournalType;
                    tblLedgerJournalNameDesination.ApproveActive = tblLedgerJournalNameSource.ApproveActive;
                    tblLedgerJournalNameDesination.ApproveGroupId = tblLedgerJournalNameSource.ApproveGroupId;
                    tblLedgerJournalNameDesination.NoAutoPost = tblLedgerJournalNameSource.NoAutoPost;
                    tblLedgerJournalNameDesination.WorkflowApproval = tblLedgerJournalNameSource.WorkflowApproval;
                    tblLedgerJournalNameDesination.Configuration = tblLedgerJournalNameSource.Configuration;
                    if (!tblNST.RecId)
                    {
                        info(strFmt('Number Sequence is not updated for %1 > Entity %2', tblLedgerJournalNameDesination.JournalName, destinationEntity));
                    }
                    tblLedgerJournalNameDesination.NumberSequenceTable = tblNST.recid;
                    tblLedgerJournalNameDesination.NewVoucher = tblLedgerJournalNameSource.NewVoucher;
                    tblLedgerJournalNameDesination.BlockUserGroupId = tblLedgerJournalNameSource.BlockUserGroupId;
                    tblLedgerJournalNameDesination.FixedOffsetAccount = tblLedgerJournalNameSource.FixedOffsetAccount;
                    tblLedgerJournalNameDesination.OffsetAccountType = tblLedgerJournalNameSource.OffsetAccountType;
                    tblLedgerJournalNameDesination.OffsetLedgerDimension = tblLedgerJournalNameSource.OffsetLedgerDimension;
                    tblLedgerJournalNameDesination.LedgerJournalInclTax = tblLedgerJournalNameSource.LedgerJournalInclTax;
                    tblLedgerJournalNameDesination.insert();
                    ttsCommit;
                    ++countOUT;
                }
            }
        }
    }

    info(strFmt('Journal Names Creation > Read: %1, Inserted: %2', countIN, countOUT));
}

Please let me know if you have any suggestions.


问:
How To Use Tesseract OCR in PHP?
I am using XAMPP on my Windows.
I wanted to use Tesseract OCR in PHP

My tesseract installed in

```<code>C:/Program Files/Tesseract OCR/
</code>```

And XAMPP was installed in

```<code>C:/xampp/
</code>```

I am using this code to exec the Tesseract in my PHP

```<code>exec("tesseract test.png test.txt");
</code>```

But it's not working...

答:
```<code>#Debes tener eng.traineddata y el tesseract.exe en la carpeta prueba#
//este codigo funciona en el servidor local
<?php
$imagen = file_get_contents('http://e-consultaruc.sunat.gob.pe/cl-ti-
itmrconsruc/captcha?accion=image');
file_put_contents('C:\AppServ\www\Sitio AAA\Prueba\foto.jpg', $imagen);
exec("tesseract.exe foto.jpg mitexto2.txt");
?>
<form action="obtener_imagen_captcha.php" method="post">
<input type="submit" value="Aceptar">
</form>
</code>```

ContentLicense: CC BY-SA 4.0

Title: How To Use Tesseract OCR in PHP?

Body:
I am using XAMPP on my Windows.
I wanted to use Tesseract OCR in PHP

My tesseract installed in

C:/Program Files/Tesseract OCR/

And XAMPP was installed in

C:/xampp/

I am using this code to exec the Tesseract in my PHP

exec("tesseract test.png test.txt");

But it's not working...


问:
Python: Replace datetime64[ns] into a index in pandas
I want to replace the last Date (which is index) from 2017-06-18 to date_replace which is in datetime64 format. However, I get error when I replace it, the code is as below:

```<code>>>> date_replace
0   2017-06-19
Name: trading_day, dtype: datetime64[ns]

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2017-06-13   AD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2017-06-16   AD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2017-06-17   AD  5.210000  5.560000  5.210000  5.560000  5.560000    200
2017-06-18   AD  5.200000  5.250000  5.200000  5.250000  5.250000    9000

>>> df.index[-1] = date_replace
TypeError: Index does not support mutable operations

>>> import datetime
>>> df.rename({df.index[-1]: datetime.date.date_replace()}, inplace = True)
AttributeError: type object 'datetime.date' has no attribute 'date_replace'
</code>```

The output I want:

```<code>           Stock      Open      High       Low     Close Adj Close  Volume
Date
2017-06-13   AD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2017-06-16   AD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2017-06-17   AD  5.210000  5.560000  5.210000  5.560000  5.560000    200
2017-06-19   AD  5.200000  5.250000  5.200000  5.250000  5.250000    9000
</code>```

SO how to replace the date elegantly with no error and same format?

答:
use pd.DataFrame.rename.  You can pass a dictionary to the index parameter to specify which indices get renamed to what.

```<code>df.rename(index={df.index[-1]: date_replace[0]})

           Stock  Open  High   Low  Close  Adj Close  Volume
Date
2017-06-13    AD  5.23  5.26  5.20   5.26       5.26    5000
2017-06-16    AD  5.22  5.26  5.22   5.26       5.26    6000
2017-06-17    AD  5.21  5.56  5.21   5.56       5.56     200
2017-06-19    AD  5.20  5.25  5.20   5.25       5.25    9000

</code>```

Body:
I want to replace the last Date (which is index) from 2017-06-18 to date_replace which is in datetime64 format. However, I get error when I replace it, the code is as below:

>>> date_replace
0   2017-06-19
Name: trading_day, dtype: datetime64[ns]

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2017-06-13   AD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2017-06-16   AD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2017-06-17   AD  5.210000  5.560000  5.210000  5.560000  5.560000    200
2017-06-18   AD  5.200000  5.250000  5.200000  5.250000  5.250000    9000

>>> df.index[-1] = date_replace
TypeError: Index does not support mutable operations

>>> import datetime
>>> df.rename({df.index[-1]: datetime.date.date_replace()}, inplace = True)
AttributeError: type object 'datetime.date' has no attribute 'date_replace'

The output I want:

           Stock      Open      High       Low     Close Adj Close  Volume
Date
2017-06-13   AD  5.230000  5.260000  5.200000  5.260000  5.260000    5000
2017-06-16   AD  5.220000  5.260000  5.220000  5.260000  5.260000    6000
2017-06-17   AD  5.210000  5.560000  5.210000  5.560000  5.560000    200
2017-06-19   AD  5.200000  5.250000  5.200000  5.250000  5.250000    9000

SO how to replace the date elegantly with no error and same format?

Body:
use pd.DataFrame.rename.  You can pass a dictionary to the index parameter to specify which indices get renamed to what.

df.rename(index={df.index[-1]: date_replace[0]})

           Stock  Open  High   Low  Close  Adj Close  Volume
Date
2017-06-13    AD  5.23  5.26  5.20   5.26       5.26    5000
2017-06-16    AD  5.22  5.26  5.22   5.26       5.26    6000
2017-06-17    AD  5.21  5.56  5.21   5.56       5.56     200
2017-06-19    AD  5.20  5.25  5.20   5.25       5.25    9000


问:
Connecting two Combo-boxes with html and js
I am trying to make these two combo-boxes join each other. But, my problem is, that my second combo-box cannot change if I select the category.

This is what I've done.

HTML CODE

```<code><!-- language: lang-html -->

<label for="JenisBarang">Jenis Barang</label>
<br>
<select id="JenisBarang" name="JenisBarang">
    <option value="0" selected="selected">Mouse</option>
    <option value="1">Keyboard</option>
    <option value="2">Webcam</option>
</select>
<br>

<label for="PilihBarang">Pilih Barang</label>
<br>
<select id="PilihBarang_0" name="PilihBarang_0" style="display: inline;">
    <option value="1">Asus GX-1000</option>
    <option value="2">Logitech M238 Edisi : Burung Hantu</option>
    <option value="3">Logitech M238 Edisi : Astronot</option>
    <option value="4">Logitech M238 Edisi : Musang</option>
    <option value="5">Logitech M238 Edisi : Kera</option>
    <option value="6">Lenovo N700</option>
    <option value="7">Asus Gladius</option>
</select>
<select id="PilihBarang_1" name="PilihBarang_1" style="display: none;">
    <option value="1">Logitech K400r</option>
    <option value="2">Logitech MK240</option>
    <option value="3">Asus GK2000</option>
</select>
<select id="PilihBarang_2" name="PilihBarang_2" style="display: none;">
    <option value="1">Lenovo Webcam</option>
    <option value="2">Logitech C920</option>
</select>
<br>
</code>```

Java Script CODE

```<code><script>
    function change_product(evt)
    {
    var JenisBarang=document.getElementById('JenisBarang'),whichstate;

    whichstate=JenisBarang.options[state.selectedIndex].value;

    for(var i=0;i<JenisBarang.options.length;i++)
       document.getElementById('PilihBarang_'+i).style.display=(i==whichstate ? 'inline':'none');
    }
</script>
</code>```

Dictionary

JenisBarang means the category ex Mouse

PilihBarang means the items ex Mouse Logitech M185

答:
Can you check the following Code. use value specify options in the second combo box. It is a simple code hope nothing to explain.. I have placed couple of comments.

$("#comboBox1").change(function() {
  if ($(this).data('options') === undefined) {
    /* Get all the options in second Combo box*/
    $(this).data('options', $('#comboBox2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#comboBox2').html(options);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<select name="comboBox1" id="comboBox1">
  <option value="0">Please Select</option>
  <option value="1">Mouse</option>
  <option value="2">Keyboard</option>
  <option value="3">WebCam</option>
</select>

<!-- Second Combo Box-->
<select name="comboBox2" id="comboBox2">
  <option value="1">Mouse Model 1</option>
  <option value="1">Mouse Model 2</option>
  <option value="1">Mouse Model 3</option>
  <option value="2">Keyboard model 1</option>
  <option value="2">Keyboard model 2</option>
  <option value="2">Keyboard model 3</option>
  <option value="3">webcam model 1</option>
  <option value="3">webcam model 2</option>
</select></code>```

Edit : JS Fiddle link JS Fiddle

Body:
I am trying to make these two combo-boxes join each other. But, my problem is, that my second combo-box cannot change if I select the category.

This is what I've done.

HTML CODE

Jenis Barang

<select id="JenisBarang" name="JenisBarang">
    <option value="0" selected="selected">Mouse</option>
    <option value="1">Keyboard</option>
    <option value="2">Webcam</option>
</select>

Pilih Barang

<select id="PilihBarang_0" name="PilihBarang_0" style="display: inline;">
    <option value="1">Asus GX-1000</option>
    <option value="2">Logitech M238 Edisi : Burung Hantu</option>
    <option value="3">Logitech M238 Edisi : Astronot</option>
    <option value="4">Logitech M238 Edisi : Musang</option>
    <option value="5">Logitech M238 Edisi : Kera</option>
    <option value="6">Lenovo N700</option>
    <option value="7">Asus Gladius</option>
</select>
<select id="PilihBarang_1" name="PilihBarang_1" style="display: none;">
    <option value="1">Logitech K400r</option>
    <option value="2">Logitech MK240</option>
    <option value="3">Asus GK2000</option>
</select>
<select id="PilihBarang_2" name="PilihBarang_2" style="display: none;">
    <option value="1">Lenovo Webcam</option>
    <option value="2">Logitech C920</option>
</select>

Java Script CODE

Dictionary

JenisBarang means the category ex Mouse

PilihBarang means the items ex Mouse Logitech M185

Body:
Can you check the following Code. use value specify options in the second combo box. It is a simple code hope nothing to explain.. I have placed couple of comments.

$("#comboBox1").change(function() {
  if ($(this).data('options') === undefined) {
    /* Get all the options in second Combo box*/
    $(this).data('options', $('#comboBox2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#comboBox2').html(options);
});

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

<select name="comboBox1" id="comboBox1">
  <option value="0">Please Select</option>
  <option value="1">Mouse</option>
  <option value="2">Keyboard</option>
  <option value="3">WebCam</option>
</select>

<!-- Second Combo Box-->
<select name="comboBox2" id="comboBox2">
  <option value="1">Mouse Model 1</option>
  <option value="1">Mouse Model 2</option>
  <option value="1">Mouse Model 3</option>
  <option value="2">Keyboard model 1</option>
  <option value="2">Keyboard model 2</option>
  <option value="2">Keyboard model 3</option>
  <option value="3">webcam model 1</option>
  <option value="3">webcam model 2</option>
</select>

Edit : JS Fiddle link JS Fiddle


问:
factorial of a number
I have the following code but it is not giving perfect result for factorial can u find it out plz</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
</code>```

答:
The important part of the function is this line:

```<code> x = x * fact(x-1);
</code>```

but the fact function does not return a value, so this is the same as x * undefined. Try adding return x; to the bottom of your function.

ContentLicense: CC BY-SA 2.5

Title: factorial of a number

Body:
I have the following code but it is not giving perfect result for factorial can u find it out plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1">

  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>

Body:
The important part of the function is this line:

 x = x * fact(x-1);

but the fact function does not return a value, so this is the same as x * undefined. Try adding return x; to the bottom of your function.


问:
Regex for a random set of chars and digits
I am looking for a regex that matches only when it sees a string that is randomly filled by digits and chars.

For example, adfak332arg3 is allowed but 332352 and fagaaah are not allowed. .*[^\\s] looks fine for strings with only chars but how to fix it to accepts the desired strings and refuses the other two types?

Body:
You can try this regex

"[\\d\\w]*\\d\\w[\\d\\w]*|[\\d\\w]*\\w\\d[\\d\\w]*"


问:
How do I add several .cpp files into a single CMakeLists.txt
I currently have a project with a template for one CMakeLists.txt for one executable, one header and one .cpp file. I would like for it to have several .cpp files, but still have it all compiled and build. How should I make the CMakeLists.txt file build and compile all the .cpp files, and how can I check if it worked?

答:
How should I make the CMakeLists file build and compile all the .cpp files

add_executable in cmake accepts more than just one argument.
So write your .cpp files as follows:

```<code>add_executable(my_project_executable main.cpp include/helper.cpp ...)
</code>```

Furthermore, using set is a basic practice for this, as follows:

```<code>set(SOURCES main.cpp include/helper.cpp ...)
add_executable(my_project_executable ${SOURCES})
</code>```

how can I check if it worked?

Well, why don't you just build it to see if it works?

```<code># See it build okay.
$ cmake .
$ make
</code>```

Body:
How should I make the CMakeLists file build and compile all the .cpp files

add_executable in cmake accepts more than just one argument.
So write your .cpp files as follows:

add_executable(my_project_executable main.cpp include/helper.cpp ...)

Furthermore, using set is a basic practice for this, as follows:

set(SOURCES main.cpp include/helper.cpp ...)
add_executable(my_project_executable ${SOURCES})

how can I check if it worked?

Well, why don't you just build it to see if it works?

# See it build okay.
$ cmake .
$ make


问:
Listen to any changes (caused by code) in value of an HTML element
I can use some events like "oninput", "onchange" ... to detect if an HTML element change its value. But these events occurs only when user manually change the value (By keyboard, mouse...)

But sometimes HTML elements's values are changed by my code (not by users) or by form's reset() method and I also want to listen to these change events.

So how can I detect when a value of an element changes? (In all situations)

答:
You could try something like this:

```<code>document.ewatch=[];
watchEle=(id,callback)=>{
    var ii=document.ewatch.length;
    document.ewatch[ii]={};
    var we={
        watch_id:ii,
        ele:document.getElementById(id)
    };
    we.fun=callback;
    we.old=we.ele.innerHTML;
    we.watch_code=function(){
        var id=ii;
        var ee=document.ewatch[id];
        var new1=ee.ele.innerHTML;
        if(new1!=ee.old){
            we.fun(ee.old,new1);
            ee.old=new1;
            document.ewatch[id]=ee;
        }
    };
    document.ewatch[ii]=we;
    return {
        start:()=>{
            we.interval=setInterval(we.watch_code,100);
        },
        stop:()=>{
            try{
                clearInterval(we.interval);
            }catch(e){}
        }
    };
};
var e1=watchEle("ele_id",(oldc,newc)=>{
    alert("content change");
});
e1.start();
</code>```

Attaches a watcher to an element, and watches the innerHTML content, and executes the callback on the event it changes.

For your question, you could change .innerHTML to .value

Body:
You could try something like this:

document.ewatch=[];
watchEle=(id,callback)=>{
    var ii=document.ewatch.length;
    document.ewatch[ii]={};
    var we={
        watch_id:ii,
        ele:document.getElementById(id)
    };
    we.fun=callback;
    we.old=we.ele.innerHTML;
    we.watch_code=function(){
        var id=ii;
        var ee=document.ewatch[id];
        var new1=ee.ele.innerHTML;
        if(new1!=ee.old){
            we.fun(ee.old,new1);
            ee.old=new1;
            document.ewatch[id]=ee;
        }
    };
    document.ewatch[ii]=we;
    return {
        start:()=>{
            we.interval=setInterval(we.watch_code,100);
        },
        stop:()=>{
            try{
                clearInterval(we.interval);
            }catch(e){}
        }
    };
};
var e1=watchEle("ele_id",(oldc,newc)=>{
    alert("content change");
});
e1.start();

Attaches a watcher to an element, and watches the innerHTML content, and executes the callback on the event it changes.

For your question, you could change .innerHTML to .value


问:
Invalid conversion from throwing function of type '(_) throws -> ()' to non-throwing function type '(DataSnapshot) -> Void'
I have following error:

Invalid conversion from throwing function of type '(_) throws -> ()'
  to non-throwing function type '(DataSnapshot) -> Void'

```<code>func getUserList() throws {
    var ref: DatabaseReference!
    ref = Database.database().reference()
    ref.child("User").observeSingleEvent(of: .value, with: { (snapshot) in

    let value = snapshot.value as? NSDictionary
        let keys = value?.allKeys

        for key in keys! {
        let dict = value?[key] as? NSDictionary
        let user = User.init(name: dict?["Name"] as? String ?? "", selected: dict?["Selected"] as? String ?? "")
        let viewUser = ViewUser.init(user: user)
            self.data.append(viewUser)

            debugPrint(user ?? "")
        }
        self.tableView.reloadData()

        if value?.count == 0 {
            throw UserError.Empty
        }
    })
}
</code>```

答:
You are throwing an error in the completion block. This is not possible and causes the error.

The return value of the closure is not related to the return value of the enclosing function – strictly spoken throws is not a return value but is affected, too.

To be able to return something from the closure you have to implement a completion block rather than throws

```<code>func getUserList(completion : (Error?) -> ())
</code>```

and use it

```<code>completion(value.isEmpty ? UserError.Empty : nil)
</code>```

Side-note: You are using too many question and exclamation marks. Use optional binding to unwrap optionals for example (and use Swift native collection types)

```<code>if let value = snapshot.value as? [String:Any] {
   for key in value.keys { ...
</code>```

Body:
I have following error:

Invalid conversion from throwing function of type '(_) throws -> ()'
  to non-throwing function type '(DataSnapshot) -> Void'

func getUserList() throws {
    var ref: DatabaseReference!
    ref = Database.database().reference()
    ref.child("User").observeSingleEvent(of: .value, with: { (snapshot) in

    let value = snapshot.value as? NSDictionary
        let keys = value?.allKeys

        for key in keys! {
        let dict = value?[key] as? NSDictionary
        let user = User.init(name: dict?["Name"] as? String ?? "", selected: dict?["Selected"] as? String ?? "")
        let viewUser = ViewUser.init(user: user)
            self.data.append(viewUser)

            debugPrint(user ?? "")
        }
        self.tableView.reloadData()

        if value?.count == 0 {
            throw UserError.Empty
        }
    })
}

Body:
You are throwing an error in the completion block. This is not possible and causes the error.

The return value of the closure is not related to the return value of the enclosing function – strictly spoken throws is not a return value but is affected, too.

To be able to return something from the closure you have to implement a completion block rather than throws

func getUserList(completion : (Error?) -> ())

and use it

completion(value.isEmpty ? UserError.Empty : nil)

Side-note: You are using too many question and exclamation marks. Use optional binding to unwrap optionals for example (and use Swift native collection types)

if let value = snapshot.value as? [String:Any] {
   for key in value.keys { ...


问:
IntelliJ Javascript "Cannot Find Declaration to go to" when using custom module path
I'm trying to use Javascript ES6 import syntax with WebPack configured to use client and node_modules as root paths for resolving imports.

IntelliJ Idea discovers modules from "node_modules" directory, but it cannot resolve paths from "client" directory.

For example:

When im using:

import ImmutableStore from 'alt/utils/ImmutableUtil'; - IntelliJ finds proper paths, because alt module is on node_modules directory

import CustomiserActions from 'js/actions/Customiser.actions.js'; - It doesn't work, because js module is in client directory.

I've tried many options in module settings/project settings/marking directory as source roots/adding external libraries but nothing seems to work.

IntelliJ Idea version: 14.1.5

答: I know this is old thread. Just for reference, mark the parent directory(in this case 'js') as 'Resource Root,' then Intellisense will work on 2016 version.</p>


问:
ASP.Net: How to control div-style in backend?
I will control the style from a div-container from the backend (c#, code behind).

I will not use the runat="server"-tag, because the div-id is much used in javaScript.

How to do?

答:
I would do as RPM1984 suggest and use ClientIdMode="Static" if you use .Net 4.0 as he says. But if that is not an option just wrap your div in a div that hasn't runat="server" like:

```<code><div id="wrapperDiv">
    <div id="innerDiv" runat="server">additional stuff</div>
</div>
</code>```

That should work and it would be fairly straight forward to access the inner div using the outer div's id in jQuery:

```<code>$(document).ready(function() {
    $('#wrapperDiv > div').css('display', 'none');
});
</code>```

Body:
I would do as RPM1984 suggest and use ClientIdMode="Static" if you use .Net 4.0 as he says. But if that is not an option just wrap your div in a div that hasn't runat="server" like:

<div id="wrapperDiv">
    <div id="innerDiv" runat="server">additional stuff</div>
</div>

That should work and it would be fairly straight forward to access the inner div using the outer div's id in jQuery:

$(document).ready(function() {
    $('#wrapperDiv > div').css('display', 'none');
});


问:
Using Caffe in C++; Unable to pass caffe::SolverParameter to function without error
I am attempting to compile the "Hello World XOR" C++ example given by:

https://medium.com/@shiyan/caffe-c-helloworld-example-with-memorydata-input-20c692a82a22

Hardware:
EX50-UD3R Motherboard
GT-640 NVidia cards (2 Cards)
Intel 980 (6 core)
16Gig (4x4) DDR3 RAM

Environment:
Ubuntu 16.04.2 LTS   Kernel: 4.4.0-78-generic
Eclipse Neon3 R4.6.3
CUDA 8.0
Caffe:  whatever ver I downloaded from Berkley on 06/04/2017

I followed the installation instructions for installing Caffe in Ubuntu 16.04:  https://github.com/BVLC/caffe/wiki/Ubuntu-16.04-or-15.10-Installation-Guide

and all the make commands succeeded.

However when I try to use the libraries in a simple cpp program:

```<code>#include <memory>

#include <cstdlib>    // Provides NULL, rand, size_t;
#include <stdio.h>  // For printf
#include <cstring>  // For string
#include "/home/caffe-master/include/caffe/layers/memory_data_layer.hpp"
#include "/home/caffe-master-path>/include/caffe/caffe.hpp"

void blah( caffe::SolverParameter *sp);

int main()
{
... standard c++ code to generate random data deleted for brevity...
    caffe::SolverParameter solver_param;  // No errors given here for this declaration

    blah( solver_param);   // Simple function created to test error, same error appears here

    caffe::ReadSolverParamsFromTextFileOrDie( path, &solver_param);  // Actual function from XOR example, same error

    caffe::ReadSolverParamsFromTextFileOrDie("./solver.prototxt", &solver_param);  // This also gives same error

    boost::shared_ptr<caffe::Solver<float> > solver(caffe::SolverRegistry<float>::CreateSolver(solver_param)); // Same error here

... code that would of passed random data to caffe deleted ...
    return 0;
}

void blah( caffe::SolverParameter *sp)
{
    std::cout << "BLAH: " << sp->rms_decay_;
    return;
}
</code>```

In Eclipse Neon I get the following error for any line that includes the variable solver_param including the lines that where I created the simple function blah which takes one argument of type caffe::SolverParameter *

Invalid arguments 'Candidates are:
void ReadSolverParamsFromTextFileOrDie(const std::__cxx11::basic_string,std::allocator> &, ? *)'  caffe_hellow.cpp    /caffe  line 47 Semantic Error

I tried setting the full paths in the include path and that got rid of some errors, I added the libpath in eclipse to include caffe and boost and that got rid of more errors leaving only this one for now. I've been searching for a solution, looking at the .hpp caffe files to try to understand them and trying different settings in eclipse to get rid of this error but nothing works.  Casting did not work either.

For some reason it does not recognize any variable declared as type SolverParameter as a compatible argument to a function that requires it.  The error message gives "? *" as the argument type.  What does that mean?  Can you help?  Thank you.

答:
You need to include

```<code>#include "caffe/proto/caffe.pb.h"
</code>```

For all caffe.proto related declarations

Body:
I am attempting to compile the "Hello World XOR" C++ example given by:

https://medium.com/@shiyan/caffe-c-helloworld-example-with-memorydata-input-20c692a82a22

Hardware:
EX50-UD3R Motherboard
GT-640 NVidia cards (2 Cards)
Intel 980 (6 core)
16Gig (4x4) DDR3 RAM

Environment:
Ubuntu 16.04.2 LTS   Kernel: 4.4.0-78-generic
Eclipse Neon3 R4.6.3
CUDA 8.0
Caffe:  whatever ver I downloaded from Berkley on 06/04/2017

I followed the installation instructions for installing Caffe in Ubuntu 16.04:  https://github.com/BVLC/caffe/wiki/Ubuntu-16.04-or-15.10-Installation-Guide

and all the make commands succeeded.

However when I try to use the libraries in a simple cpp program:

#include <memory>

#include <cstdlib>    // Provides NULL, rand, size_t;
#include <stdio.h>  // For printf
#include <cstring>  // For string
#include "/home/caffe-master/include/caffe/layers/memory_data_layer.hpp"
#include "/home/caffe-master-path>/include/caffe/caffe.hpp"

void blah( caffe::SolverParameter *sp);

int main()
{
... standard c++ code to generate random data deleted for brevity...
    caffe::SolverParameter solver_param;  // No errors given here for this declaration

    blah( solver_param);   // Simple function created to test error, same error appears here

    caffe::ReadSolverParamsFromTextFileOrDie( path, &solver_param);  // Actual function from XOR example, same error

    caffe::ReadSolverParamsFromTextFileOrDie("./solver.prototxt", &solver_param);  // This also gives same error

    boost::shared_ptr<caffe::Solver<float> > solver(caffe::SolverRegistry<float>::CreateSolver(solver_param)); // Same error here

... code that would of passed random data to caffe deleted ...
    return 0;
}

void blah( caffe::SolverParameter *sp)
{
    std::cout << "BLAH: " << sp->rms_decay_;
    return;
}

In Eclipse Neon I get the following error for any line that includes the variable solver_param including the lines that where I created the simple function blah which takes one argument of type caffe::SolverParameter *

Invalid arguments 'Candidates are:
void ReadSolverParamsFromTextFileOrDie(const std::__cxx11::basic_string,std::allocator> &, ? *)'  caffe_hellow.cpp    /caffe  line 47 Semantic Error

I tried setting the full paths in the include path and that got rid of some errors, I added the libpath in eclipse to include caffe and boost and that got rid of more errors leaving only this one for now. I've been searching for a solution, looking at the .hpp caffe files to try to understand them and trying different settings in eclipse to get rid of this error but nothing works.  Casting did not work either.

For some reason it does not recognize any variable declared as type SolverParameter as a compatible argument to a function that requires it.  The error message gives "? *" as the argument type.  What does that mean?  Can you help?  Thank you.

Body:
You need to include

#include "caffe/proto/caffe.pb.h"

For all caffe.proto related declarations


问:
How can I get python to print out the current elapsed time while a function is running?
So I currently have python printing how long it took for a function to run after its done running with something like:

```<code>import time
t = time.time()
# do something in here
print "\n Time Taken: %.3f sec" % (time.time()-t)
</code>```

but I want to show the live time that has passed since the function has started, and I cant quite figure out a way to get that to happen.

for example in a terminal I want it to say something like:

```<code>Working on xFunction. Time Elapsed 72.485 sec... (live updated time)
xFunction Has finished.
Time Taken: 1152.546 sec
</code>```

Any help would be appreciated.

答:
Here's an example with a thread that will print how much time has elapsed since it started and can be stopped from the main loop.

```<code>import time
import threading

class ElapsedTimeThread(threading.Thread):
    """"Stoppable thread that prints the time elapsed"""
    def __init__(self):
        super(ElapsedTimeThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

    def run(self):
        thread_start = time.time()
        while not self.stopped():
            print("\rElapsed Time {:.3f} seconds".format(time.time()-thread_start), end="")
            #include a delay here so the thread doesn't uselessly thrash the CPU
            time.sleep(0.01)

if __name__ == "__main__":
    start = time.time()
    thread = ElapsedTimeThread()
    thread.start()
    # do something
    time.sleep(5)
    # something is finished so stop the thread
    thread.stop()
    thread.join()
    print() # empty print() to output a newline
    print("Finished in {:.3f} seconds".format(time.time()-start))
</code>```

This gives the following output, with the Elapsed Time counting up from zero and being overwritten:

```<code>J:\>python thr_time.py
Elapsed Time 5.000 seconds
Finished in 5.001 seconds
</code>```

Note that this code is in Python 3. More info on stopping threads here & here.

Let me know if you'd like clarification on any portions.

Body:
So I currently have python printing how long it took for a function to run after its done running with something like:

import time
t = time.time()
# do something in here
print "\n Time Taken: %.3f sec" % (time.time()-t)

but I want to show the live time that has passed since the function has started, and I cant quite figure out a way to get that to happen.

for example in a terminal I want it to say something like:

Working on xFunction. Time Elapsed 72.485 sec... (live updated time)
xFunction Has finished.
Time Taken: 1152.546 sec

Any help would be appreciated.

Body:
Here's an example with a thread that will print how much time has elapsed since it started and can be stopped from the main loop.

import time
import threading

class ElapsedTimeThread(threading.Thread):
    """"Stoppable thread that prints the time elapsed"""
    def __init__(self):
        super(ElapsedTimeThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

    def run(self):
        thread_start = time.time()
        while not self.stopped():
            print("\rElapsed Time {:.3f} seconds".format(time.time()-thread_start), end="")
            #include a delay here so the thread doesn't uselessly thrash the CPU
            time.sleep(0.01)

if __name__ == "__main__":
    start = time.time()
    thread = ElapsedTimeThread()
    thread.start()
    # do something
    time.sleep(5)
    # something is finished so stop the thread
    thread.stop()
    thread.join()
    print() # empty print() to output a newline
    print("Finished in {:.3f} seconds".format(time.time()-start))

This gives the following output, with the Elapsed Time counting up from zero and being overwritten:

J:\>python thr_time.py
Elapsed Time 5.000 seconds
Finished in 5.001 seconds

Note that this code is in Python 3. More info on stopping threads here & here.

Let me know if you'd like clarification on any portions.


问:
MySQL pivot row run in sql fiddle but not work in syntax model codeigniter
i use code to use MySQL pipot row at this link MySQL pivot row into dynamic number of columns
it's work on query editor and SQL fidle. but it's not work when i use query to model of codeIgniter

in Model PHP on Code Igniter i use code like this:

```<code>$query=$this->db->query("
   SET @sql = NULL;
   SELECT
   GROUP_CONCAT(DISTINCT
   CONCAT(
     'count(case when tahun = ''',
     tahun,
     ''' then 1 end) AS tahun_',
     replace(tahun, ' ', '')
   )
   ) INTO @sql
   from tb_tahun;

   SET @sql = CONCAT('SELECT pt.jenis_perjal, ', @sql, ' from tb_jenis_perjal pt
   left join tb_kebutuhan_perjal s
     on pt.id_jenis_perjal = s.id_jenis_perjal
   left join tb_tahun pd
     on s.id_tahun = pd.id_tahun
   group by pt.jenis_perjal');

   PREPARE stmt FROM @sql;
   EXECUTE stmt;
   DEALLOCATE PREPARE stmt;
");
</code>```

result of query :

```<code>Err Number : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT GROUP_CONCAT(DISTINCT CONCAT( 'count(case when' at line 2
</code>```

答:
Try saving the text in a variable and pass that variable as parameter to run method</p>

```<code>    $var = "SET @sql = NULL;
       SELECT
       GROUP_CONCAT(DISTINCT
       CONCAT(
         'count(case when tahun = ''',
         tahun,
         ''' then 1 end) AS tahun_',
         replace(tahun, ' ', '')
       )
       ) INTO @sql
       from tb_tahun;

       SET @sql = CONCAT('SELECT pt.jenis_perjal, ', @sql, ' from tb_jenis_perjal pt
       left join tb_kebutuhan_perjal s
         on pt.id_jenis_perjal = s.id_jenis_perjal
       left join tb_tahun pd
         on s.id_tahun = pd.id_tahun
       group by pt.jenis_perjal');

       PREPARE stmt FROM @sql;
       EXECUTE stmt;
       DEALLOCATE PREPARE stmt;";

     $query=$this->db->query($var);
</code>```

Body:
i use code to use MySQL pipot row at this link MySQL pivot row into dynamic number of columns
it's work on query editor and SQL fidle. but it's not work when i use query to model of codeIgniter

in Model PHP on Code Igniter i use code like this:

$query=$this->db->query("
   SET @sql = NULL;
   SELECT
   GROUP_CONCAT(DISTINCT
   CONCAT(
     'count(case when tahun = ''',
     tahun,
     ''' then 1 end) AS tahun_',
     replace(tahun, ' ', '')
   )
   ) INTO @sql
   from tb_tahun;

   SET @sql = CONCAT('SELECT pt.jenis_perjal, ', @sql, ' from tb_jenis_perjal pt
   left join tb_kebutuhan_perjal s
     on pt.id_jenis_perjal = s.id_jenis_perjal
   left join tb_tahun pd
     on s.id_tahun = pd.id_tahun
   group by pt.jenis_perjal');

   PREPARE stmt FROM @sql;
   EXECUTE stmt;
   DEALLOCATE PREPARE stmt;
");

result of query :

Err Number : 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT GROUP_CONCAT(DISTINCT CONCAT( 'count(case when' at line 2

Body:
Try saving the text in a variable and pass that variable as parameter to run method

    $var = "SET @sql = NULL;
       SELECT
       GROUP_CONCAT(DISTINCT
       CONCAT(
         'count(case when tahun = ''',
         tahun,
         ''' then 1 end) AS tahun_',
         replace(tahun, ' ', '')
       )
       ) INTO @sql
       from tb_tahun;

       SET @sql = CONCAT('SELECT pt.jenis_perjal, ', @sql, ' from tb_jenis_perjal pt
       left join tb_kebutuhan_perjal s
         on pt.id_jenis_perjal = s.id_jenis_perjal
       left join tb_tahun pd
         on s.id_tahun = pd.id_tahun
       group by pt.jenis_perjal');

       PREPARE stmt FROM @sql;
       EXECUTE stmt;
       DEALLOCATE PREPARE stmt;";

     $query=$this->db->query($var);


问:
Why using parallelStream access and modify Collection get different result?
I got confused about the following code

```<code>  public static void main(String[] args) throws InterruptedException
  {
    Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
    List<Integer> listOfIntegers =
            new ArrayList<>(Arrays.asList(intArray));
    List<Integer> parallelStorage = new ArrayList<>();//Collections.synchronizedList(new ArrayList<>());
    listOfIntegers
            .parallelStream()
            // Don't do this! It uses a stateful lambda expression.
            .map(e -> {
                parallelStorage.add(e);
                return e;
            })
            .forEachOrdered(e -> System.out.print(e + " "));
    System.out.println();
    parallelStorage
            .stream()
            .forEachOrdered(e -> System.out.print(e + " "));
    System.out.println();
    System.out.println("Sleep 5 sec");
    TimeUnit.SECONDS.sleep(5);
    parallelStorage
            .stream()
            .forEachOrdered(e -> System.out.print(e + " "));
}
</code>```

EveryTime execute it I got different result which really confused me a lot ,
here are some results :

```<code>Result 1:
1 2 3 4 5 6 7 8
null 3 8 7 1 4 5 6
Sleep 5 sec
null 3 8 7 1 4 5 6

Result 2：
1 2 3 4 5 6 7 8
6 2 4 1 5 7 8
Sleep 5 sec
6 2 4 1 5 7 8
</code>```

Here are two problems:

Q1: Why the size of parallelStorage is uncertain?

I understand parallelStream using fork/join framework, so I guess the problem is caused by some thread who doesn't finish their job, then I paused the main thread for 5 seconds, but seems no help, the size of parallelStorage still kept unchanged;

Q2: Why null elements exist in parallelStorage?

答:
ArrayList is not thread-safe.  That means that if you have two threads updating the list simultaneously, the two threads could interfere which each other in ways that could cause loss of data (or, for some data structures, could entirely corrupt the structure).

I don't know the exact sequence of steps that gets taken when you add to an ArrayList, but let's say it's something like this.  An ArrayList should contain a backing array, and an instance variable that indicates what the current size is

Read the array size into local variable N

Put the new element in arr[N]

Add 1 to N

Store N back in the array size

Now suppose you have two threads doing this.  Since there is no synchronization, the threads could take the steps in this order, if they both call add at the same time:

```<code>Read the array size into N
                                    Read the array size into N
Put the new element in arr[N]
                                    Put the new element in arr[N]
Add 1 to N
                                    Add 1 to N
Store N into the array size
                                    Store N into the array size
</code>```

If the array size is 3 before either thread calls add, note that both threads will read 3 into their own local variable N; then they'll both put the new element in the same place, and then will both store 4 into the array size.  So even though two elements were "added", the new array size will be 4 and not 5, and one of the new data elements will be lost.

That's why you need a synchronized list.

(The way the steps are done between the multiple threads is unpredictable.  So it's believable that in some cases, a different order of execution could lead to the size being incremented by both threads before an element is stored, causing an element in the array to remain unused and therefore be null.  Please don't take the sequence of steps I posted here as the actual steps taken by the Java runtime; it's just an example, and I didn't look at the ArrayList code.)

Body:
I got confused about the following code

  public static void main(String[] args) throws InterruptedException
  {
    Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
    List<Integer> listOfIntegers =
            new ArrayList<>(Arrays.asList(intArray));
    List<Integer> parallelStorage = new ArrayList<>();//Collections.synchronizedList(new ArrayList<>());
    listOfIntegers
            .parallelStream()
            // Don't do this! It uses a stateful lambda expression.
            .map(e -> {
                parallelStorage.add(e);
                return e;
            })
            .forEachOrdered(e -> System.out.print(e + " "));
    System.out.println();
    parallelStorage
            .stream()
            .forEachOrdered(e -> System.out.print(e + " "));
    System.out.println();
    System.out.println("Sleep 5 sec");
    TimeUnit.SECONDS.sleep(5);
    parallelStorage
            .stream()
            .forEachOrdered(e -> System.out.print(e + " "));
}

EveryTime execute it I got different result which really confused me a lot ,
here are some results :

Result 1:
1 2 3 4 5 6 7 8
null 3 8 7 1 4 5 6
Sleep 5 sec
null 3 8 7 1 4 5 6

Result 2：
1 2 3 4 5 6 7 8
6 2 4 1 5 7 8
Sleep 5 sec
6 2 4 1 5 7 8

Here are two problems:

Q1: Why the size of parallelStorage is uncertain?

I understand parallelStream using fork/join framework, so I guess the problem is caused by some thread who doesn't finish their job, then I paused the main thread for 5 seconds, but seems no help, the size of parallelStorage still kept unchanged;

Q2: Why null elements exist in parallelStorage?

Body:
ArrayList is not thread-safe.  That means that if you have two threads updating the list simultaneously, the two threads could interfere which each other in ways that could cause loss of data (or, for some data structures, could entirely corrupt the structure).

I don't know the exact sequence of steps that gets taken when you add to an ArrayList, but let's say it's something like this.  An ArrayList should contain a backing array, and an instance variable that indicates what the current size is

Read the array size into local variable N

Put the new element in arr[N]

Add 1 to N

Store N back in the array size

Now suppose you have two threads doing this.  Since there is no synchronization, the threads could take the steps in this order, if they both call add at the same time:

Read the array size into N
                                    Read the array size into N
Put the new element in arr[N]
                                    Put the new element in arr[N]
Add 1 to N
                                    Add 1 to N
Store N into the array size
                                    Store N into the array size

If the array size is 3 before either thread calls add, note that both threads will read 3 into their own local variable N; then they'll both put the new element in the same place, and then will both store 4 into the array size.  So even though two elements were "added", the new array size will be 4 and not 5, and one of the new data elements will be lost.

That's why you need a synchronized list.

(The way the steps are done between the multiple threads is unpredictable.  So it's believable that in some cases, a different order of execution could lead to the size being incremented by both threads before an element is stored, causing an element in the array to remain unused and therefore be null.  Please don't take the sequence of steps I posted here as the actual steps taken by the Java runtime; it's just an example, and I didn't look at the ArrayList code.)


答:
You can use the semi_join function from dplyr:

```<code>library(dplyr)

semi_join(df1, df2, by = c("Year", "Month", "Day", "Hour"))
</code>```

This will return only the rows in df1 that are matched in df2 by the Year, Month, Day and Hour columns. Unlike some of the other joins, it is not mutating, meaning it won't add the columns of df2 to the result.

Title: How to subset a dataframe from another dataframe with different length ?

Body:
How to subset a dataframe from another dataframe of different length ?
eg: I have two dataframes, df1 and df2, how do I subset df1 using df2's Year, Month, Day, Hour so it will become something like the Expected Outcome?

Where Year, Month, Day, Hour from row 4, 6, 7 in df1 matches df2's row 1, 2, 3 so only row 4, 6, 7 in df1 is in the expected outcome.

df1

    V1  Year Month Day Hour Min Sec   Weight
1  1640 1999    02  05   04  00  00 1.936074
2  1519 1999    02  10   12  00  00 1.944277
3  1219 1999    02  25   16  00  00 1.947789
4  1720 1999    03  11   16  00  00 1.946841
5  1782 1999    03  18   08  00  00 1.956711
6  1523 1999    03  24   12  00  00 1.965768
7  1153 1999    04  01   16  00  00 1.981121
8  1262 1999    04  08   16  00  00 1.987066
9  1860 1999    04  15   00  00  00 1.982274
10 1624 1999    04  28   08  00  00 1.999045

df2

    V1  Year Month Day Hour Min Sec   Weight
1  3587 1999    03  11   16  00  00 2.836074
2  4675 1999    03  24   12  00  00 2.854277
3  3592 1999    04  01   16  00  00 2.917789
4  2980 1999    04  12   16  00  00 2.926841
5  2857 1999    04  18   16  00  00 2.986711

Expected Outcome

    V1  Year Month Day Hour Min Sec   Weight
4  1720 1999    03  11   16  00  00 1.946841
6  1523 1999    03  24   12  00  00 1.965768
7  1153 1999    04  01   16  00  00 1.981121

Body:
You can use the semi_join function from dplyr:

library(dplyr)

semi_join(df1, df2, by = c("Year", "Month", "Day", "Hour"))

This will return only the rows in df1 that are matched in df2 by the Year, Month, Day and Hour columns. Unlike some of the other joins, it is not mutating, meaning it won't add the columns of df2 to the result.


问:
Building Libraries on Windows
Hobbyist and newbie, so no laughing ;)

I have been developing some toy programs on my Mac for a long time and everything is nice and straightforward.

I was trying to port one of my existing projects to Windows (as a way to get started in developing for Windows) but am stuck trying to build the libraries I have come to love in a Unix environment under Windows (and MinGW).

At the risk of revealing my naïvety, could someone just run through how to build and install a library on Windows (including any special software required)?

For example, an install readme might look like this:

```<code>Do this to install:
./configure
make
make install
</code>```

Obviously on Windows that pukes...so what are the analogous steps on Windows?

答:
You have a couple of options wrt building unix style libraries on windows:

Google for a pre-built binary distribution made for windows of the library in question.

If the libraries authors have bothered to support it, you can try installing Cygwin to get a posix like build environment on windows

Some libraries - like OpenSSL - have a set of build instructions for windows that include installing ActiveState Perl, and then running the appropriate configure script manually.

Where the authors of the library have made no special effort, you are pretty stuck: Create a static library project in the dev environment, add the libraries files to it, create (or move) the headers that the ./configure step usually creates or moves and build it yourself.

It is a tragic state of affairs that doing this "simple" task is so hard. Developers seem to take one of two lessons away from this:

Microsoft is the devil. Microsoft hates developers. Hates open source software. And is #@#$. Compiling libraries and software from source via a standardized ./configure & make install process is the one true way.

Microsoft is the one true way. The microsoft eco system of pre-built .lib files and headers is perfection and people who build everything from source using arcane perl scripts and install into a standardized filesystem are mentally defective.

Your pick :P

Title: Building Libraries on Windows

Body:
Hobbyist and newbie, so no laughing ;)

I have been developing some toy programs on my Mac for a long time and everything is nice and straightforward.

I was trying to port one of my existing projects to Windows (as a way to get started in developing for Windows) but am stuck trying to build the libraries I have come to love in a Unix environment under Windows (and MinGW).

At the risk of revealing my naïvety, could someone just run through how to build and install a library on Windows (including any special software required)?

For example, an install readme might look like this:

Do this to install:
./configure
make
make install

Obviously on Windows that pukes...so what are the analogous steps on Windows?


问:
After adding aasm gem, application gives me error: wrong number of arguments (given 1, expected 0)
My model:

```<code>class Lead < ApplicationRecord

  include AASM

  aasm column: 'status' do
     state :new, initial: true
     state :valid

     event :submit do
       transitions from: :new, to: :valid
     end
     ...
  end
  ...

end
</code>```

And the Controller:

```<code>class LeadsController < ApplicationController
  ...

  def create
  @lead = @leads.new lead_params
  if @lead.save
    flash[:success] = "Lead saved successfully"
    render 'show'
  end

  ...
end
</code>```

When trying to create a new lead, it gives me error wrong number of arguments (given 1, expected 0). All this happened after I added aasm gem. What could be the reason?

答: Well found the reason after some hard work. Problem is with how AASM gem is built. Here I have used valid as a state. That's the problem. Seems like it's a reserved keywork in the gem. Renaming it to another state name solved the problem.

Body:
My model:

class Lead < ApplicationRecord

  include AASM

  aasm column: 'status' do
     state :new, initial: true
     state :valid

     event :submit do
       transitions from: :new, to: :valid
     end
     ...
  end
  ...

end

And the Controller:

class LeadsController < ApplicationController
  ...

  def create
  @lead = @leads.new lead_params
  if @lead.save
    flash[:success] = "Lead saved successfully"
    render 'show'
  end

  ...
end

When trying to create a new lead, it gives me error wrong number of arguments (given 1, expected 0). All this happened after I added aasm gem. What could be the reason?


问:
mysql BLOB manipulate in php
In mysql, I have a db column with BLOB data type.

The blob data looks something like this:

```<code>{\"Name\":\"Mike Smith\",\"Number\":\"1\"}
</code>```

or

```<code>[{\"Name\":\"Mike Smith\"},{\"Name\":\"Jon Doe\",\"Spaces\":\"1\"},{\"Name\":\"My Space(s)\"},{\"Name\":\"Rear\"}]
</code>```

I am trying to detect the content in php and saving the string as a variable as such:

```<code>{\"Name\":\"Mike Smith\",\"Number\":\"1\"}
BECOMES -> Mike Smith(1)
</code>```

And...

```<code>[{\"Name\":\"Mike Smith\"},{\"Name\":\"Jon Doe\",\"Number\":\"1\"},{\"Name\":\"My Space(s)\"},{\"Name\":\"Rear\"}]
BECOMES --> Mike Smith, Jon Doe(1), My Space(s), Rear
</code>```

I am not familiar with BLOB data type and wanted to get some help from the community. How would I manipulate the BLOB data to above?

Any suggestions will be much appreciated.

答:
```<code><?php

$data = '[{\"Name\":\"Mike Smith\"},{\"Name\":\"Jon Doe\",\"Number\":\"1\"},
{\"Name\":\"My Space(s)\"},{\"Name\":\"Rear\"}]';

$data =  json_decode(stripslashes($data))  ;

 $string = '';
 for ($i=0; $i <sizeof($data) ; $i++) {

 $d = $data[$i];

 if(isset($d->Number)){
    $number = '('.$d->Number.')';
 }
 else{
    $number = '';
 }

 $string .= ($d->Name).$number.',  ';

}

echo $string;
</code>```

Title: mysql BLOB manipulate in php

Body:
In mysql, I have a db column with BLOB data type.

The blob data looks something like this:

{\"Name\":\"Mike Smith\",\"Number\":\"1\"}

or

[{\"Name\":\"Mike Smith\"},{\"Name\":\"Jon Doe\",\"Spaces\":\"1\"},{\"Name\":\"My Space(s)\"},{\"Name\":\"Rear\"}]

I am trying to detect the content in php and saving the string as a variable as such:

{\"Name\":\"Mike Smith\",\"Number\":\"1\"}
BECOMES -> Mike Smith(1)

And...

[{\"Name\":\"Mike Smith\"},{\"Name\":\"Jon Doe\",\"Number\":\"1\"},{\"Name\":\"My Space(s)\"},{\"Name\":\"Rear\"}]
BECOMES --> Mike Smith, Jon Doe(1), My Space(s), Rear

I am not familiar with BLOB data type and wanted to get some help from the community. How would I manipulate the BLOB data to above?

Any suggestions will be much appreciated.


问:
Rails 5 ActiveRecord, how to include fields from associated tables?
With Rails 5, Given the models:

```<code>chef_positions
* id
* name

skills
* id
* name

chef_position_skills
* id
* chef_position_id
* skill_id
</code>```

I have a controller method to return the chef_position_skills by chef_position_id:

```<code>  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end
</code>```

This returns:

```<code> [{"id":1,"chef_position_id":2,"skill_id":1,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"},{"id":2,"chef_position_id":2,"skill_id":2,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"}]
</code>```

How can I get the controller to do the following:

include skill.name for each record

Do not include the timestamps

答:
you need to associate the two first if you haven't already, in your model,  chef_positions.rb

```<code>has_many :skills, through: :chef_position_skills
</code>```

Then in your controller,

```<code>ChefPosition.where(id: params[:chef_position_id]).joins(:skills).select('chef_positions.id, skills.name')
</code>```

Body:
With Rails 5, Given the models:

chef_positions
* id
* name

skills
* id
* name

chef_position_skills
* id
* chef_position_id
* skill_id

I have a controller method to return the chef_position_skills by chef_position_id:

  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end

This returns:

 [{"id":1,"chef_position_id":2,"skill_id":1,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"},{"id":2,"chef_position_id":2,"skill_id":2,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"}]

How can I get the controller to do the following:

include skill.name for each record

Do not include the timestamps

Body:
you need to associate the two first if you haven't already, in your model,  chef_positions.rb

has_many :skills, through: :chef_position_skills

Then in your controller,

ChefPosition.where(id: params[:chef_position_id]).joins(:skills).select('chef_positions.id, skills.name')


问:
using index match with sum if
I need to link up a sumif() with an index match (i'm guessing here) but don't really know where to start.

Basically i a table with different classes of pets, their species and quantity. there are 3 stores. I need an output where i can get the quantity of each species from each store dynamically.

data table:

```<code>"A1"                Pet Stores
Species  Class      a   b   c
cat      Fluffy1    1   0   0
cat      Fluffy2    3   0   0
cat      Fluffy3    5   7   1
cat      Fluffy4    6   0   7
dog      Barky1     7   6   9
dog      Barky2     1   3   9
dog      Barky3     0   2   8
dog      Barky4     0   2   3
fish     Swimmy1    0   0   0
fish     Swimmy2    1   3   0
fish     Swimmy3    0   2   3
fish     Swimmy4    0   0   0
</code>```

Output:

```<code>Pet Store   a   <--change this
cat         15  <--output
dog         8   <--output
fish        1   <--output
</code>```

right now my formula for "cat" is =SUMIF($A$3:$A$14,A17,$C$3:$C$14). however, it only looks down the 1 column that i've set. how do i change it such that it searches for the "Pet Store" and returns sum of the respective column?

答:
Slightly shorter that @teylyn's version:

```<code>=SUMIF(A$2:A$13,A16,OFFSET(C$2:C$13,,CODE(B$15)-97))
</code>```

but less versatile as it relies on the shop names being coded (which however is as in the example and makes sense for column label purposes):

However my preference would be for a PivotTable:

Title: using index match with sum if

Body:
I need to link up a sumif() with an index match (i'm guessing here) but don't really know where to start.

Basically i a table with different classes of pets, their species and quantity. there are 3 stores. I need an output where i can get the quantity of each species from each store dynamically.

data table:

"A1"                Pet Stores
Species  Class      a   b   c
cat      Fluffy1    1   0   0
cat      Fluffy2    3   0   0
cat      Fluffy3    5   7   1
cat      Fluffy4    6   0   7
dog      Barky1     7   6   9
dog      Barky2     1   3   9
dog      Barky3     0   2   8
dog      Barky4     0   2   3
fish     Swimmy1    0   0   0
fish     Swimmy2    1   3   0
fish     Swimmy3    0   2   3
fish     Swimmy4    0   0   0

Output:

Pet Store   a   <--change this
cat         15  <--output
dog         8   <--output
fish        1   <--output

right now my formula for "cat" is =SUMIF($A$3:$A$14,A17,$C$3:$C$14). however, it only looks down the 1 column that i've set. how do i change it such that it searches for the "Pet Store" and returns sum of the respective column?

Body:
Slightly shorter that @teylyn's version:

=SUMIF(A$2:A$13,A16,OFFSET(C$2:C$13,,CODE(B$15)-97))

but less versatile as it relies on the shop names being coded (which however is as in the example and makes sense for column label purposes):

However my preference would be for a PivotTable:


问:
MySQL query to get desired output
What I'm getting with my current query:

```<code>+---------------+--------------------+-------+--------+--------+
|    Name       |       email        | Apple | Orange | Banana |
+---------------+--------------------+-------+--------+--------+
| NULL          | NULL               | YES   | YES    | YES    |
| Molly Weasley | mweasley@gmail.com | YES   | YES    | YES    |
| Viktor Krum   | vkrum@gmail.com    | YES   | YES    | NULL   |
+---------------+--------------------+-------+--------+--------+
</code>```

What I want:

```<code>+---------------+--------------------+-------+--------+--------+--------------+
|    Name       |       email        | Apple | Orange | Banana | Info Entered |
+---------------+--------------------+-------+--------+--------+--------------+
| Severus Snape | ssnape@gmail.com   |       |        |        | No           |
| Molly Weasley | mweasley@gmail.com | YES   | YES    | YES    | Yes          |
| Viktor Krum   | vkrum@gmail.com    | YES   | YES    |        | Yes          |
+---------------+--------------------+-------+--------+--------+--------------+
</code>```

Basically, Severus Snape has not answered the questionnaire yet (he has no records in the answers table) but I'd still like tho show him (because he received the questionnaire as indicated in the questions table). Apple, orange, and banana would be blank for him (it's showing YES all the way across for some reason).

The query I'm using:

```<code>SELECT CONCAT(people.firstName, ' ', people.lastName) AS Name,
people.email,
MAX(CASE WHEN questions.fruit = 'apple' THEN 'YES' END) AS Apple,
MAX(CASE WHEN questions.fruit = 'orange' THEN 'YES' END) AS Orange,
MAX(CASE WHEN questions.fruit = 'banana' THEN 'YES' END) AS Banana
FROM answers
LEFT JOIN questions ON answers.questionID = questions.questionID
LEFT JOIN people ON questions.person = people.person AND questions.questionnaire = '24'
GROUP BY CONCAT(people.firstName, ' ', people.lastName), people.email
ORDER BY Name
</code>```

Sample data:

people table:

```<code>+-----------+----------+--------------------+--------+
| firstName | lastName |       email        | person |
+-----------+----------+--------------------+--------+
| Harry     | Potter   | hpotter@gmail.com  |      1 |
| Ron       | Weasley  | rweasley@gmail.com |      2 |
| Hermione  | Granger  | hgranger@gmail.com |      3 |
| Severus   | Snape    | ssnape@gmail.com   |      4 |
| Viktor    | Krum     | vkrum@gmail.com    |      5 |
| Molly     | Weasley  | mweasley@gmail.com |      6 |
| Oliver    | Wood     | owood@gmail.com    |      7 |
| Remus     | Loopin   | rlupin@gmail.com   |      8 |
+-----------+----------+--------------------+--------+
</code>```

questions table:

```<code>+---------------+--------+------------+--------+
| questionnaire | person | questionID | fruit  |
+---------------+--------+------------+--------+
|            23 |      1 |         55 | apple  |
|            23 |      1 |         56 | orange |
|            23 |      1 |         57 | banana |
|            23 |      2 |         58 | apple  |
|            23 |      2 |         59 | orange |
|            23 |      2 |         60 | banana |
|            23 |      3 |         61 | apple  |
|            23 |      3 |         62 | orange |
|            23 |      3 |         63 | banana |
|            24 |      4 |         64 | apple  |
|            24 |      4 |         65 | orange |
|            24 |      4 |         66 | banana |
|            24 |      5 |         67 | apple  |
|            24 |      5 |         68 | orange |
|            24 |      5 |         69 | banana |
|            24 |      6 |         70 | apple  |
|            24 |      6 |         71 | orange |
|            24 |      6 |         72 | banana |
+---------------+--------+------------+--------+
</code>```

answers table:

```<code>+----------+------------+---------------------+-----------------+
| answerID | questionID |        info         |  dateAnswered   |
+----------+------------+---------------------+-----------------+
|       40 |         59 | some info here      | 5/26/2017 19:23 |
|       41 |         59 |                     | 5/26/2017 18:30 |
|       42 |         59 |                     | 5/26/2017 18:29 |
|       43 |         66 |                     | 5/26/2017 18:36 |
|       44 |         66 |                     | 5/26/2017 20:28 |
|       45 |         70 |                     | 5/26/2017 20:28 |
|       46 |         55 | more info here      | 5/26/2017 20:29 |
|       47 |         71 |                     | 5/26/2017 20:29 |
|       48 |         67 |                     | 5/26/2017 20:31 |
|       49 |         64 |                     | 5/26/2017 18:37 |
|       50 |         55 |                     | 5/26/2017 18:46 |
|       51 |         72 |                     | 5/26/2017 18:46 |
|       52 |         72 | another bit of info | 5/26/2017 18:46 |
|       53 |         72 | and more info       | 5/26/2017 18:46 |
|       54 |         61 |                     | 5/26/2017 18:29 |
|       55 |         61 |                     | 5/26/2017 18:30 |
|       56 |         68 | the info            | 5/26/2017 18:36 |
|       57 |         59 |                     | 5/26/2017 19:22 |
|       58 |         66 |                     | 5/26/2017 19:37 |
|       59 |         61 |                     | 5/26/2017 19:37 |
|       60 |         61 |                     | 5/26/2017 18:33 |
|       61 |         68 | this info           | 5/26/2017 18:38 |
|       62 |         68 |                     | 5/26/2017 19:33 |
|       63 |         68 | some more  info     | 5/26/2017 19:42 |
|       64 |         68 |                     | 5/26/2017 19:56 |
|       65 |         60 |                     | 5/26/2017 20:03 |
+----------+------------+---------------------+-----------------+
</code>```

答:
Try to change the order:</p>

```<code>SELECT
    CONCAT(people.firstName, ' ', people.lastName) AS Name,
    people.email,
    MAX(CASE WHEN questions.fruit = 'apple' AND answers.questionID IS NOT NULL THEN 'YES' END) AS Apple,
    MAX(CASE WHEN questions.fruit = 'orange' AND answers.questionID IS NOT NULL  THEN 'YES' END) AS Orange,
    MAX(CASE WHEN questions.fruit = 'banana' AND answers.questionID IS NOT NULL  THEN 'YES' END) AS Banana
FROM people
JOIN questions ON questions.person = people.person AND questions.questionnaire = '24'
LEFT JOIN answers ON answers.questionID = questions.questionID
GROUP BY CONCAT(people.firstName, ' ', people.lastName), people.email
ORDER BY Name
</code>```

Title: MySQL query to get desired output

Body:
What I'm getting with my current query:

+---------------+--------------------+-------+--------+--------+
|    Name       |       email        | Apple | Orange | Banana |
+---------------+--------------------+-------+--------+--------+
| NULL          | NULL               | YES   | YES    | YES    |
| Molly Weasley | mweasley@gmail.com | YES   | YES    | YES    |
| Viktor Krum   | vkrum@gmail.com    | YES   | YES    | NULL   |
+---------------+--------------------+-------+--------+--------+

What I want:

+---------------+--------------------+-------+--------+--------+--------------+
|    Name       |       email        | Apple | Orange | Banana | Info Entered |
+---------------+--------------------+-------+--------+--------+--------------+
| Severus Snape | ssnape@gmail.com   |       |        |        | No           |
| Molly Weasley | mweasley@gmail.com | YES   | YES    | YES    | Yes          |
| Viktor Krum   | vkrum@gmail.com    | YES   | YES    |        | Yes          |
+---------------+--------------------+-------+--------+--------+--------------+

Basically, Severus Snape has not answered the questionnaire yet (he has no records in the answers table) but I'd still like tho show him (because he received the questionnaire as indicated in the questions table). Apple, orange, and banana would be blank for him (it's showing YES all the way across for some reason).

The query I'm using:

SELECT CONCAT(people.firstName, ' ', people.lastName) AS Name,
people.email,
MAX(CASE WHEN questions.fruit = 'apple' THEN 'YES' END) AS Apple,
MAX(CASE WHEN questions.fruit = 'orange' THEN 'YES' END) AS Orange,
MAX(CASE WHEN questions.fruit = 'banana' THEN 'YES' END) AS Banana
FROM answers
LEFT JOIN questions ON answers.questionID = questions.questionID
LEFT JOIN people ON questions.person = people.person AND questions.questionnaire = '24'
GROUP BY CONCAT(people.firstName, ' ', people.lastName), people.email
ORDER BY Name

Sample data:

people table:

+-----------+----------+--------------------+--------+
| firstName | lastName |       email        | person |
+-----------+----------+--------------------+--------+
| Harry     | Potter   | hpotter@gmail.com  |      1 |
| Ron       | Weasley  | rweasley@gmail.com |      2 |
| Hermione  | Granger  | hgranger@gmail.com |      3 |
| Severus   | Snape    | ssnape@gmail.com   |      4 |
| Viktor    | Krum     | vkrum@gmail.com    |      5 |
| Molly     | Weasley  | mweasley@gmail.com |      6 |
| Oliver    | Wood     | owood@gmail.com    |      7 |
| Remus     | Loopin   | rlupin@gmail.com   |      8 |
+-----------+----------+--------------------+--------+

questions table:

+---------------+--------+------------+--------+
| questionnaire | person | questionID | fruit  |
+---------------+--------+------------+--------+
|            23 |      1 |         55 | apple  |
|            23 |      1 |         56 | orange |
|            23 |      1 |         57 | banana |
|            23 |      2 |         58 | apple  |
|            23 |      2 |         59 | orange |
|            23 |      2 |         60 | banana |
|            23 |      3 |         61 | apple  |
|            23 |      3 |         62 | orange |
|            23 |      3 |         63 | banana |
|            24 |      4 |         64 | apple  |
|            24 |      4 |         65 | orange |
|            24 |      4 |         66 | banana |
|            24 |      5 |         67 | apple  |
|            24 |      5 |         68 | orange |
|            24 |      5 |         69 | banana |
|            24 |      6 |         70 | apple  |
|            24 |      6 |         71 | orange |
|            24 |      6 |         72 | banana |
+---------------+--------+------------+--------+

answers table:

+----------+------------+---------------------+-----------------+
| answerID | questionID |        info         |  dateAnswered   |
+----------+------------+---------------------+-----------------+
|       40 |         59 | some info here      | 5/26/2017 19:23 |
|       41 |         59 |                     | 5/26/2017 18:30 |
|       42 |         59 |                     | 5/26/2017 18:29 |
|       43 |         66 |                     | 5/26/2017 18:36 |
|       44 |         66 |                     | 5/26/2017 20:28 |
|       45 |         70 |                     | 5/26/2017 20:28 |
|       46 |         55 | more info here      | 5/26/2017 20:29 |
|       47 |         71 |                     | 5/26/2017 20:29 |
|       48 |         67 |                     | 5/26/2017 20:31 |
|       49 |         64 |                     | 5/26/2017 18:37 |
|       50 |         55 |                     | 5/26/2017 18:46 |
|       51 |         72 |                     | 5/26/2017 18:46 |
|       52 |         72 | another bit of info | 5/26/2017 18:46 |
|       53 |         72 | and more info       | 5/26/2017 18:46 |
|       54 |         61 |                     | 5/26/2017 18:29 |
|       55 |         61 |                     | 5/26/2017 18:30 |
|       56 |         68 | the info            | 5/26/2017 18:36 |
|       57 |         59 |                     | 5/26/2017 19:22 |
|       58 |         66 |                     | 5/26/2017 19:37 |
|       59 |         61 |                     | 5/26/2017 19:37 |
|       60 |         61 |                     | 5/26/2017 18:33 |
|       61 |         68 | this info           | 5/26/2017 18:38 |
|       62 |         68 |                     | 5/26/2017 19:33 |
|       63 |         68 | some more  info     | 5/26/2017 19:42 |
|       64 |         68 |                     | 5/26/2017 19:56 |
|       65 |         60 |                     | 5/26/2017 20:03 |
+----------+------------+---------------------+-----------------+

Body:
Try to change the order:

SELECT
    CONCAT(people.firstName, ' ', people.lastName) AS Name,
    people.email,
    MAX(CASE WHEN questions.fruit = 'apple' AND answers.questionID IS NOT NULL THEN 'YES' END) AS Apple,
    MAX(CASE WHEN questions.fruit = 'orange' AND answers.questionID IS NOT NULL  THEN 'YES' END) AS Orange,
    MAX(CASE WHEN questions.fruit = 'banana' AND answers.questionID IS NOT NULL  THEN 'YES' END) AS Banana
FROM people
JOIN questions ON questions.person = people.person AND questions.questionnaire = '24'
LEFT JOIN answers ON answers.questionID = questions.questionID
GROUP BY CONCAT(people.firstName, ' ', people.lastName), people.email
ORDER BY Name