问:
How to train a sense2vec model
The documentation of sense2vec mentions 3 primary files -  the first of them being merge_text.py. I have tried several types of inputs- txt,csv,bzipped file since merge_text.py tries to open files compressed by bzip2.

The file can be found at:
https://github.com/spacy-io/sense2vec/blob/master/bin/merge_text.py

What type of input format does this script require?
Further, if anyone could please suggest how to train the model.

答:
I extended and adjusted the code samples from sense2vec.

You go from this input text:

"As far as Saudi Arabia and its motives, that is very simple also. The Saudis are
good at money and arithmetic. Faced with the painful choice of losing money
maintaining current production at US$60 per barrel or taking two million barrels
per day off the market and losing much more money - it's an easy choice: take
the path that is less painful. If there are secondary reasons like hurting US
tight oil producers or hurting Iran and Russia, that's great, but it's really
just about the money."

To this:

as|ADV far|ADV as|ADP saudi_arabia|ENT and|CCONJ its|ADJ motif|NOUN that|ADJ is|VERB very|ADV simple|ADJ also|ADV saudis|ENT are|VERB good|ADJ at|ADP money|NOUN and|CCONJ arithmetic|NOUN faced|VERB with|ADP painful_choice|NOUN of|ADP losing|VERB money|NOUN maintaining|VERB current_production|NOUN at|ADP us$|SYM 60|MONEY per|ADP barrel|NOUN or|CCONJ taking|VERB two_million|CARDINAL barrel|NOUN per|ADP day|NOUN off|ADP market|NOUN and|CCONJ losing|VERB  much_more_money|NOUN it|PRON 's|VERB easy_choice|NOUN take|VERB path|NOUN that|ADJ is|VERB less|ADV painful|ADJ if|ADP there|ADV are|VERB secondary_reason|NOUN like|ADP hurting|VERB us|ENT tight_oil_producer|NOUN or|CCONJ hurting|VERB iran|ENT and|CCONJ russia|ENT 's|VERB great|ADJ but|CCONJ it|PRON 's|VERB really|ADV just|ADV about|ADP money|NOUN

Double line breaks are interpreted as separate documents.

Urls are recognized as such, stripped down to domain.tld and marked as |URL

Nouns (also noun being part of noun phrases) are lemmatized (as motives become motifs)

Words with POS-tags like DET (determinate article) and PUNCT (for punctuation) are dropped

Here's the code. Let me know if you have questions.

I'll probably publish it on github.com/woltob soon.

```<code>import spacy
import re

nlp = spacy.load('en')
nlp.matcher = None

LABELS = {
    'ENT': 'ENT',
    'PERSON': 'PERSON',
    'NORP': 'ENT',
    'FAC': 'ENT',
    'ORG': 'ENT',
    'GPE': 'ENT',
    'LOC': 'ENT',
    'LAW': 'ENT',
    'PRODUCT': 'ENT',
    'EVENT': 'ENT',
    'WORK_OF_ART': 'ENT',
    'LANGUAGE': 'ENT',
    'DATE': 'DATE',
    'TIME': 'TIME',
    'PERCENT': 'PERCENT',
    'MONEY': 'MONEY',
    'QUANTITY': 'QUANTITY',
    'ORDINAL': 'ORDINAL',
    'CARDINAL': 'CARDINAL'
}

pre_format_re = re.compile(r'^[\`\*\~]')
post_format_re = re.compile(r'[\`\*\~]$')
url_re = re.compile(r'(https?:\/\/)?([a-z0-9-]+\.)?([\d\w]+?\.[^\/]{2,63})')
single_linebreak_re = re.compile('\n')
double_linebreak_re = re.compile('\n{2,}')
whitespace_re = re.compile(r'[ \t]+')
quote_re = re.compile(r'"|`|´')

def strip_meta(text):
    text = text.replace('per cent', 'percent')
    text = text.replace('>', '>').replace('<', '<')
    text = pre_format_re.sub('', text)
    text = post_format_re.sub('', text)
    text = double_linebreak_re.sub('{2break}', text)
    text = single_linebreak_re.sub(' ', text)
    text = text.replace('{2break}', '\n')
    text = whitespace_re.sub(' ', text)
    text = quote_re.sub('', text)
    return text

def transform_doc(doc):
    for ent in doc.ents:
        ent.merge(ent.root.tag_, ent.text, LABELS[ent.label_])
    for np in doc.noun_chunks:
        while len(np) > 1 and np[0].dep_ not in ('advmod', 'amod', 'compound'):
            np = np[1:]
        np.merge(np.root.tag_, np.text, np.root.ent_type_)
    strings = []
    for sent in doc.sents:
        sentence = []
        if sent.text.strip():
            for w in sent:
                if w.is_space:
                    continue
                w_ = represent_word(w)
                if w_:
                    sentence.append(w_)
            strings.append(' '.join(sentence))
    if strings:
        return '\n'.join(strings) + '\n'
    else:
        return ''

def represent_word(word):
    if word.like_url:
        x = url_re.search(word.text.strip().lower())
        if x:
            return x.group(3)+'|URL'
        else:
            return word.text.lower().strip()+'|URL?'
    text = re.sub(r'\s', '_', word.text.strip().lower())
    tag = LABELS.get(word.ent_type_)
    # Dropping PUNCTUATION such as commas and DET like the
    if tag is None and word.pos_ not in ['PUNCT', 'DET']:
        tag = word.pos_
    elif tag is None:
        return None
    # if not word.pos_:
    #    tag = '?'
    return text + '|' + tag

corpus = '''
As far as Saudi Arabia and its motives, that is very simple also. The Saudis are
good at money and arithmetic. Faced with the painful choice of losing money
maintaining current production at US$60 per barrel or taking two million barrels
per day off the market and losing much more money - it's an easy choice: take
the path that is less painful. If there are secondary reasons like hurting US
tight oil producers or hurting Iran and Russia, that's great, but it's really
just about the money.
'''

corpus_stripped = strip_meta(corpus)

doc = nlp(corpus_stripped)
corpus_ = []
for word in doc:
    # only lemmatize NOUN and PROPN
    if word.pos_ in ['NOUN', 'PROPN'] and len(word.text) > 3 and len(word.text) != len(word.lemma_):
        # Keep the original word with the length of the lemma, then add the white space, if it was there.:
        lemma_ = str(word.text[:1]+word.lemma_[1:]+word.text_with_ws[len(word.text):])
            # print(word.text, lemma_)
        corpus_.append(lemma_)
    # print(word.text, word.text[:len(word.lemma_)]+word.text_with_ws[len(word.text):])
    # All other words are added normally.
    else:
        corpus_.append(word.text_with_ws)

result = transform_doc(nlp(''.join(corpus_)))

sense2vec_filename = 'text.txt'
file = open(sense2vec_filename,'w')
file.write(result)
file.close()
print(result)
</code>```

You could visualise your model using Gensim in Tensorboard using this approach:
https://github.com/ArdalanM/gensim2tensorboard

I'll also adjust this code to work with the sense2vec approach (e.g. the words become lowercase in the preprocessing step, just comment it out in the code).

Happy coding,
woltob

Title: How to train a sense2vec model

Body:
I extended and adjusted the code samples from sense2vec.

You go from this input text:

"As far as Saudi Arabia and its motives, that is very simple also. The Saudis are
good at money and arithmetic. Faced with the painful choice of losing money
maintaining current production at US$60 per barrel or taking two million barrels
per day off the market and losing much more money - it's an easy choice: take
the path that is less painful. If there are secondary reasons like hurting US
tight oil producers or hurting Iran and Russia, that's great, but it's really
just about the money."

To this:

as|ADV far|ADV as|ADP saudi_arabia|ENT and|CCONJ its|ADJ motif|NOUN that|ADJ is|VERB very|ADV simple|ADJ also|ADV saudis|ENT are|VERB good|ADJ at|ADP money|NOUN and|CCONJ arithmetic|NOUN faced|VERB with|ADP painful_choice|NOUN of|ADP losing|VERB money|NOUN maintaining|VERB current_production|NOUN at|ADP us$|SYM 60|MONEY per|ADP barrel|NOUN or|CCONJ taking|VERB two_million|CARDINAL barrel|NOUN per|ADP day|NOUN off|ADP market|NOUN and|CCONJ losing|VERB  much_more_money|NOUN it|PRON 's|VERB easy_choice|NOUN take|VERB path|NOUN that|ADJ is|VERB less|ADV painful|ADJ if|ADP there|ADV are|VERB secondary_reason|NOUN like|ADP hurting|VERB us|ENT tight_oil_producer|NOUN or|CCONJ hurting|VERB iran|ENT and|CCONJ russia|ENT 's|VERB great|ADJ but|CCONJ it|PRON 's|VERB really|ADV just|ADV about|ADP money|NOUN

Double line breaks are interpreted as separate documents.

Urls are recognized as such, stripped down to domain.tld and marked as |URL

Nouns (also noun being part of noun phrases) are lemmatized (as motives become motifs)

Words with POS-tags like DET (determinate article) and PUNCT (for punctuation) are dropped

Here's the code. Let me know if you have questions.

I'll probably publish it on github.com/woltob soon.

import spacy
import re

nlp = spacy.load('en')
nlp.matcher = None

LABELS = {
    'ENT': 'ENT',
    'PERSON': 'PERSON',
    'NORP': 'ENT',
    'FAC': 'ENT',
    'ORG': 'ENT',
    'GPE': 'ENT',
    'LOC': 'ENT',
    'LAW': 'ENT',
    'PRODUCT': 'ENT',
    'EVENT': 'ENT',
    'WORK_OF_ART': 'ENT',
    'LANGUAGE': 'ENT',
    'DATE': 'DATE',
    'TIME': 'TIME',
    'PERCENT': 'PERCENT',
    'MONEY': 'MONEY',
    'QUANTITY': 'QUANTITY',
    'ORDINAL': 'ORDINAL',
    'CARDINAL': 'CARDINAL'
}

pre_format_re = re.compile(r'^[\`\*\~]')
post_format_re = re.compile(r'[\`\*\~]$')
url_re = re.compile(r'(https?:\/\/)?([a-z0-9-]+\.)?([\d\w]+?\.[^\/]{2,63})')
single_linebreak_re = re.compile('\n')
double_linebreak_re = re.compile('\n{2,}')
whitespace_re = re.compile(r'[ \t]+')
quote_re = re.compile(r'"|`|´')

def strip_meta(text):
    text = text.replace('per cent', 'percent')
    text = text.replace('&gt;', '>').replace('&lt;', '<')
    text = pre_format_re.sub('', text)
    text = post_format_re.sub('', text)
    text = double_linebreak_re.sub('{2break}', text)
    text = single_linebreak_re.sub(' ', text)
    text = text.replace('{2break}', '\n')
    text = whitespace_re.sub(' ', text)
    text = quote_re.sub('', text)
    return text

def transform_doc(doc):
    for ent in doc.ents:
        ent.merge(ent.root.tag_, ent.text, LABELS[ent.label_])
    for np in doc.noun_chunks:
        while len(np) > 1 and np[0].dep_ not in ('advmod', 'amod', 'compound'):
            np = np[1:]
        np.merge(np.root.tag_, np.text, np.root.ent_type_)
    strings = []
    for sent in doc.sents:
        sentence = []
        if sent.text.strip():
            for w in sent:
                if w.is_space:
                    continue
                w_ = represent_word(w)
                if w_:
                    sentence.append(w_)
            strings.append(' '.join(sentence))
    if strings:
        return '\n'.join(strings) + '\n'
    else:
        return ''

def represent_word(word):
    if word.like_url:
        x = url_re.search(word.text.strip().lower())
        if x:
            return x.group(3)+'|URL'
        else:
            return word.text.lower().strip()+'|URL?'
    text = re.sub(r'\s', '_', word.text.strip().lower())
    tag = LABELS.get(word.ent_type_)
    # Dropping PUNCTUATION such as commas and DET like the
    if tag is None and word.pos_ not in ['PUNCT', 'DET']:
        tag = word.pos_
    elif tag is None:
        return None
    # if not word.pos_:
    #    tag = '?'
    return text + '|' + tag

corpus = '''
As far as Saudi Arabia and its motives, that is very simple also. The Saudis are
good at money and arithmetic. Faced with the painful choice of losing money
maintaining current production at US$60 per barrel or taking two million barrels
per day off the market and losing much more money - it's an easy choice: take
the path that is less painful. If there are secondary reasons like hurting US
tight oil producers or hurting Iran and Russia, that's great, but it's really
just about the money.
'''

corpus_stripped = strip_meta(corpus)

doc = nlp(corpus_stripped)
corpus_ = []
for word in doc:
    # only lemmatize NOUN and PROPN
    if word.pos_ in ['NOUN', 'PROPN'] and len(word.text) > 3 and len(word.text) != len(word.lemma_):
        # Keep the original word with the length of the lemma, then add the white space, if it was there.:
        lemma_ = str(word.text[:1]+word.lemma_[1:]+word.text_with_ws[len(word.text):])
            # print(word.text, lemma_)
        corpus_.append(lemma_)
    # print(word.text, word.text[:len(word.lemma_)]+word.text_with_ws[len(word.text):])
    # All other words are added normally.
    else:
        corpus_.append(word.text_with_ws)

result = transform_doc(nlp(''.join(corpus_)))

sense2vec_filename = 'text.txt'
file = open(sense2vec_filename,'w')
file.write(result)
file.close()
print(result)

You could visualise your model using Gensim in Tensorboard using this approach:
https://github.com/ArdalanM/gensim2tensorboard

I'll also adjust this code to work with the sense2vec approach (e.g. the words become lowercase in the preprocessing step, just comment it out in the code).

Happy coding,
woltob


来源: stackexchange

问:
Saving an Image of Chart With a SaveFileDialog
On button click, my program captures a screenshot of a chart, titled chartMain. Code below:

```<code>private void buttonScreenshot_Click(object sender, EventArgs e)
{
    this.chartMain.SaveImage("C:/capture.png", ChartImageFormat.Png);
}
</code>```

However, this doesn't allow the user to specify the save location so I was wondering how I would implement SaveFileDialog to allow the user to choose where to save it.

Could someone please point me in the right direction as I am currently stuck.

Thank you in advance.

答:
A simple example, modify to your needs (I would check out this page though):</p>

```<code>var save = new SaveFileDialog();
save.Filter = "PNG files (*.png)|*.txt|All files (*.*)|*.*";
if(save.ShowDialog() == DialogResult.OK)
{
    this.chartMain.SaveImage(save.FileName, ChartImageFormat.Png);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
On button click, my program captures a screenshot of a chart, titled chartMain. Code below:

private void buttonScreenshot_Click(object sender, EventArgs e)
{
    this.chartMain.SaveImage("C:/capture.png", ChartImageFormat.Png);
}

However, this doesn't allow the user to specify the save location so I was wondering how I would implement SaveFileDialog to allow the user to choose where to save it.

Could someone please point me in the right direction as I am currently stuck.

Thank you in advance.

Body:
A simple example, modify to your needs (I would check out this page though):

var save = new SaveFileDialog();
save.Filter = "PNG files (*.png)|*.txt|All files (*.*)|*.*";
if(save.ShowDialog() == DialogResult.OK)
{
    this.chartMain.SaveImage(save.FileName, ChartImageFormat.Png);
}


问:
Sencha Touch: List ItemTap Event Firing
I am following along very closely with the code within the GeoCongress.us App, as this is my first Sencha Touch app and the premise behind that app's layout functionality is similar to what I hope to achieve.

I am having an issue getting a List object to respond to the itemtap event though. My intent is to capture the itemtap event at the SetsScreen level, fire my own custom event which my App object would listen for, and App could then handle the process of displaying a new card (based on the item tapped).

First, the SetsScreen object (relevant portions of it at least):

```<code>DataSets.views.SetsScreen = Ext.extend(Ext.Panel, {
    cls: 'sets-screen',
    layout: 'card',

    initComponent: function() {
        // Build the main content list and add it to the main scren
        this.setsList = new DataSets.views.SetsList({
            scroll: false
        });
        this.setsList.on('itemtap', this.onListItemTap, this);

        this.main = new Ext.Container({
            scroll: true,
            items: [this.setsList]
        });

        this.items = [this.main];
        DataSets.views.SetsScreen.superclass.initComponent.call(this);
    },

    onListItemTap: function(dv, index, item, e) {
        alert('Test');
    }
});
</code>```

Here is my SetsList object (nothing really amazing here):

```<code>DataSets.views.SetsList = Ext.extend(Ext.List, {
    itemSelector: '.sets-list-item',
    singleSelect: true,

    initComponent: function() {
        this.store = DataSets.stores.Sets;
        this.itemTpl = Ext.XTemplate.from('sets-list');

        DataSets.views.SetsList.superclass.initComponent.call(this);
    }
});
</code>```

And the Sets object is nothing more than a quick data model and Ext.data.Store:

```<code>Ext.regModel('Sets', {
    idProperty: 'id',
    fields: [
        'title',
        'last_updated',
        'current_value'
    ]
});

DataSets.stores.Sets = new Ext.data.Store({
    model: 'Sets',
    data: [
        {id: 0, title: 'Weight', last_updated: new Date('11/28/2010 00:00:00 AM GMT-0600'), current_value: 145},
        {id: 1, title: 'Cups of Coffee', last_updated: new Date('11/28/2010 07:00:00 AM GMT-0600'), current_value: 1}
    ]
});
</code>```

答: You might need to look at the updated screencast - since some of the API's changed in the 1.0 release and the older screencast is now out of synch.</p>

ContentLicense: CC BY-SA 2.5

Title: Sencha Touch: List ItemTap Event Firing

Body:
I am following along very closely with the code within the GeoCongress.us App, as this is my first Sencha Touch app and the premise behind that app's layout functionality is similar to what I hope to achieve.

I am having an issue getting a List object to respond to the itemtap event though. My intent is to capture the itemtap event at the SetsScreen level, fire my own custom event which my App object would listen for, and App could then handle the process of displaying a new card (based on the item tapped).

First, the SetsScreen object (relevant portions of it at least):

DataSets.views.SetsScreen = Ext.extend(Ext.Panel, {
    cls: 'sets-screen',
    layout: 'card',

    initComponent: function() {
        // Build the main content list and add it to the main scren
        this.setsList = new DataSets.views.SetsList({
            scroll: false
        });
        this.setsList.on('itemtap', this.onListItemTap, this);

        this.main = new Ext.Container({
            scroll: true,
            items: [this.setsList]
        });

        this.items = [this.main];
        DataSets.views.SetsScreen.superclass.initComponent.call(this);
    },

    onListItemTap: function(dv, index, item, e) {
        alert('Test');
    }
});

Here is my SetsList object (nothing really amazing here):

DataSets.views.SetsList = Ext.extend(Ext.List, {
    itemSelector: '.sets-list-item',
    singleSelect: true,

    initComponent: function() {
        this.store = DataSets.stores.Sets;
        this.itemTpl = Ext.XTemplate.from('sets-list');

        DataSets.views.SetsList.superclass.initComponent.call(this);
    }
});

And the Sets object is nothing more than a quick data model and Ext.data.Store:

Ext.regModel('Sets', {
    idProperty: 'id',
    fields: [
        'title',
        'last_updated',
        'current_value'
    ]
});

DataSets.stores.Sets = new Ext.data.Store({
    model: 'Sets',
    data: [
        {id: 0, title: 'Weight', last_updated: new Date('11/28/2010 00:00:00 AM GMT-0600'), current_value: 145},
        {id: 1, title: 'Cups of Coffee', last_updated: new Date('11/28/2010 07:00:00 AM GMT-0600'), current_value: 1}
    ]
});


问:
uncaught TypeError: Cannot read property 'style' of null at frame
Im making a loading bar.

And now i got an error when i click on download

Uncaught TypeError: Cannot read property 'style' of null

I dont know what i am dong wrong please can someone help me here is my code

```<code><a class="tooltip-test" id="header"><div class="progress" id="headerTop" style="cursor:default">
                <div id="myElement" class="progress-bar bg-info progress-bar-striped progress-bar-animated myBar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
                    <p class="text-center">0%</p>
                </div>
            </div></a>
            <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button>
        </div>
        <script type="text/javascript">
            function move() {
                document.getElementById("headerTop").style.cursor = "wait";
                var elem = document.getElementById("myBar");
                var width = 0;
                var id = setInterval(frame, 1000);
                function frame() {
                    if (width >= 99) {
                        var number = random(99, 100)
                        if(number = 99) {
                            clearInterval(id);
                            document.getElementById("MyElement").className =
                            document.getElementById("MyElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' )
                            document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over";
                        }else if (number = 100) {
                            clearInterval(id);
                            document.getElementById("MyElement").className =
                            document.getElementById("MyElement").className.replace
                            ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' )
                            document.getElementById("header").title = "download is ready";
                        }
                    } else {
                        width++;
                        elem.style.width = width + '%';
                        elem.innerHTML = width * 1 + '%';
                    }
                }
            }
    </script>
</code>```

F.Y.I i am using bootstrap for the styling

答:
I think the problem is with this line:

```<code>var elem = document.getElementById("myBar");
</code>```

You're selecting by Id but myBar is a class

So you should select by classname

You could also just select by id as you do below:

```<code>var elem document.getElementById("MyElement");
</code>```

That's probably the easiest thing to do.

Body:
Im making a loading bar.

And now i got an error when i click on download

Uncaught TypeError: Cannot read property 'style' of null

I dont know what i am dong wrong please can someone help me here is my code

0%

            <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button>

F.Y.I i am using bootstrap for the styling

Body:
I think the problem is with this line:

var elem = document.getElementById("myBar");

You're selecting by Id but myBar is a class

So you should select by classname

You could also just select by id as you do below:

var elem document.getElementById("MyElement");

That's probably the easiest thing to do.


问:
codeigniter not loading application/core files
Got a problem with codeigniter with exteding the core. I build a website local and it workst perfect. Even when checking out on new machine or diferent php version ( tested on 5.3 and 5.2 ) it works normal. But when i upload it to my server it doesnt load the files in application/core. I get the error message:

```<code>Fatal error: Class 'LEAN_Controller' not found in /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/controllers/wachtlijsten/overzicht.php on line 3
</code>```

When i ouput the loaded files like so:

```<code>print_r(get_included_files());
</code>```

i get these results:
localhost:

```<code>Array ( [0] => C:\wamp\www\website\index.php [1] =>
C:\wamp\www\website\system\core\CodeIgniter.php [2] =>
C:\wamp\www\website\system\core\Common.php [3] =>
C:\wamp\www\website\application\config\constants.php [4] =>
C:\wamp\www\website\system\core\Benchmark.php [5] =>
C:\wamp\www\website\application\config\config.php [6] =>
C:\wamp\www\website\system\core\Hooks.php [7] =>
C:\wamp\www\website\system\core\Config.php [8] =>
C:\wamp\www\website\system\libraries\Log.php [9] =>
C:\wamp\www\website\system\core\Utf8.php [10] =>
C:\wamp\www\website\system\core\URI.php [11] =>
C:\wamp\www\website\system\core\Router.php [12] =>
C:\wamp\www\website\application\config\routes.php [13] =>
C:\wamp\www\website\system\core\Output.php [14] =>
C:\wamp\www\website\application\config\mimes.php [15] =>
C:\wamp\www\website\system\core\Security.php [16] =>
C:\wamp\www\website\system\core\Input.php [17] =>
C:\wamp\www\website\system\core\Lang.php [18] =>
C:\wamp\www\website\system\core\Controller.php [19] =>
C:\wamp\www\website\application\core\lean_controller.php [20] =>
C:\wamp\www\website\application\controllers\wachtlijsten\overzicht.php )
</code>```

server:

```<code>Array ( [0] => /var/www/vhosts/website/subdomains/w8systeem/httpdocs/index.php [1] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/CodeIgniter.php [2] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Common.php [3] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/config/constants.php [4] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Benchmark.php [5] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/config/config.php [6] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Hooks.php [7] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Config.php [8] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/libraries/Log.php [9] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Utf8.php [10] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/URI.php [11] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Router.php [12] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/config/routes.php [13] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Output.php [14] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/config/mimes.php [15] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Security.php [16] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Input.php [17] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Lang.php [18] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Controller.php [19] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/controllers/wachtlijsten/overzicht.php )
</code>```

I'm out of ideas. Dont know where to search further..

答:
C:\wamp\www\website\application\core\lean_controller.php

should be

C:\wamp\www\website\application\core\LEAN_Controller.php

Linux is case sensitive, windows is not

Body:
Got a problem with codeigniter with exteding the core. I build a website local and it workst perfect. Even when checking out on new machine or diferent php version ( tested on 5.3 and 5.2 ) it works normal. But when i upload it to my server it doesnt load the files in application/core. I get the error message:

Fatal error: Class 'LEAN_Controller' not found in /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/controllers/wachtlijsten/overzicht.php on line 3

When i ouput the loaded files like so:

print_r(get_included_files());

i get these results:
localhost:

Array ( [0] => C:\wamp\www\website\index.php [1] =>
C:\wamp\www\website\system\core\CodeIgniter.php [2] =>
C:\wamp\www\website\system\core\Common.php [3] =>
C:\wamp\www\website\application\config\constants.php [4] =>
C:\wamp\www\website\system\core\Benchmark.php [5] =>
C:\wamp\www\website\application\config\config.php [6] =>
C:\wamp\www\website\system\core\Hooks.php [7] =>
C:\wamp\www\website\system\core\Config.php [8] =>
C:\wamp\www\website\system\libraries\Log.php [9] =>
C:\wamp\www\website\system\core\Utf8.php [10] =>
C:\wamp\www\website\system\core\URI.php [11] =>
C:\wamp\www\website\system\core\Router.php [12] =>
C:\wamp\www\website\application\config\routes.php [13] =>
C:\wamp\www\website\system\core\Output.php [14] =>
C:\wamp\www\website\application\config\mimes.php [15] =>
C:\wamp\www\website\system\core\Security.php [16] =>
C:\wamp\www\website\system\core\Input.php [17] =>
C:\wamp\www\website\system\core\Lang.php [18] =>
C:\wamp\www\website\system\core\Controller.php [19] =>
C:\wamp\www\website\application\core\lean_controller.php [20] =>
C:\wamp\www\website\application\controllers\wachtlijsten\overzicht.php )

server:

Array ( [0] => /var/www/vhosts/website/subdomains/w8systeem/httpdocs/index.php [1] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/CodeIgniter.php [2] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Common.php [3] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/config/constants.php [4] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Benchmark.php [5] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/config/config.php [6] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Hooks.php [7] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Config.php [8] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/libraries/Log.php [9] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Utf8.php [10] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/URI.php [11] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Router.php [12] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/config/routes.php [13] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Output.php [14] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/config/mimes.php [15] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Security.php [16] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Input.php [17] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Lang.php [18] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/system/core/Controller.php [19] =>
 /var/www/vhosts/website/subdomains/w8systeem/httpdocs/application/controllers/wachtlijsten/overzicht.php )

I'm out of ideas. Dont know where to search further..


问:
Magento - Collection Filter by Array Keep Order
Is it possible to filter a Magento collection using an array of id's BUT have the collection results ordered by the order of the id's passed to the filter.

For example:

```<code>$collection = Mage::getModel('catalog/product')
                  ->getCollection()
                  ->addAttributeToFilter('entity_id', array(
                       'in' => array(1, 3, 2),
                   ));
</code>```

I would like the collection to have products in order, 1,3,2 so as when looping through the collection they come out in that specific order?

The only alternative i currently have is to manually create an array of products:

```<code>$productIds = array(1,3,2);
$collection = array();

foreach($productIds as $productId) {
    $collection[] = Mage::getModel('catalog/product')->load($productId);
}
</code>```

This obviously works but seems like an ugly way to do this.

is there a way to do this purely via magento collections?

答:
Pretty old but a simple solution I found on stackoverflow is

```<code>$productIds = array(1,3,2);
$products = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToFilter('entity_id', array('in' => $productIds));
$products->getSelect()->order("find_in_set(entity_id,'".implode(',',$productIds)."')");
</code>```

from here on stackoverflow

Body:
Is it possible to filter a Magento collection using an array of id's BUT have the collection results ordered by the order of the id's passed to the filter.

For example:

$collection = Mage::getModel('catalog/product')
                  ->getCollection()
                  ->addAttributeToFilter('entity_id', array(
                       'in' => array(1, 3, 2),
                   ));

I would like the collection to have products in order, 1,3,2 so as when looping through the collection they come out in that specific order?

The only alternative i currently have is to manually create an array of products:

$productIds = array(1,3,2);
$collection = array();

foreach($productIds as $productId) {
    $collection[] = Mage::getModel('catalog/product')->load($productId);
}

This obviously works but seems like an ugly way to do this.

is there a way to do this purely via magento collections?

Body:
Pretty old but a simple solution I found on stackoverflow is

$productIds = array(1,3,2);
$products = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToFilter('entity_id', array('in' => $productIds));
$products->getSelect()->order("find_in_set(entity_id,'".implode(',',$productIds)."')");

from here on stackoverflow


问:
Regex for links in html text
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?

Adam

UPDATE:
I am actually looking for two different answers:

What's the library solution for parsing HTML links. Beautiful Soup seems to be a good solution (thanks, Igal Serban and cletus!)

Can a link be defined using a regex?

答:
No there isn't.

You can consider using Beautiful Soup. You can call it the standard for parsing html files.

OwnerDisplayName: Udi Pasmon

Title: Regex for links in html text

LastEditorDisplayName: Udi Pasmon

OwnerDisplayName: Igal Serban


问:
Can I store an object constructor into an array or hashtable?
Let's say I have a class Foo and another class Bar that both extends from a superclass Foobar, each one with it's own  constructor.

So, I want to make an application in Java 8 that let's a user choose from a list of objects to implement, and add them to a list —I was thinking of using an array or hashtable—, in this case I want to show a message like:

```<code>Choose an object of the following list:
 [1] Foo
 [2] Bar
</code>```

The idea is to let the user create multiple instances of such classes and add them to an array. For example, if the user chooses 1, I want to assign a variable with a[0] = new Foo(), and then if he chooses 2, a[1] = new Bar(), but then, if the user chooses 1 again, then a[2] should be a new instance of Foo. My first idea was to initialize an array with the constructors like:

```<code>anArray[1] = new Foo();
anArray[2] = new Bar();
</code>```

The problem with that implementation is that if I call a[0] = anArray[1] and then a[1] = anArray[1], then a[0]and a[1] would be the same object.

What I am looking for is if there is a way of creating an undefined number of instances of each object without having to implement it as a chain of if else (because in reality I have more than 2 type of objects). I was thinking of using an array or a hashtable, but I don't know if there is actually a way of doing it.

答:
Can I store an object constructor into an array or hashtable?

If you are in Java-8+ land then you certainly can.  I'll assume you mean HashMap not a HashTable.  I would instead create an array of Factory objects.  Create a FooFactory and a BarFactory each which support  create method that returns an object.

```<code> public interface MyFactory<T> {
      public T create();
 }

 public class FooFactory implements MyFactory<Foo> {
      public Foo create() {
          return new Foo();
      }
 }

 public class BarFactory implements MyFactory<Bar> {
      public Bar create() {
          return new Bar();
      }
 }
</code>```

Then you can do:

```<code>MyFactory[] factories = new MyFactory[10];
factories[0] = new FooFactory();
factories[1] = new BarFactory();
...
</code>```

And then you can use the array:

```<code>Object obj = factories[0].create();
</code>```

Body:
Let's say I have a class Foo and another class Bar that both extends from a superclass Foobar, each one with it's own  constructor.

So, I want to make an application in Java 8 that let's a user choose from a list of objects to implement, and add them to a list —I was thinking of using an array or hashtable—, in this case I want to show a message like:

Choose an object of the following list:
 [1] Foo
 [2] Bar

The idea is to let the user create multiple instances of such classes and add them to an array. For example, if the user chooses 1, I want to assign a variable with a[0] = new Foo(), and then if he chooses 2, a[1] = new Bar(), but then, if the user chooses 1 again, then a[2] should be a new instance of Foo. My first idea was to initialize an array with the constructors like:

anArray[1] = new Foo();
anArray[2] = new Bar();

The problem with that implementation is that if I call a[0] = anArray[1] and then a[1] = anArray[1], then a[0]and a[1] would be the same object.

What I am looking for is if there is a way of creating an undefined number of instances of each object without having to implement it as a chain of if else (because in reality I have more than 2 type of objects). I was thinking of using an array or a hashtable, but I don't know if there is actually a way of doing it.

Body:
Can I store an object constructor into an array or hashtable?

If you are in Java-8+ land then you certainly can.  I'll assume you mean HashMap not a HashTable.  I would instead create an array of Factory objects.  Create a FooFactory and a BarFactory each which support  create method that returns an object.

 public interface MyFactory<T> {
      public T create();
 }

 public class FooFactory implements MyFactory<Foo> {
      public Foo create() {
          return new Foo();
      }
 }

 public class BarFactory implements MyFactory<Bar> {
      public Bar create() {
          return new Bar();
      }
 }

Then you can do:

MyFactory[] factories = new MyFactory[10];
factories[0] = new FooFactory();
factories[1] = new BarFactory();
...

And then you can use the array:

Object obj = factories[0].create();


问:
How to make my scanner ignore lines ending in <dir> using java?
I have a scanner which is reading in a file, but I do not know how to make the scanner ignore lines ending in < dir > </p>

答:
Use Scanner#next method. It will block until user inputs a non-empty string.

Update after the question was rephrased:

Try the following way:

```<code>    Scanner scanner = new Scanner(System.in);
    scanner.useDelimiter("\r\n"); //For Windows, new line.
    String s = "";
    do {
        s = scanner.next();
    }
    while(s.endsWith("< dir >"));
</code>```

Body:
Use Scanner#next method. It will block until user inputs a non-empty string.

Update after the question was rephrased:

Try the following way:

    Scanner scanner = new Scanner(System.in);
    scanner.useDelimiter("\r\n"); //For Windows, new line.
    String s = "";
    do {
        s = scanner.next();
    }
    while(s.endsWith("< dir >"));


问:
Add scroll on my JList
My ScrollPane won't show to my JList. I tried using this, this, and many other ways to add a scroll on my jlist but it wont just show. Here is the sample of my code.

```<code>        JScrollPane scrollPane = new JScrollPane(list_1);
    list_1 = new JList();
    scrollPane.setViewportView(list_1);
    list_1.setBounds(16, 94, 579, 248);
    contentPane.add(list_1);
    contentPane.add(scrollPane);
</code>```

My JList consists of array of files (paths) that came from my database.

答:
The list needs to be created before being added to the scrollpane. The code should be:

```<code>list_1 = new JList();
JScrollPane scrollPane = new JScrollPane(list_1);
//list_1 = new JList();
</code>```

A component can only have a single parent. The code should be:

```<code>//contentPane.add(list_1); // this will remove the list from the scrollpane
contentPane.add(scrollPane);
</code>```

Don't use setBounds():

```<code>list_1.setBounds(16, 94, 579, 248);
</code>```

The scrollpane uses its own layout manager so the above code does nothing. Swing was designed to be used with layout managers.

3 problems with 6 lines of code. I suggest you start by reading the section from the Swing tutorial on How to Use Lists for more information and working examples.

The tutorial is full of basic Swing information and will help you get started with simple examples containing better structured code.

Title: Add scroll on my JList

Body:
My ScrollPane won't show to my JList. I tried using this, this, and many other ways to add a scroll on my jlist but it wont just show. Here is the sample of my code.

        JScrollPane scrollPane = new JScrollPane(list_1);
    list_1 = new JList();
    scrollPane.setViewportView(list_1);
    list_1.setBounds(16, 94, 579, 248);
    contentPane.add(list_1);
    contentPane.add(scrollPane);

My JList consists of array of files (paths) that came from my database.

Body:
The list needs to be created before being added to the scrollpane. The code should be:

list_1 = new JList();
JScrollPane scrollPane = new JScrollPane(list_1);
//list_1 = new JList();

A component can only have a single parent. The code should be:

//contentPane.add(list_1); // this will remove the list from the scrollpane
contentPane.add(scrollPane);

Don't use setBounds():

list_1.setBounds(16, 94, 579, 248);

The scrollpane uses its own layout manager so the above code does nothing. Swing was designed to be used with layout managers.

3 problems with 6 lines of code. I suggest you start by reading the section from the Swing tutorial on How to Use Lists for more information and working examples.

The tutorial is full of basic Swing information and will help you get started with simple examples containing better structured code.


问:
Reasons not to use use a wildcard pull?
Are there any reasons not to use a wildcard pull?

```<code>(defn pull-wild
  "Pulls all attributes of a single entity."
  [db ent-id]
  (d/pull db '[*] ent-id))
</code>```

It's much more convenient than explicitly stating the attributes.

答:
It depends on which attributes you need to have in your application and if it's data intensive or whether you want to pull lots of entities.

In case you use the client-library, you might want to minimize the data that needs to be send over the wire.

I guess there are lots of other thoughts about that.

But as long as it's fast enough I would pull the wildcard.

fricke

Title: Reasons not to use use a wildcard pull?

Body:
Are there any reasons not to use a wildcard pull?

(defn pull-wild
  "Pulls all attributes of a single entity."
  [db ent-id]
  (d/pull db '[*] ent-id))

It's much more convenient than explicitly stating the attributes.


问:
How to understand array sorting in Swift
Can someone please visualize the process of sorting?

```<code>let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }
</code>```

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

答:
The sorted function takes a closure which defines the ordering of any two elements. The sorting algorithm does a series of comparisons between items, and uses the closure to determine the ordering amongst them.

Here's an example which prints out all the comparisons done in the sorting of an example array of numbers:

```<code>let numbers = [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
let sorted = numbers.sorted { (a: Int, b: Int) -> Bool in
    let result = a < b
    print("\(a) is \(result ? "" : "not") before \(b)")
    return result
}

print(sorted)
</code>```

$0 and $1 are implicit closure parameters. They're names implicitly given to the parameters of a closure. They're often used in cases where the names given to parameters of a closure are rather arbitrary, such as in this case.

In your example, the closure behaves as if it was like so:

```<code>let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { leftElement, rightElement in
    return leftElement > rightElement
}
</code>```

As you can see leftElement and rightElement don't add much information to the code, which is why it's preferred to use implicit closure parameters in a case like this.

Body:
Can someone please visualize the process of sorting?

let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { $0 > $1 }

If I were to sort these 3 numbers in descending order in real life, it would result in this: scrSh1, but Swift makes it complicated: scrSh2.

How can there be 4 returns and why is the last one 'false'?
How are the arguments $0 and $1 changing their positions?

Body:
The sorted function takes a closure which defines the ordering of any two elements. The sorting algorithm does a series of comparisons between items, and uses the closure to determine the ordering amongst them.

Here's an example which prints out all the comparisons done in the sorting of an example array of numbers:

let numbers = [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
let sorted = numbers.sorted { (a: Int, b: Int) -> Bool in
    let result = a < b
    print("\(a) is \(result ? "" : "not") before \(b)")
    return result
}

print(sorted)

$0 and $1 are implicit closure parameters. They're names implicitly given to the parameters of a closure. They're often used in cases where the names given to parameters of a closure are rather arbitrary, such as in this case.

In your example, the closure behaves as if it was like so:

let numbers = [0,2,1]
let sortedNumbers = numbers.sorted { leftElement, rightElement in
    return leftElement > rightElement
}

As you can see leftElement and rightElement don't add much information to the code, which is why it's preferred to use implicit closure parameters in a case like this.


问:
PHP map array data to HTML table while skipping some html table columns
Alo,

I have this array in php:

```<code>$data=array(1,2,3,4,5,6,7,8);
</code>```

I want to put it in html table that has the following structure (image)

The colored columns are to be skipped entirely. I have failed to do so but here is my attempt anyway:

```<code>$totalColumnsPerRow=8;
$skippableColumns=array(3,6,7,8);
$counter=1;
//loop the array now
$row="<tr>";
foreach($data as $val){
//do we need to start a new row or not?
 if ($counter==$totalColumnsPerRow){
 //close open row and create a new one.
 $counter=1;
 $row.="</tr><tr>":
  }

 //show I skip the current column or not?
 if(in_array($counter,$skippableColumns)){
 //skip column then add current value
 $row.="<td></td>";
 $row.="<td>$val</td>";
 }
 else{
 $row.="<td>$val</td>";
  }
 $counter++;
}
</code>```

That gives me the following table structure. If it had successfully skipped the rows, a new row would have started with value 5.

Here is a PHP fiddle

Any idea on how to like pause the loop and use it in usable column? Is my approach practical?

答:
I modified your code. Please try the following. Added comments for better understanding.

```<code><table border="1" width="600px">
<tr>
<td>A</td><td>B</td><td>ABT</td><td>C</td><td>D</td><td>CDT</td><td>ACT</td><td>TTT</td>
</tr>

<?php

$data = array(1,2,3,4,5,6,7,8);
$totalColumnsPerRow = 8;
$skippableColumns = array(3,6,7,8);

$table = '<tr>';
$lastIndex = 0;

for($i = 1; $i <= $totalColumnsPerRow; $i++) { // Per column

    if(in_array($i, $skippableColumns)) { // Skipping coulmn value
        $table .= '<td></td>';
    } else { // Adding coulmn value
        $table .= '<td>'.$data[$lastIndex].'</td>';
        $lastIndex++; // Incrementing data index
    }

    if($i == $totalColumnsPerRow) { // Last column
        $table .= '</tr>'; // Ending row

        if($lastIndex <= count($data) -1) { // Data left
            $table .= '<tr>'; // Starting new row

            $i = 0; // Resetting so in the next increment it will become 1
        }
    }
}

echo $table;
?>
</code>```

Output is

Body:
Alo,

I have this array in php:

$data=array(1,2,3,4,5,6,7,8);

I want to put it in html table that has the following structure (image)

The colored columns are to be skipped entirely. I have failed to do so but here is my attempt anyway:

$totalColumnsPerRow=8;
$skippableColumns=array(3,6,7,8);
$counter=1;
//loop the array now
$row="
";
foreach($data as $val){
//do we need to start a new row or not?
 if ($counter==$totalColumnsPerRow){
 //close open row and create a new one.
 $counter=1;
 $row.="

":
  }

 //show I skip the current column or not?
 if(in_array($counter,$skippableColumns)){
 //skip column then add current value
 $row.="	";
 $row.="$val	";
 }
 else{
 $row.="$val	";
  }
 $counter++;
}

That gives me the following table structure. If it had successfully skipped the rows, a new row would have started with value 5.

Here is a PHP fiddle

Any idea on how to like pause the loop and use it in usable column? Is my approach practical?

Body:
I modified your code. Please try the following. Added comments for better understanding.

<table border="1" width="600px">
<tr>
<td>A</td><td>B</td><td>ABT</td><td>C</td><td>D</td><td>CDT</td><td>ACT</td><td>TTT</td>
</tr>

<?php

$data = array(1,2,3,4,5,6,7,8);
$totalColumnsPerRow = 8;
$skippableColumns = array(3,6,7,8);

$table = '<tr>';
$lastIndex = 0;

for($i = 1; $i <= $totalColumnsPerRow; $i++) { // Per column

    if(in_array($i, $skippableColumns)) { // Skipping coulmn value
        $table .= '<td></td>';
    } else { // Adding coulmn value
        $table .= '<td>'.$data[$lastIndex].'</td>';
        $lastIndex++; // Incrementing data index
    }

    if($i == $totalColumnsPerRow) { // Last column
        $table .= '</tr>'; // Ending row

        if($lastIndex <= count($data) -1) { // Data left
            $table .= '<tr>'; // Starting new row

            $i = 0; // Resetting so in the next increment it will become 1
        }
    }
}

echo $table;
?>

Output is


问:
Running two BackgroundWorkers together
I want to run 2 BackgroundWorkers in parallel. How can I implement it?  In my code below, backgroundWorker2 doesn't work:</p>

```<code>private void Form1_Load(object sender, EventArgs e)
{
  backgroundWorker1.RunWorkerAsync();
  backgroundWorker2.RunWorkerAsync();
}
</code>```

答:
Use the Task Parallel Library instead. Newer way of doing things like this.

Pseudocode using Parallel.Invoke:

```<code>Parallel.Invoke(() => SomeMethod(), () => SomeOtherMethod());
</code>```

Pseudocode with Task:

```<code>async Task SomeMethod() {  }
async Task SomeOtherMethod() {  }

Task task1 = SomeMethod();
Task task2 = SomeOtherMethod();
await Task.WhenAll(task1,task2);
// get results task1.Result and task2.Result
</code>```

Title: Running two BackgroundWorkers together

Body:
I want to run 2 BackgroundWorkers in parallel. How can I implement it?  In my code below, backgroundWorker2 doesn't work:

private void Form1_Load(object sender, EventArgs e)
{
  backgroundWorker1.RunWorkerAsync();
  backgroundWorker2.RunWorkerAsync();
}

Body:
Use the Task Parallel Library instead. Newer way of doing things like this.

Pseudocode using Parallel.Invoke:

Parallel.Invoke(() => SomeMethod(), () => SomeOtherMethod());

Pseudocode with Task:

async Task SomeMethod() {  }
async Task SomeOtherMethod() {  }

Task task1 = SomeMethod();
Task task2 = SomeOtherMethod();
await Task.WhenAll(task1,task2);
// get results task1.Result and task2.Result


问:
How to insert nested params into main params
I am building a Backbone/Marionette web app with Rails 5 as backend. I am sending form data with nested attributes. Unfortunately these nested attributes are added outside of the :goal parameters. How can I insert them into the main (:goal) params before save? Otherwise they are ignored and not inserted into the database.

These are my params sent to server:

```<code>{"id"=>"7", "title"=>"ReBook", "gtype"=>"personal", "starts_at"=>"2017-03-03", "ends_at"=>"2017-10-03", "status"=>"completed", "user_id"=>1, "user_name"=>"Mike", "likes"=>0, "starts_at_formatted"=>"2017-03-03", "ends_at_formatted"=>"2017-10-03", "goalresults_attributes"=>{"description"=>"rrr", "progress"=>"333"}, "goal"=>{"id"=>"7", "user_id"=>1, "title"=>"Rebook", "gtype"=>"personal", "starts_at"=>"2017-03-03", "ends_at"=>"2017-10-03", "status"=>"completed"}}
</code>```

答:
```<code>params['goal']['user_name'] = params['user_name']
params['goal']['likes'] = params['likes']
params['goal']['starts_at_formatted'] = params['starts_at_formatted']
params['goal']['goalresults_attributes'] = params['goalresults_attributes']
params['goal']['progress'] = params['progress']
</code>```

Put this in before you do do update_attributes

It's very dirty/ugly. But it will get the job done

Body:
I am building a Backbone/Marionette web app with Rails 5 as backend. I am sending form data with nested attributes. Unfortunately these nested attributes are added outside of the :goal parameters. How can I insert them into the main (:goal) params before save? Otherwise they are ignored and not inserted into the database.

These are my params sent to server:

{"id"=>"7", "title"=>"ReBook", "gtype"=>"personal", "starts_at"=>"2017-03-03", "ends_at"=>"2017-10-03", "status"=>"completed", "user_id"=>1, "user_name"=>"Mike", "likes"=>0, "starts_at_formatted"=>"2017-03-03", "ends_at_formatted"=>"2017-10-03", "goalresults_attributes"=>{"description"=>"rrr", "progress"=>"333"}, "goal"=>{"id"=>"7", "user_id"=>1, "title"=>"Rebook", "gtype"=>"personal", "starts_at"=>"2017-03-03", "ends_at"=>"2017-10-03", "status"=>"completed"}}

Body:
params['goal']['user_name'] = params['user_name']
params['goal']['likes'] = params['likes']
params['goal']['starts_at_formatted'] = params['starts_at_formatted']
params['goal']['goalresults_attributes'] = params['goalresults_attributes']
params['goal']['progress'] = params['progress']

Put this in before you do do update_attributes

It's very dirty/ugly. But it will get the job done


问:
react-native fetch and basic authentication
I tried to use fetch with this syntax:

```<code>fetch("https://user:password@url", {
   ...
}).then((response) => {
   ...
}).done();
</code>```

The same url works in CURL but returns 401 in React Native.

Any ideas?

Thanks,
Paul

答: You could have used btoa() instead of using the base_64 module. btoa() is a function on the Window.

Body:
I tried to use fetch with this syntax:

fetch("https://user:password@url", {
   ...
}).then((response) => {
   ...
}).done();

The same url works in CURL but returns 401 in React Native.

Any ideas?

Thanks,
Paul


问:
Automapper Many to Many
I've been trying to get this working for too long.  I've looked at every automapper question I could find, but still no luck.

How do I configure Automapper so that it will properly map my many to many properties between my business entity and my database model?

I'm using a repository pattern using a DB first data model.

I have these entity objects:

```<code> public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public DateTime CreateDate { get { return DateTime.Now; } private set { } }
    public List<Department> Departments { get; set; }
    public List<Company> Companies { get; set; }
}

  public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreateDate { get { return DateTime.Now; } private set { } }
}

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreateDate { get { return DateTime.Now; } private set { } }
}
</code>```

I need to be able to update these. I need to map them to the db object so I can update the user.

```<code> public partial class User{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Nullable<System.DateTime> CreateDate { get; set; }

    public virtual ICollection<UsersCompany> UsersCompanies { get; set; }

    public virtual ICollection<UsersDepartment> UsersDepartments { get; set; }
}

public partial class UsersCompany
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int CompanyId { get; set; }

    public virtual Company Company { get; set; }
    public virtual User User { get; set; }
}

public partial class UsersDepartment
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
    public virtual User User { get; set; }
}
</code>```

I have a method in which I pass the entity and attempt to map it to the db model.  This is what I have right now after about 100 different attempts to get automapper to politely map my join tables...with no luck.

```<code>private DBUser ToDataModel(User user)
    {

        var config = new MapperConfiguration(cfg =>
        {

            cfg.CreateMap<User, DBUser>()
            .ForMember(dest => dest.UsersDepartments, opt => opt.MapFrom(x => x.Departments));

            cfg.CreateMap<User, DBUsersDepartment>()
                .ForMember(x => x.User, y => y.MapFrom(z => z));

            cfg.CreateMap<Department, DBUsersDepartment>();

        });
        IMapper mapper = config.CreateMapper();

        return mapper.Map<DBUser>(user);
    }
</code>```

This is what I see after it 'maps' (notice no user information has been mapped):

答:
For anyone interested.  I ended up going a different route, where I update each collection separately, then update the base user class.
...now off to the next issue.</p>

Title: Automapper Many to Many

Body:
I've been trying to get this working for too long.  I've looked at every automapper question I could find, but still no luck.

How do I configure Automapper so that it will properly map my many to many properties between my business entity and my database model?

I'm using a repository pattern using a DB first data model.

I have these entity objects:

 public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public DateTime CreateDate { get { return DateTime.Now; } private set { } }
    public List<Department> Departments { get; set; }
    public List<Company> Companies { get; set; }
}

  public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreateDate { get { return DateTime.Now; } private set { } }
}

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreateDate { get { return DateTime.Now; } private set { } }
}

I need to be able to update these. I need to map them to the db object so I can update the user.

 public partial class User{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Nullable<System.DateTime> CreateDate { get; set; }

    public virtual ICollection<UsersCompany> UsersCompanies { get; set; }

    public virtual ICollection<UsersDepartment> UsersDepartments { get; set; }
}

public partial class UsersCompany
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int CompanyId { get; set; }

    public virtual Company Company { get; set; }
    public virtual User User { get; set; }
}

public partial class UsersDepartment
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
    public virtual User User { get; set; }
}

I have a method in which I pass the entity and attempt to map it to the db model.  This is what I have right now after about 100 different attempts to get automapper to politely map my join tables...with no luck.

private DBUser ToDataModel(User user)
    {

        var config = new MapperConfiguration(cfg =>
        {

            cfg.CreateMap<User, DBUser>()
            .ForMember(dest => dest.UsersDepartments, opt => opt.MapFrom(x => x.Departments));

            cfg.CreateMap<User, DBUsersDepartment>()
                .ForMember(x => x.User, y => y.MapFrom(z => z));

            cfg.CreateMap<Department, DBUsersDepartment>();

        });
        IMapper mapper = config.CreateMapper();

        return mapper.Map<DBUser>(user);
    }

This is what I see after it 'maps' (notice no user information has been mapped):


问:
Kendo Panel Bar not working for alternative load of the panel
I have a requirement where i have to show a popup on click of a button and in the popup i have to show 2 panels. But on alternate click of the button when the popup appears, nothing happens on clicking the panel. I had faced a similar type of issue where a grid was not loading properly on alternate click of the tab where it was present. I just emptied the grid using  $("#GridId").empty before every load and it worked. But i don't understand how to implement that concept in case of panel. I am using Kendo panels and grids. I am setting the panel items using

 tags. It's working when i give expandMode: "single" for the panel bar but my requirement is to show all the panel dropdowns. Can someone help resolve this issue?

答: I solved the issue by adding this line $("#Gridname").kendoPanelBar()  in the $(document).ready function of the js file


问:
Adding elements to an ArrayList and if the element have the same value in the ArrayList, it can't be added
I am developing a search system. I have this problem with same Coordinate getting add more than once into the search queue. I've add some if statements to filter out these problem but it still occur and I have no idea why. I've not found a way to use LinkedHashSet because I tried to add new object into the list.

```<code>    package pathFinding;

    import java.util.ArrayList;
    import java.util.LinkedHashSet;

    public class SearchOld {
    public static Boolean pathFind(Coord start, Coord end /*, ArraList<Coord> blocked*/){

        boolean arrive = false;
        boolean way = false;

        ArrayList<Node> openList = new ArrayList<Node>();
        ArrayList<Node> closedList = new ArrayList<Node>();
        ArrayList<Node> adjNode = new ArrayList<Node>();
        ArrayList<Coord> emptyList = new ArrayList<Coord>();

        int num = 0;
        Node startNode = new Node(start, start);
        closedList.add(startNode);
        openList.add(startNode);
        System.out.println(openList.get(0).getCoord().getX() + " " + openList.get(0).getCoord().getY());
        a:{while(!arrive){
            all:{for(int i = 0;i<openList.size();i++){
                if(end.getX() == openList.get(i).getCoord().getX() && end.getY() == openList.get(i).getCoord().getY()){
                    arrive = true;
                    break all;
            }
            adjNode.addAll(Adjacent.findAdjacent(openList.get(0).getCoord()));
                for(int j=0;j<adjNode.size();j++){
                    check:{for(int k = 0;k<openList.size();k++){
                        if(adjNode.get(0).getCoord().getX() == openList.get(k).getCoord().getX() && adjNode.get(0).getCoord().getY() == openList.get(k).getCoord().getY()){
                            adjNode.remove(0);
                            System.err.println("X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                            arrive = true;
                            break check;
                        }else{
                            for(int l = 0;l<closedList.size();l++){
                                if(adjNode.get(0).getCoord().getX() == closedList.get(l).getCoord().getX() && adjNode.get(0).getCoord().getY() == closedList.get(l).getCoord().getY()){
                                    /*if(end.getX() == adjNode.get(0).getCoord().getX() && end.getY() == adjNode.get(0).getCoord().getY()){
                                        openList.add(adjNode.get(0));
                                        closedList.add(adjNode.get(0));
                                        break all;
                                }*/
                                    adjNode.remove(0);
                                    break check;
                                }else{
                                    openList.add(adjNode.get(0));
                                    adjNode.remove(0);
                                    break check;
                                }
                            }
                        }
                    }}
                }
            closedList.add(openList.get(0));
            openList.remove(0);
            LinkedHashSet<Node> tempSet = new LinkedHashSet<Node>();
            tempSet.addAll(closedList);
            closedList.clear();
            closedList.addAll(tempSet);
        };}

    };}

        //Coordinate got add many times
        for(int m = 0;m<closedList.size();m++){
            if(closedList.get(m).getCoord().getX() != closedList.get(m).getParent().getX() || closedList.get(m).getCoord().getY() != closedList.get(m).getParent().getY()){
            System.out.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());
        }else{
            System.err.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());

            }
        };
        System.out.println(closedList.size());
        System.out.println(arrive);
        //return closedList;
        return arrive;
    }
}
</code>```

Class Adjacent.java

```<code>public static ArrayList<Node> findAdjacent(Coord coord){
    ArrayList<Node> adj = new ArrayList<Node>();

    if(coord.getX() > 1){
        Node left = new Node(new Coord(coord.getX()-1, coord.getY()), coord);
        adj.add(left);
    }
    if(coord.getX() < 25){
        Node right = new Node(new Coord(coord.getX()+1, coord.getY()), coord);
        adj.add(right);
    }
    if(coord.getY() > 1){
        Node up = new Node(new Coord(coord.getX(), coord.getY()-1), coord);
        adj.add(up);
    }
    if(coord.getY() < 25){
        Node down = new Node(new Coord(coord.getX(), coord.getY()+1), coord);
        adj.add(down);
    }
    return adj;

}
</code>```

The ones in comments mean that I will add later when this problem is fixed. Thanks for helping.

[EDIT]

I've now tried @Dhiraj suggestion on changing the comparing method for comparing Coordinates. But the result is still the same, coordinates getting add to the search queue more than once. I've also clean up the code a bit.

Class Search.java:

```<code>package pathFinding;

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class Search {
public static Boolean pathFind(Coord start, Coord end /*, ArraList<Coord> blocked*/){

        boolean arrive = false;
        boolean way = false;

        ArrayList<Node> openList = new ArrayList<Node>();
        ArrayList<Node> closedList = new ArrayList<Node>();
        ArrayList<Node> adjNode = new ArrayList<Node>();
        ArrayList<Coord> emptyList = new ArrayList<Coord>();

        int num = 0;
        Node startNode = new Node(start, start);
        closedList.add(startNode);
        openList.add(startNode);
        System.out.println(openList.get(0).getCoord().getX() + " " + openList.get(0).getCoord().getY());
        a:{while(arrive == false){
            if(CheckList.checkCoordInNodeArray(openList, end) || CheckList.checkCoordInNodeArray(closedList, end)){
                arrive = true;
                break;
            }
            all:{for(int i = 0;i<openList.size();i++){
                adjNode.addAll(Adjacent.findAdjacent(openList.get(0).getCoord()));
                for(int j=0;j<adjNode.size();j++){
                    if(CheckList.checkCoordInNodeArray(adjNode, end)){
                        arrive = true;
                        break all;
                    }
                    if(CheckList.checkCoordInNodeArray(openList, adjNode.get(0).getCoord()) == false || CheckList.checkCoordInNodeArray(closedList, adjNode.get(0).getCoord()) == false){
                        System.out.println("o " + CheckList.checkCoordInNodeArray(openList, adjNode.get(0).getCoord()) + " X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                        System.out.println("c " + CheckList.checkCoordInNodeArray(closedList, adjNode.get(0).getCoord())+ " X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                        openList.add(adjNode.get(0));
                        adjNode.remove(0);
                        break;
                    }else{

                        adjNode.remove(0);
                        break;
                    }
                }
                closedList.add(openList.get(0));
                openList.remove(0);
                LinkedHashSet<Node> tempSet = new LinkedHashSet<Node>();
                tempSet.addAll(closedList);
                closedList.clear();
                closedList.addAll(tempSet);
            };}

        };}

        //Coordinate got add many times
        System.out.println("CSIZE" + closedList.size());
        for(int m = 0;m<closedList.size();m++){
            if(closedList.get(m).getCoord().getX() != closedList.get(m).getParent().getX() || closedList.get(m).getCoord().getY() != closedList.get(m).getParent().getY()){
                System.out.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());
            }else{
                System.err.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());

            }
        };
        System.out.println(closedList.size());
        System.out.println(arrive);
        //return closedList;
        return arrive;
    }
}
</code>```

[EDIT2]
Here's my CheckList.java

```<code>package pathFinding;

import java.util.ArrayList;

public class CheckList {

    public static boolean checkNodeArray(ArrayList<Node> ar, Node no){
        boolean ava = true;
        for(Node node : ar){
            if(no.equals(node.getCoord())){
                ava  = true;
            }else{
                ava = false;
            }
        }
        return ava;
    }

    public static boolean checkCoordInNodeArray(ArrayList<Node> ar, Coord Coor){
        boolean ava = true;
        for(Node node : ar){
            if(Node.compareNodeCoord(Coor, node)){
                ava  = true;
            }else{
                ava = false;
            }
        }
        return ava;
    }

    public static Coord findCoordInNodeArray(ArrayList<Node> ar, Coord Coor){
        Coord coor = Coor;
        for(Node node : ar){
            if(Node.compareNodeCoord(Coor, node) == true){
                coor = node.getParent();
                break;
            }else{

            }
        }
        if(coor == Coor){
            System.err.println("NotFound");
        }
        return coor;
    }
}
</code>```

And here are my compareNodeCoord()

```<code>public static boolean compareNodeCoord(Node node1, Node node2){
        boolean equal = false;
        if(node1.equals(node2.getCoord())){
            equal = true;
        }else{
            equal = false;
        }
        return equal;
    }
    public static boolean compareNodeCoord(Coord coor1, Node node2){
        boolean equal = false;
        if(coor1.equals(node2.getCoord())){
            equal = true;
        }else{
            equal = false;
        }
        return equal;
    }
</code>```

This problem isn't very big a first but when I start to increase the size of the block traveled, the program will be stuck in an very very long loop.

Sorry if this looks messy. I am very new here and also very new to programming using Java.

答:
You should override the equals method to compare the object.
 Please refer the below code as for same.

```<code>public static void main(String[] args) {
        Coordinates c1 = new Coordinates(10, 15);
        List<Coordinates> coordinatesList = new ArrayList<>();
        coordinatesList.add(c1);

        Coordinates c2 = new Coordinates(10, 15);
        for(Coordinates coordinate:coordinatesList ){
        if (coordinate.equals(c2)) {
            System.out.println("Equal ");
        } else {
            System.out.println("Not Equal ");
        }
        }
    }
</code>```

And Coordinates class will be as below

```<code>class Coordinates{
    private double x, y;

    public Coordinates(double x, double y) {
        this.x= x;
        this.y= y;
    }

     // Overriding equals() to compare two Complex objects
    @Override
    public boolean equals(Object o) {

        // If the object is compared with itself then return true
        if (o == this) {
            return true;
        }

        /* Check if o is an instance of Complex or not
          "null instanceof [type]" also returns false */
        if (!(o instanceof Coordinates)) {
            return false;
        }

        // typecast o to Complex so that we can compare data members
        Coordinates c = (Coordinates) o;

        // Compare the data members and return accordingly
        return Double.compare(x, c.x) == 0
                && Double.compare(y, c.y) == 0;
    }
}
</code>```

Body:
I am developing a search system. I have this problem with same Coordinate getting add more than once into the search queue. I've add some if statements to filter out these problem but it still occur and I have no idea why. I've not found a way to use LinkedHashSet because I tried to add new object into the list.

    package pathFinding;

    import java.util.ArrayList;
    import java.util.LinkedHashSet;

    public class SearchOld {
    public static Boolean pathFind(Coord start, Coord end /*, ArraList<Coord> blocked*/){

        boolean arrive = false;
        boolean way = false;

        ArrayList<Node> openList = new ArrayList<Node>();
        ArrayList<Node> closedList = new ArrayList<Node>();
        ArrayList<Node> adjNode = new ArrayList<Node>();
        ArrayList<Coord> emptyList = new ArrayList<Coord>();

        int num = 0;
        Node startNode = new Node(start, start);
        closedList.add(startNode);
        openList.add(startNode);
        System.out.println(openList.get(0).getCoord().getX() + " " + openList.get(0).getCoord().getY());
        a:{while(!arrive){
            all:{for(int i = 0;i<openList.size();i++){
                if(end.getX() == openList.get(i).getCoord().getX() && end.getY() == openList.get(i).getCoord().getY()){
                    arrive = true;
                    break all;
            }
            adjNode.addAll(Adjacent.findAdjacent(openList.get(0).getCoord()));
                for(int j=0;j<adjNode.size();j++){
                    check:{for(int k = 0;k<openList.size();k++){
                        if(adjNode.get(0).getCoord().getX() == openList.get(k).getCoord().getX() && adjNode.get(0).getCoord().getY() == openList.get(k).getCoord().getY()){
                            adjNode.remove(0);
                            System.err.println("X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                            arrive = true;
                            break check;
                        }else{
                            for(int l = 0;l<closedList.size();l++){
                                if(adjNode.get(0).getCoord().getX() == closedList.get(l).getCoord().getX() && adjNode.get(0).getCoord().getY() == closedList.get(l).getCoord().getY()){
                                    /*if(end.getX() == adjNode.get(0).getCoord().getX() && end.getY() == adjNode.get(0).getCoord().getY()){
                                        openList.add(adjNode.get(0));
                                        closedList.add(adjNode.get(0));
                                        break all;
                                }*/
                                    adjNode.remove(0);
                                    break check;
                                }else{
                                    openList.add(adjNode.get(0));
                                    adjNode.remove(0);
                                    break check;
                                }
                            }
                        }
                    }}
                }
            closedList.add(openList.get(0));
            openList.remove(0);
            LinkedHashSet<Node> tempSet = new LinkedHashSet<Node>();
            tempSet.addAll(closedList);
            closedList.clear();
            closedList.addAll(tempSet);
        };}

    };}

        //Coordinate got add many times
        for(int m = 0;m<closedList.size();m++){
            if(closedList.get(m).getCoord().getX() != closedList.get(m).getParent().getX() || closedList.get(m).getCoord().getY() != closedList.get(m).getParent().getY()){
            System.out.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());
        }else{
            System.err.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());

            }
        };
        System.out.println(closedList.size());
        System.out.println(arrive);
        //return closedList;
        return arrive;
    }
}

Class Adjacent.java

public static ArrayList<Node> findAdjacent(Coord coord){
    ArrayList<Node> adj = new ArrayList<Node>();

    if(coord.getX() > 1){
        Node left = new Node(new Coord(coord.getX()-1, coord.getY()), coord);
        adj.add(left);
    }
    if(coord.getX() < 25){
        Node right = new Node(new Coord(coord.getX()+1, coord.getY()), coord);
        adj.add(right);
    }
    if(coord.getY() > 1){
        Node up = new Node(new Coord(coord.getX(), coord.getY()-1), coord);
        adj.add(up);
    }
    if(coord.getY() < 25){
        Node down = new Node(new Coord(coord.getX(), coord.getY()+1), coord);
        adj.add(down);
    }
    return adj;

}

The ones in comments mean that I will add later when this problem is fixed. Thanks for helping.

[EDIT]

I've now tried @Dhiraj suggestion on changing the comparing method for comparing Coordinates. But the result is still the same, coordinates getting add to the search queue more than once. I've also clean up the code a bit.

Class Search.java:

package pathFinding;

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class Search {
public static Boolean pathFind(Coord start, Coord end /*, ArraList<Coord> blocked*/){

        boolean arrive = false;
        boolean way = false;

        ArrayList<Node> openList = new ArrayList<Node>();
        ArrayList<Node> closedList = new ArrayList<Node>();
        ArrayList<Node> adjNode = new ArrayList<Node>();
        ArrayList<Coord> emptyList = new ArrayList<Coord>();

        int num = 0;
        Node startNode = new Node(start, start);
        closedList.add(startNode);
        openList.add(startNode);
        System.out.println(openList.get(0).getCoord().getX() + " " + openList.get(0).getCoord().getY());
        a:{while(arrive == false){
            if(CheckList.checkCoordInNodeArray(openList, end) || CheckList.checkCoordInNodeArray(closedList, end)){
                arrive = true;
                break;
            }
            all:{for(int i = 0;i<openList.size();i++){
                adjNode.addAll(Adjacent.findAdjacent(openList.get(0).getCoord()));
                for(int j=0;j<adjNode.size();j++){
                    if(CheckList.checkCoordInNodeArray(adjNode, end)){
                        arrive = true;
                        break all;
                    }
                    if(CheckList.checkCoordInNodeArray(openList, adjNode.get(0).getCoord()) == false || CheckList.checkCoordInNodeArray(closedList, adjNode.get(0).getCoord()) == false){
                        System.out.println("o " + CheckList.checkCoordInNodeArray(openList, adjNode.get(0).getCoord()) + " X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                        System.out.println("c " + CheckList.checkCoordInNodeArray(closedList, adjNode.get(0).getCoord())+ " X" + adjNode.get(0).getCoord().getX() + "Y" + adjNode.get(0).getCoord().getY());
                        openList.add(adjNode.get(0));
                        adjNode.remove(0);
                        break;
                    }else{

                        adjNode.remove(0);
                        break;
                    }
                }
                closedList.add(openList.get(0));
                openList.remove(0);
                LinkedHashSet<Node> tempSet = new LinkedHashSet<Node>();
                tempSet.addAll(closedList);
                closedList.clear();
                closedList.addAll(tempSet);
            };}

        };}

        //Coordinate got add many times
        System.out.println("CSIZE" + closedList.size());
        for(int m = 0;m<closedList.size();m++){
            if(closedList.get(m).getCoord().getX() != closedList.get(m).getParent().getX() || closedList.get(m).getCoord().getY() != closedList.get(m).getParent().getY()){
                System.out.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());
            }else{
                System.err.println("X"+closedList.get(m).getCoord().getX()+"Y"+closedList.get(m).getCoord().getY() +"Parent X" + closedList.get(m).getParent().getX() + "Y" + closedList.get(m).getParent().getY());

            }
        };
        System.out.println(closedList.size());
        System.out.println(arrive);
        //return closedList;
        return arrive;
    }
}

[EDIT2]
Here's my CheckList.java

package pathFinding;

import java.util.ArrayList;

public class CheckList {

    public static boolean checkNodeArray(ArrayList<Node> ar, Node no){
        boolean ava = true;
        for(Node node : ar){
            if(no.equals(node.getCoord())){
                ava  = true;
            }else{
                ava = false;
            }
        }
        return ava;
    }

    public static boolean checkCoordInNodeArray(ArrayList<Node> ar, Coord Coor){
        boolean ava = true;
        for(Node node : ar){
            if(Node.compareNodeCoord(Coor, node)){
                ava  = true;
            }else{
                ava = false;
            }
        }
        return ava;
    }

    public static Coord findCoordInNodeArray(ArrayList<Node> ar, Coord Coor){
        Coord coor = Coor;
        for(Node node : ar){
            if(Node.compareNodeCoord(Coor, node) == true){
                coor = node.getParent();
                break;
            }else{

            }
        }
        if(coor == Coor){
            System.err.println("NotFound");
        }
        return coor;
    }
}

And here are my compareNodeCoord()

public static boolean compareNodeCoord(Node node1, Node node2){
        boolean equal = false;
        if(node1.equals(node2.getCoord())){
            equal = true;
        }else{
            equal = false;
        }
        return equal;
    }
    public static boolean compareNodeCoord(Coord coor1, Node node2){
        boolean equal = false;
        if(coor1.equals(node2.getCoord())){
            equal = true;
        }else{
            equal = false;
        }
        return equal;
    }

This problem isn't very big a first but when I start to increase the size of the block traveled, the program will be stuck in an very very long loop.

Sorry if this looks messy. I am very new here and also very new to programming using Java.

Body:
You should override the equals method to compare the object.
 Please refer the below code as for same.

public static void main(String[] args) {
        Coordinates c1 = new Coordinates(10, 15);
        List<Coordinates> coordinatesList = new ArrayList<>();
        coordinatesList.add(c1);

        Coordinates c2 = new Coordinates(10, 15);
        for(Coordinates coordinate:coordinatesList ){
        if (coordinate.equals(c2)) {
            System.out.println("Equal ");
        } else {
            System.out.println("Not Equal ");
        }
        }
    }

And Coordinates class will be as below

class Coordinates{
    private double x, y;

    public Coordinates(double x, double y) {
        this.x= x;
        this.y= y;
    }

     // Overriding equals() to compare two Complex objects
    @Override
    public boolean equals(Object o) {

        // If the object is compared with itself then return true
        if (o == this) {
            return true;
        }

        /* Check if o is an instance of Complex or not
          "null instanceof [type]" also returns false */
        if (!(o instanceof Coordinates)) {
            return false;
        }

        // typecast o to Complex so that we can compare data members
        Coordinates c = (Coordinates) o;

        // Compare the data members and return accordingly
        return Double.compare(x, c.x) == 0
                && Double.compare(y, c.y) == 0;
    }
}


问:
angular 2 ng2-translate custom TranslateLoader not working with API
ng2-translate not working with custom TranslateLoader when fetching data from API. Below is my custom TranslateLoader

translateCustomLoader.ts

```<code>@Injectable()
export class CustomTranslateLoader implements TranslateLoader  {

    constructor(private http: Http, private apiService: AuthHttp) { console.log("customer loader initialized"); }

    getTranslation(lang: string): Observable<any>{
        var apiAddress = "http://test.com/api/gettranslationsfromDB?culture=" + lang;

        return this.apiService.get(apiAddress).map((res) => res.json());

        //return Observable.of({ "hello": "translatedhello","welcome":"translatedwelcome"});
    }
}
</code>```

Response from API is

```<code>{ "hello": "translatedhello","welcome":"translatedwelcome"}
</code>```

Added TranslateLoader to providers in app.module.ts

```<code>providers: [CustomTranslateLoader, { provide: TranslateLoader, useClass: CustomTranslateLoader}]
</code>```

In my HTML page I have below

```<code><h4>{{ 'hello' | translate }}</h4>
</code>```

I still see hello getting rendered.This works fine if I replace

```<code>return this.apiService.get(apiAddress).map((res) => res.json());
</code>```

with

```<code>return Observable.of({ "hello": "translatedhello","welcome":"translatedwelcome"});
</code>```

So I am pretty sure there isn't anything wrong with the configuration.What am I missing here?

答:
I got it working by changing getTranslation as below

```<code>getTranslation(lang: string): Observable<any> {
    var apiAddress = "http://test.com/api/gettranslationsfromDB?culture=" + lang;
    return Observable.create(observer => {
            this.authService.get(apiAddress)
                .subscribe((res: Response) => {
                    observer.next(JSON.parse(res.json()));
                    observer.complete();
                });
        });

    }
</code>```

Although doesn't make much sense to me. Hope this helps someone.

Body:
ng2-translate not working with custom TranslateLoader when fetching data from API. Below is my custom TranslateLoader

translateCustomLoader.ts

@Injectable()
export class CustomTranslateLoader implements TranslateLoader  {

    constructor(private http: Http, private apiService: AuthHttp) { console.log("customer loader initialized"); }

    getTranslation(lang: string): Observable<any>{
        var apiAddress = "http://test.com/api/gettranslationsfromDB?culture=" + lang;

        return this.apiService.get(apiAddress).map((res) => res.json());

        //return Observable.of({ "hello": "translatedhello","welcome":"translatedwelcome"});
    }
}

Response from API is

{ "hello": "translatedhello","welcome":"translatedwelcome"}

Added TranslateLoader to providers in app.module.ts

providers: [CustomTranslateLoader, { provide: TranslateLoader, useClass: CustomTranslateLoader}]

In my HTML page I have below

{{ 'hello' | translate }}

I still see hello getting rendered.This works fine if I replace

return this.apiService.get(apiAddress).map((res) => res.json());

with

return Observable.of({ "hello": "translatedhello","welcome":"translatedwelcome"});

So I am pretty sure there isn't anything wrong with the configuration.What am I missing here?

Body:
I got it working by changing getTranslation as below

getTranslation(lang: string): Observable<any> {
    var apiAddress = "http://test.com/api/gettranslationsfromDB?culture=" + lang;
    return Observable.create(observer => {
            this.authService.get(apiAddress)
                .subscribe((res: Response) => {
                    observer.next(JSON.parse(res.json()));
                    observer.complete();
                });
        });

    }

Although doesn't make much sense to me. Hope this helps someone.


问:
Two floats throw TypeError: unsupported operand type(s) for +: 'float' and 'str'
I am running into an issue with the following line of code:

underground['distributed_load_C'] = float(ugLineList[21])*1000 + ('+' if float(ugLineList[24]) >= 0.0 else '-') + abs(float(ugLineList[24]))*1000j

The original values pulled from ugLineList are strings and I try to type cast them into floats before addition. Even though I try to type cast them I am getting the following error:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

I've tried type casting them before this statement, and checking that the code snippets are truly floats:
print type(float(ugLineList[21])*1000), type(float(ugLineList[24]))
---> <type 'float'> <type 'float'>

I am really confused as to what is going on here so any help is greatly appreciated.

Thanks!!

答:
The comment above (you are adding the string '+' or '-' depending on the value of ugLineList[24]) is exactly correct. Assuming you intend to add or subtract

```<code>abs(float(ugLineList[24]))*1000j
</code>```

based on the evaluation of your if statement, you could do something like:

```<code>res = float(ugLineList[21])*1000
if float(ugLineList[24]) >= 0.0:
   res += abs(float(ugLineList[24]))*1000j
else:
   res -= abs(float(ugLineList[24]))*1000j
underground['distributed_load_C'] = res
</code>```

hope this helps

Body:
The comment above (you are adding the string '+' or '-' depending on the value of ugLineList[24]) is exactly correct. Assuming you intend to add or subtract

abs(float(ugLineList[24]))*1000j

based on the evaluation of your if statement, you could do something like:

res = float(ugLineList[21])*1000
if float(ugLineList[24]) >= 0.0:
   res += abs(float(ugLineList[24]))*1000j
else:
   res -= abs(float(ugLineList[24]))*1000j
underground['distributed_load_C'] = res

hope this helps


问:
ReactNative - Simulator works, iPhone crashes
First app development in ReactNative. I just started to load data in via API and now the App crashes on my phone - but works fine in the simulator. The only errors I have (nothing in console) are from xCode, see image:

Any help debugging / fixing this issue?

Thanks

答: This was an issue because I was running 8.2 in simulator and 10.2 on my phone. 10.2 does not allow you to fetch using http, only https.</p>


问:
Cakephp 3 Callback method not reached
I have a problem with the afterDelete callback method. I can't use them.

Inside one of my "Storages" plugin controllers I want to delete a record and after that I want to do some other thinks, but the callback method is not reached. I have checked this with adding a log message inside the afterDelete() callback method.

This is the controller where I removed a record:

```<code>namespace Storages\Controller;

class StoragecontainerBlocksController extends AppController {

   public function initialize() {
       parent::initialize();
       $this->loadComponent('RequestHandler');
   }

   public function ajaxDeleteBlockElement() {
       $this->autoRender = false;

       // load model
       $this->loadModel("StoragecontainerBlockElements");

       // get element id
       $elementId = $this->request->data('id');

       $this->request->allowMethod(['post', 'delete']);

       // delete element
       $storagecontainerBlockElement = $this->StoragecontainerBlockElements->get($elementId);
       $this->StoragecontainerBlockElements->delete($storagecontainerBlockElement);
   }
}
</code>```

This is the (model) table where the afterDelete callback is defined:

```<code>  use Cake\Log\Log;
  class StoragecontainerBlockElementsTable extends Table {

   public function afterDelete(Event $event) {
       Log::debug('Got here');
   }
  }
</code>```

Update:

When I debugged Log::debug($this->StoragecontainerBlockElements); inside the ajaxDeleteBlockElement function I got the following array inside debug.log file:

```<code>2017-03-31 07:03:48 Debug: Cake\ORM\Table Object
(
    [registryAlias] => StoragecontainerBlockElements
    [table] => storagecontainer_block_elements
    [alias] => StoragecontainerBlockElements
    [entityClass] => \Cake\ORM\Entity
    [associations] => Array
        (
        )

    [behaviors] => Array
        (
        )

    [defaultConnection] => default
    [connectionName] => default
</code>```

Update:

```<code>namespace Storages\Model\Table;

use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Log\Log;

class StoragecontainerBlockElementsTable extends Table {

    public function initialize(array $config) {
       parent::initialize($config);
    }

    public function afterDelete(Event $event) {
       Log::debug('Got here');
    }
}
</code>```

答:
Try

```<code>use Cake\Log\Log;
use Cake\ORM\Table;

class StoragecontainerBlockElementsTable extends Table {

    public function afterDelete($event, $entity, $options){
        Log::debug('Got here');

    }
}
</code>```

Details Here

Title: Cakephp 3 Callback method not reached

Body:
I have a problem with the afterDelete callback method. I can't use them.

Inside one of my "Storages" plugin controllers I want to delete a record and after that I want to do some other thinks, but the callback method is not reached. I have checked this with adding a log message inside the afterDelete() callback method.

This is the controller where I removed a record:

namespace Storages\Controller;

class StoragecontainerBlocksController extends AppController {

   public function initialize() {
       parent::initialize();
       $this->loadComponent('RequestHandler');
   }

   public function ajaxDeleteBlockElement() {
       $this->autoRender = false;

       // load model
       $this->loadModel("StoragecontainerBlockElements");

       // get element id
       $elementId = $this->request->data('id');

       $this->request->allowMethod(['post', 'delete']);

       // delete element
       $storagecontainerBlockElement = $this->StoragecontainerBlockElements->get($elementId);
       $this->StoragecontainerBlockElements->delete($storagecontainerBlockElement);
   }
}

This is the (model) table where the afterDelete callback is defined:

  use Cake\Log\Log;
  class StoragecontainerBlockElementsTable extends Table {

   public function afterDelete(Event $event) {
       Log::debug('Got here');
   }
  }

Update:

When I debugged Log::debug($this->StoragecontainerBlockElements); inside the ajaxDeleteBlockElement function I got the following array inside debug.log file:

2017-03-31 07:03:48 Debug: Cake\ORM\Table Object
(
    [registryAlias] => StoragecontainerBlockElements
    [table] => storagecontainer_block_elements
    [alias] => StoragecontainerBlockElements
    [entityClass] => \Cake\ORM\Entity
    [associations] => Array
        (
        )

    [behaviors] => Array
        (
        )

    [defaultConnection] => default
    [connectionName] => default

Update:

namespace Storages\Model\Table;

use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Log\Log;

class StoragecontainerBlockElementsTable extends Table {

    public function initialize(array $config) {
       parent::initialize($config);
    }

    public function afterDelete(Event $event) {
       Log::debug('Got here');
    }
}

Body:
Try

use Cake\Log\Log;
use Cake\ORM\Table;

class StoragecontainerBlockElementsTable extends Table {

    public function afterDelete($event, $entity, $options){
        Log::debug('Got here');

    }
}

Details Here


问:
whats wrong with the following code for thread in java?
```<code>class threaddemo extends Thread

{
    Thread t ;
    t=Thread.currentThread();//error(incompatible type. thread cant,t be converted to t)
    String s=t.getName();

    @Override
    public void run()
    {
        for(int i=0;i<5;i++)
        {
            System.out.println(i+" "+t.getName());
            try
            {
                Thread.sleep(1000);
            } catch (InterruptedException ex)
            {
                Logger.getLogger(threaddemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
</code>```

答:
You can't do initialisation like:

```<code>Thread t ;
t=Thread.currentThread(); //error(incompatible type. thread cant,t be converted to t)
</code>```

if you are outside of a method.

If the variable is a field of a class, you basically* have to do declaration and instantiation on one line:

```<code>Thread t = Thread.currentThread();
</code>```

*I say basically because this is not strictly true. You can also use constructors, for example:

```<code>class MyClass
{
    String str; //declaration

    MyClass()
    {
        str = "hello"; //instantiation
    }
}
</code>```

There is at least one other method which is less common and I wouldn't worry about for now. This page of Oracle's site describes it.

Body:
You can't do initialisation like:

Thread t ;
t=Thread.currentThread(); //error(incompatible type. thread cant,t be converted to t)

if you are outside of a method.

If the variable is a field of a class, you basically* have to do declaration and instantiation on one line:

Thread t = Thread.currentThread();

*I say basically because this is not strictly true. You can also use constructors, for example:

class MyClass
{
    String str; //declaration

    MyClass()
    {
        str = "hello"; //instantiation
    }
}

There is at least one other method which is less common and I wouldn't worry about for now. This page of Oracle's site describes it.