问:
Formula to find part of a cell's value as exact match to a value from other cells
On tab 1, I have data down column B that contains string values like this:

\\ABC\VOL1\DATA\Dan\Personal Folders

  \\ABC\VOL1\DATA\Mike\My Stuff\Docs\Support

  \\ABC\VOL1\DATA\Mike\My Stuff\Photos

  \\ABC\VOL1\DATA\Bob\Plans

On tab 2, I have data down column C that I want to use as a lookup table like this:

\\ABC\VOL1\DATA\Adam

  \\ABC\VOL1\DATA\Steve

  \\ABC\VOL1\DATA\Mike

  \\ABC\VOL1\DATA\Ronnie

I need a formula I can put on tab 1 down column C to see if any part of each text string from tab 1, column B matches any complete text string from tab 2, column C.  So for example, I would place this formula to show Yes or No like this:

Column B......................................................................Column C

  \\ABC\VOL1\DATA\Dan\Personal Folders....................No

  \\ABC\VOL1\DATA\Mike\My Stuff\Docs\Support..........Yes

  \\ABC\VOL1\DATA\Mike\My Stuff\Photos.....................Yes

  \\ABC\VOL1\DATA\Bob\Plans.......................................No

I have tried VLOOKUP, INDEX/MATCH, ISNUMBER/SEARCH, and COUNTIF as an array with wildcards, but I just cannot seem to figure it out.  Currently, with COUNTIF as array, I have this:

```<code>=COUNTIF(B2,"*" & 'Tab 2'!$C$2:$C$1000 & "*")
</code>```

This is the start to return the array results, but the results aren't as I would expect as I get "0" when I should get "1" for certain rows.

If anyone can help me out with a formula (not VBA) using any of the functions mentioned above or any others, I would greatly appreciate it.  Thanks.

答:
use this array formula:

```<code>=IF(COUNT(SEARCH('Tab 2'!$C$2:INDEX('Tab 2'!$C:$C,MATCH("zzz",'Tab 2'!$C:$C)),B2)),"Yes","No")
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

Body:
On tab 1, I have data down column B that contains string values like this:

\\ABC\VOL1\DATA\Dan\Personal Folders

  \\ABC\VOL1\DATA\Mike\My Stuff\Docs\Support

  \\ABC\VOL1\DATA\Mike\My Stuff\Photos

  \\ABC\VOL1\DATA\Bob\Plans

On tab 2, I have data down column C that I want to use as a lookup table like this:

\\ABC\VOL1\DATA\Adam

  \\ABC\VOL1\DATA\Steve

  \\ABC\VOL1\DATA\Mike

  \\ABC\VOL1\DATA\Ronnie

I need a formula I can put on tab 1 down column C to see if any part of each text string from tab 1, column B matches any complete text string from tab 2, column C.  So for example, I would place this formula to show Yes or No like this:

Column B......................................................................Column C

  \\ABC\VOL1\DATA\Dan\Personal Folders....................No

  \\ABC\VOL1\DATA\Mike\My Stuff\Docs\Support..........Yes

  \\ABC\VOL1\DATA\Mike\My Stuff\Photos.....................Yes

  \\ABC\VOL1\DATA\Bob\Plans.......................................No

I have tried VLOOKUP, INDEX/MATCH, ISNUMBER/SEARCH, and COUNTIF as an array with wildcards, but I just cannot seem to figure it out.  Currently, with COUNTIF as array, I have this:

=COUNTIF(B2,"*" & 'Tab 2'!$C$2:$C$1000 & "*")

This is the start to return the array results, but the results aren't as I would expect as I get "0" when I should get "1" for certain rows.

If anyone can help me out with a formula (not VBA) using any of the functions mentioned above or any others, I would greatly appreciate it.  Thanks.

Body:
use this array formula:

=IF(COUNT(SEARCH('Tab 2'!$C$2:INDEX('Tab 2'!$C:$C,MATCH("zzz",'Tab 2'!$C:$C)),B2)),"Yes","No")

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


来源: stackexchange

问:
Autowire HashMap of @Component
I have an interface:

```<code>public interface EmailSender {

    void send(Locale locale, List<User> recipients, int ticketId);

}
</code>```

And few different implementations, and I want to autowire a HashMap of them, to have possibility to get concrete realization by class name, but when I write:

```<code>@Autowired
private HashMap<String, EmailSender> emailSenders;
</code>```

I get an exception:

No qualifying bean of type 'java.util.HashMap'

```<code>@Autowired
private List<EmailSender> emailSenders;
</code>```

It is interesting that whet I tried to change HashMap to List all worked fine, do you know how to correctly do that?

答:
If you define your bean of your own(not collectable) type:

With Spring you can create few beans of same type. But in this case you can't do this:

```<code>@Authowire
private MyBean bean1;

@Authowire
private MyBean bean2;
</code>```

But you can do next:

```<code>@Authowire
@Qualifier("firstBean")
private MyBean bean1;

@Authowire
@Qualifier("firstBean")
private MyBean bean2;
</code>```

And in same time you can get all instances of you bean, asking for getting list of them

```<code>@Authowire
private List<MyBean> beans;  // all you beans will be here
</code>```

If you defined your bean of type List or Map of your type:

Also please take a look on https://stackoverflow.com/a/13914052/814304
If you use Spring version lower then 4.3 you need use annotation @Resource if you defined you bean of type Map or List.

ContentLicense: CC BY-SA 4.0

Title: Autowire HashMap of @Component

Body:
I have an interface:

public interface EmailSender {

    void send(Locale locale, List<User> recipients, int ticketId);

}

And few different implementations, and I want to autowire a HashMap of them, to have possibility to get concrete realization by class name, but when I write:

@Autowired
private HashMap<String, EmailSender> emailSenders;

I get an exception:

No qualifying bean of type 'java.util.HashMap'

@Autowired
private List<EmailSender> emailSenders;

It is interesting that whet I tried to change HashMap to List all worked fine, do you know how to correctly do that?

Body:
If you define your bean of your own(not collectable) type:

With Spring you can create few beans of same type. But in this case you can't do this:

@Authowire
private MyBean bean1;

@Authowire
private MyBean bean2;

But you can do next:

@Authowire
@Qualifier("firstBean")
private MyBean bean1;

@Authowire
@Qualifier("firstBean")
private MyBean bean2;

And in same time you can get all instances of you bean, asking for getting list of them

@Authowire
private List<MyBean> beans;  // all you beans will be here

If you defined your bean of type List or Map of your type:

Also please take a look on https://stackoverflow.com/a/13914052/814304
If you use Spring version lower then 4.3 you need use annotation @Resource if you defined you bean of type Map or List.

ContentLicense: CC BY-SA 3.0


问:
How to wrap around a range
Angles in my program are expressed in 0 to 2pi. I want a way to add two angles and have it wrap around the 2pi to 0 if the result is higher than 2pi. Or if I subtracted an angle from an angle and it was below 0 it would wrap around 2pi.

Is there a way to do this?

Thanks.

答:
Simple trick: Just add an offset, which must be a multiple of 2pi, to bring the result into a positive range prior to doing the fmod(). The fmod() will bring it back into the range [0, 2pi) automagically. This works as long as you know a priori the range of possible inputs you might get (which you often do). The larger the offset you apply, the more bits of FP precision you loose, so you probably don't want to add, say, 20000pi, although that would certainly be "safer" in terms of handling very large out-of-bounds inputs. Presuming no one would ever pass input angles that sum outside the rather crazy range [-8pi, +inf), we'll just add 8pi before fmod()ing.

```<code>double add_angles(float a, float b)
{
    ASSERT(a + b >= -8.0f*PI);
    return fmod(a + b + 8.0f*PI, 2.0f*PI);
}
</code>```

Title: How to wrap around a range

Body:
Simple trick: Just add an offset, which must be a multiple of 2pi, to bring the result into a positive range prior to doing the fmod(). The fmod() will bring it back into the range [0, 2pi) automagically. This works as long as you know a priori the range of possible inputs you might get (which you often do). The larger the offset you apply, the more bits of FP precision you loose, so you probably don't want to add, say, 20000pi, although that would certainly be "safer" in terms of handling very large out-of-bounds inputs. Presuming no one would ever pass input angles that sum outside the rather crazy range [-8pi, +inf), we'll just add 8pi before fmod()ing.

double add_angles(float a, float b)
{
    ASSERT(a + b >= -8.0f*PI);
    return fmod(a + b + 8.0f*PI, 2.0f*PI);
}


问:
Google Chrome - Is it possible to include a SQLite db within the extension
Is it possible to include a DB file packed in with the extension when you download it.
I'm trying to include a small DB with zip codes so the extension does not have to request a look up for the proper zip code.

possible at all?

答:
Basically what I would do in a Chrome Extension, is packaging it up with a "zip_codes.json" file. Then when your extension loads, use XHR to read that file. For example, the below snippet is to asynchronously (you can use synchronous too if you want) get the zip codes stored in your extension.

```<code>var zipcodes = {};
var xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL('zip_codes.json'), false);
xhr.onreadystatechange = function() {
  zip_codes = JSON.parse(xhr.responseText);
  console.log(zip_codes);
}
</code>```

I would believe this approach would be easier to manage than adding your own localStorage cache for the files, because once you ship it, you can always update that file.

So if your zip_codes.json file has the following:

```<code>{
  33445: 'Some zip'
}
</code>```

You can just access that zip code using the following approach:

```<code>console.log(zip_codes[33445]);
</code>```

Hope that helped!

ContentLicense: CC BY-SA 2.5

Body:
Basically what I would do in a Chrome Extension, is packaging it up with a "zip_codes.json" file. Then when your extension loads, use XHR to read that file. For example, the below snippet is to asynchronously (you can use synchronous too if you want) get the zip codes stored in your extension.

var zipcodes = {};
var xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL('zip_codes.json'), false);
xhr.onreadystatechange = function() {
  zip_codes = JSON.parse(xhr.responseText);
  console.log(zip_codes);
}

I would believe this approach would be easier to manage than adding your own localStorage cache for the files, because once you ship it, you can always update that file.

So if your zip_codes.json file has the following:

{
  33445: 'Some zip'
}

You can just access that zip code using the following approach:

console.log(zip_codes[33445]);

Hope that helped!


问:
Images take time and get loaded after loading text contents on my website
I want my images to be loaded fast as HTML and CSS get loaded.
As of now HTML and CSS don't take time but loading images (all are in .svg format and small) take more than 2 seconds after other content.

Is there a way to load them faster?

I found answers regarding fast-loading and followed as well, which are:

-compress images

-Minify HTML and JS files

But my issue is still unresolved.

答:
angular js loads script and style that are ready to load and with no errors, and load error later.

if the image size is big it surely would load slow, high resolution images tends to load slow.

are you using external script and style in your code, like fonts, jquery or any other framework, try load them locally to improve site speed.

local servers like xamp, wamp etc loads base on system speed , so you cant judge else you are on production stage.

you are right minified version could work.

alternative

big sites like facebok, yahoo and google, uses site.loader to check if all site content is loaded and two if loaded display all site content.

since you are using js, check if all script are up to date and no one is using outdated function

check for errors in console .

limit your use of image.

hope that was helpful.


问:
2D array with discrete colors not working for one middle value
I have a 2D array of values between 0 and (including) 22.
I want every value to have a discrete colour and hover value assigned to it in a normal matshow plot.
I tried it with just a Colormap and with a normalization but the colours 15 and 16 are not consistent.

Without any normalization 15 has the colour of 16 (and of course the hover values are misaligned floats).
With normalization, everything is fine except 16 has the colour of 15.

I saw multiple other questions asking the same thing but following the answers resulted in this problem.

```<code>import matplotlib.pyplot as plt
import matplotlib.colors as colors

example_data = [list(range(23))]*4
cmaplist = [
    "#b3b3b3", "#333333", "#8a745c", "#8f7456",
    "#847362", "#1a53ff", "#336600", "#aa8a31",
    "#b3b3b3", "#aa8a31", "#aa8a31", "#004d00",
    "#aa8a31", "#5c330a", "#999999", "#66d9ff",
    "#e481a2", "#e996b1", "#e481a2", "#e06c92",
    "#e87da1", "#fff11c", "#ff6600"
]
norm = colors.BoundaryNorm(range(len(cmaplist)+1), len(cmaplist))
cmap = colors.LinearSegmentedColormap.from_list('mycmap', cmaplist, len(cmaplist))

plt.matshow(example_data, fignum=False, cmap=cmap, norm=norm)
plt.show()
</code>```

I am not very good with matplotlib etc. so this may be a really obvious mistake. I am treating this just like its just a simple value lookup of the data but I am aware that that's not how it actually works but I can't think of a better approach with my limited knowledge.

答:
First try to create a MCVE:

```<code>import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

example_data = np.array([list(range(20))]*4)
cmaplist = ["red", "limegreen", "blue", "gold"]*5

fig, ax = plt.subplots()

norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)-0.5, len(cmaplist))
cmap = colors.LinearSegmentedColormap.from_list('mycmap',cmaplist, len(cmaplist))

im = ax.matshow(example_data, cmap=cmap, norm=norm)

plt.show()
</code>```

As can be seen, the color at positions 14 and 15 is the same, while position 15 should be yellow. This is present in matplotlib 2.1, in matplotlib 2.0.2 the issue seems not to be there. I therefore opened a bug report about it.

Solution:

The numbers you are mapping (which are integers here) are exactly on the edge of the boundaries. I'm not exactly sure what goes wrong here, but to be on the save side, you may use the middle between two integers as the boundary, i.e.

```norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)<b>-0.5</b>, len(cmaplist))```

Complete example:

```<code>import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

example_data = np.array([list(range(20))]*4)
cmaplist = ["red", "limegreen", "blue", "gold"]*5

fig, ax = plt.subplots()

norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)-0.5, len(cmaplist))
cmap = colors.LinearSegmentedColormap.from_list('mycmap',cmaplist, len(cmaplist))

im = ax.matshow(example_data, cmap=cmap, norm=norm)

plt.show()
</code>```

Body:
I have a 2D array of values between 0 and (including) 22.
I want every value to have a discrete colour and hover value assigned to it in a normal matshow plot.
I tried it with just a Colormap and with a normalization but the colours 15 and 16 are not consistent.

Without any normalization 15 has the colour of 16 (and of course the hover values are misaligned floats).
With normalization, everything is fine except 16 has the colour of 15.

I saw multiple other questions asking the same thing but following the answers resulted in this problem.

import matplotlib.pyplot as plt
import matplotlib.colors as colors

example_data = [list(range(23))]*4
cmaplist = [
    "#b3b3b3", "#333333", "#8a745c", "#8f7456",
    "#847362", "#1a53ff", "#336600", "#aa8a31",
    "#b3b3b3", "#aa8a31", "#aa8a31", "#004d00",
    "#aa8a31", "#5c330a", "#999999", "#66d9ff",
    "#e481a2", "#e996b1", "#e481a2", "#e06c92",
    "#e87da1", "#fff11c", "#ff6600"
]
norm = colors.BoundaryNorm(range(len(cmaplist)+1), len(cmaplist))
cmap = colors.LinearSegmentedColormap.from_list('mycmap', cmaplist, len(cmaplist))

plt.matshow(example_data, fignum=False, cmap=cmap, norm=norm)
plt.show()

I am not very good with matplotlib etc. so this may be a really obvious mistake. I am treating this just like its just a simple value lookup of the data but I am aware that that's not how it actually works but I can't think of a better approach with my limited knowledge.

Body:
First try to create a MCVE:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

example_data = np.array([list(range(20))]*4)
cmaplist = ["red", "limegreen", "blue", "gold"]*5

fig, ax = plt.subplots()

norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)-0.5, len(cmaplist))
cmap = colors.LinearSegmentedColormap.from_list('mycmap',cmaplist, len(cmaplist))

im = ax.matshow(example_data, cmap=cmap, norm=norm)

plt.show()

As can be seen, the color at positions 14 and 15 is the same, while position 15 should be yellow. This is present in matplotlib 2.1, in matplotlib 2.0.2 the issue seems not to be there. I therefore opened a bug report about it.

Solution:

The numbers you are mapping (which are integers here) are exactly on the edge of the boundaries. I'm not exactly sure what goes wrong here, but to be on the save side, you may use the middle between two integers as the boundary, i.e.

norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)-0.5, len(cmaplist))

Complete example:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

example_data = np.array([list(range(20))]*4)
cmaplist = ["red", "limegreen", "blue", "gold"]*5

fig, ax = plt.subplots()

norm = colors.BoundaryNorm(np.arange(0,len(cmaplist)+1)-0.5, len(cmaplist))
cmap = colors.LinearSegmentedColormap.from_list('mycmap',cmaplist, len(cmaplist))

im = ax.matshow(example_data, cmap=cmap, norm=norm)

plt.show()


问:
Gulp Stream completion with promises
I am trying to read a file in, do a transform that is promise based and push the results through the stream. Here is the example code.

```<code>const gulp = require('gulp')
const gutil = require('gulp-util')
const through2 = require('through2')
const fs = require('fs')

module.exports = (filePath, options) => {

    return gulp.src(filePath)
    .pipe(through2.obj(function (file, enc, cb) {
        const result = file.contents.toString(enc)
        Promise.resolve(result)
        .then( result => {
            cb(null, result)
        })
        .catch(() => {})

    }))

}
</code>```

For some reason when the promise resolves and I try to call the callback I get nothing downstream and the stream never completes.

I have also tried this.push(result) and then call the callback but still the same issue. Any help would be appreciated

答:
So after some searching through other gulp util repos I see that this is how to resolve the callback properly:</p>

```<code>return gulp.src(filePath)
 .pipe(through2.obj(function (file, enc, cb) {
    const result = file.contents.toString(enc)
    Promise.resolve(result)
    .then( result => {
        file.contents = new Buffer(result);
        this.push(file)
        cb()
    })
    .catch(() => {})

}))
</code>```

Title: Gulp Stream completion with promises

Body:
I am trying to read a file in, do a transform that is promise based and push the results through the stream. Here is the example code.

const gulp = require('gulp')
const gutil = require('gulp-util')
const through2 = require('through2')
const fs = require('fs')

module.exports = (filePath, options) => {

    return gulp.src(filePath)
    .pipe(through2.obj(function (file, enc, cb) {
        const result = file.contents.toString(enc)
        Promise.resolve(result)
        .then( result => {
            cb(null, result)
        })
        .catch(() => {})

    }))

}

For some reason when the promise resolves and I try to call the callback I get nothing downstream and the stream never completes.

I have also tried this.push(result) and then call the callback but still the same issue. Any help would be appreciated

Body:
So after some searching through other gulp util repos I see that this is how to resolve the callback properly:

return gulp.src(filePath)
 .pipe(through2.obj(function (file, enc, cb) {
    const result = file.contents.toString(enc)
    Promise.resolve(result)
    .then( result => {
        file.contents = new Buffer(result);
        this.push(file)
        cb()
    })
    .catch(() => {})

}))


问:
Fancybox 3 CSS for Thumbnail Sidebar
How can I change the color of the thumbnail side bar from white to black?</p>

答:
This can be done using CSS, for example:

```<code>.fancybox-thumbs {
  background: rgba(0, 0, 0, 0.3);
}
</code>```

Demo - https://codepen.io/anon/pen/POgEMb

Title: Fancybox 3 CSS for Thumbnail Sidebar

Body:
This can be done using CSS, for example:

.fancybox-thumbs {
  background: rgba(0, 0, 0, 0.3);
}

Demo - https://codepen.io/anon/pen/POgEMb


问:
ValueError: Found input variables with inconsistent numbers of samples: [100, 7]
Currently trying to have the program guess the animal based on the feature that is included in the zoo database.
 When I run this code it gets the error ''ValueError: Found input variables with inconsistent numbers of samples: [100, 7]''. It shows the error happens on this line ''X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)''

```<code>def zoo_that():
    zoodatabase = pd.read_csv('C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/zoo.csv', header = 0)
    classtypes = pd.read_csv('C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/class.csv',header = 0,)
    zoodatabase_v2 = zoodatabase.merge(classtypes,how = 'left',left_on = 'class_type',right_on = 'Class_Number')
    X = zoodatabase_v2.loc[:, 'hair':'catsize']
    Y = zoodatabase_v2.loc[:, 'class_type':'Class_Number']
    testing_size = 0.2
    seed = 2
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)

    # Test options and evaluation metric|
    scoring = 'accuracy'

    models = []
    models.append(('LR', LogisticRegression()))
    models.append(('LDA', LinearDiscriminantAnalysis()))
    models.append(('KNN', KNeighborsClassifier()))
    models.append(('CART', DecisionTreeClassifier()))
    models.append(('NB', GaussianNB()))
    models.append(('SVM', SVC()))
    # evaluate each model in turn
    results = []
    names = []
    for name, model in models:
        kfold = model_selection.KFold(n_splits=4, random_state=seed)
        cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
        results.append(cv_results)
        names.append(name)
        msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
        print(msg)

    # Make predictions on validation dataset
    LR = LogisticRegression()
    LR.fit(X_train, Y_train)
    predictions = LR.predict(X_validation)
    print("Accuracy score\n",accuracy_score(Y_validation, predictions))
    print("Confusion matrix\n",confusion_matrix(Y_validation, predictions))
    print("Final Report\n",classification_report(Y_validation, predictions))
    print(scoring)
</code>```

```<code>zoo_that()
Traceback (most recent call last):

  File "<ipython-input-20-396e334d1676>", line 1, in <module>
    zoo_that()

  File "C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/Final Submission.py", line 35, in zoo_that
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)

  File "D:\Anaconda\lib\site-packages\sklearn\model_selection\_split.py", line 2031, in train_test_split
    arrays = indexable(*arrays)

  File "D:\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 229, in indexable
    check_consistent_length(*result)

  File "D:\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 204, in check_consistent_length
    " samples: %r" % [int(l) for l in lengths])

ValueError: Found input variables with inconsistent numbers of samples: [100, 7]
</code>```

Picture of the files
  [1]: https://i.stack.imgur.com/OaJmO.jpg [This is the Class Csv][1]
  [2]: https://i.stack.imgur.com/FL0by.jpg [This is the Zoo Csv][2]

答:
The problem is with this part:

```<code>X = zoodatabase_v2.loc[1:101,'hair':'catsize']
Y = zoodatabase_v2.loc[0:6,'Class_Type':'Animal_Names']
</code>```

X is a DataFrame with length 100 (1:101), and Y is a Series with length 6. To train a model (supervised learning), you need to give target labels for ALL input records. Also, you need to give a single target label, whereas currently it looks as if you are giving 2 ('Animal_Names' and 'Class_Type'). If you remove the subsetting, it should work. i.e.

```<code>X = zoodatabase_v2.loc[:, 'hair':'catsize']
Y = zoodatabase_v2.loc[:, 'Class_Type']
</code>```

should work fine.

Body:
Currently trying to have the program guess the animal based on the feature that is included in the zoo database.
 When I run this code it gets the error ''ValueError: Found input variables with inconsistent numbers of samples: [100, 7]''. It shows the error happens on this line ''X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)''

def zoo_that():
    zoodatabase = pd.read_csv('C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/zoo.csv', header = 0)
    classtypes = pd.read_csv('C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/class.csv',header = 0,)
    zoodatabase_v2 = zoodatabase.merge(classtypes,how = 'left',left_on = 'class_type',right_on = 'Class_Number')
    X = zoodatabase_v2.loc[:, 'hair':'catsize']
    Y = zoodatabase_v2.loc[:, 'class_type':'Class_Number']
    testing_size = 0.2
    seed = 2
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)

    # Test options and evaluation metric|
    scoring = 'accuracy'

    models = []
    models.append(('LR', LogisticRegression()))
    models.append(('LDA', LinearDiscriminantAnalysis()))
    models.append(('KNN', KNeighborsClassifier()))
    models.append(('CART', DecisionTreeClassifier()))
    models.append(('NB', GaussianNB()))
    models.append(('SVM', SVC()))
    # evaluate each model in turn
    results = []
    names = []
    for name, model in models:
        kfold = model_selection.KFold(n_splits=4, random_state=seed)
        cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
        results.append(cv_results)
        names.append(name)
        msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
        print(msg)

    # Make predictions on validation dataset
    LR = LogisticRegression()
    LR.fit(X_train, Y_train)
    predictions = LR.predict(X_validation)
    print("Accuracy score\n",accuracy_score(Y_validation, predictions))
    print("Confusion matrix\n",confusion_matrix(Y_validation, predictions))
    print("Final Report\n",classification_report(Y_validation, predictions))
    print(scoring)

zoo_that()
Traceback (most recent call last):

  File "<ipython-input-20-396e334d1676>", line 1, in <module>
    zoo_that()

  File "C:/Users/Quentin Clayton/Documents/Class work/Quarter 9/Data Analytics Project I/Final Project for Project Course/Final Submission.py", line 35, in zoo_that
    X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=testing_size, random_state=seed)

  File "D:\Anaconda\lib\site-packages\sklearn\model_selection\_split.py", line 2031, in train_test_split
    arrays = indexable(*arrays)

  File "D:\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 229, in indexable
    check_consistent_length(*result)

  File "D:\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 204, in check_consistent_length
    " samples: %r" % [int(l) for l in lengths])

ValueError: Found input variables with inconsistent numbers of samples: [100, 7]

Picture of the files
  [1]: https://i.stack.imgur.com/OaJmO.jpg [This is the Class Csv][1]
  [2]: https://i.stack.imgur.com/FL0by.jpg [This is the Zoo Csv][2]

Body:
The problem is with this part:

X = zoodatabase_v2.loc[1:101,'hair':'catsize']
Y = zoodatabase_v2.loc[0:6,'Class_Type':'Animal_Names']

X is a DataFrame with length 100 (1:101), and Y is a Series with length 6. To train a model (supervised learning), you need to give target labels for ALL input records. Also, you need to give a single target label, whereas currently it looks as if you are giving 2 ('Animal_Names' and 'Class_Type'). If you remove the subsetting, it should work. i.e.

X = zoodatabase_v2.loc[:, 'hair':'catsize']
Y = zoodatabase_v2.loc[:, 'Class_Type']

should work fine.


问:
Showing a partial view in a modal popup
I have a partial view called Search.cshtml that I display in /Home/Index.  In this file, I have an HTML form that searches and pulls back /Views/Accounts/Index with the search results.  I want to display those results in the modal popup div that is in the Search view.

When I Click the Search (sumbit input) in the code below I get an empty modal.

I am still a novice when it comes to MVC.  I tried a few different results I found on Stack Overflow, but I haven't been able to find the resolution.  The code below at least gives me a modal pop up, although it is blank.

Am I missing something insanely simple?  I have tried everything in the modal-body below (Html.Action, RenderAction, Partial, RenderPartial) and nothing seems to work.  Also, am I barking up the wrong tree there?

I have a couple screenshots and the code below.

/Home/Index with Search partial view

Empty Search Modal

Search.cshtml

```<code>@model CustomerRelationshipManager.Models.Search

@{ViewBag.Title = "Search";}
@using (Html.BeginForm("Index", "Accounts", new { id = "searchForm" }))
{

<div style="border: solid 1px #ccc; padding: 30px 0 30px 30px; border-radius: 5px;
    width: 325px; margin: auto; display: table;">
    <table>
        <tr>
            <td valign="top">
                Search By:
            </td>
            <td>
                @Html.DropDownList("Search_Type", "Search_Type")
            </td>
        </tr>
        <tr>
            <td valign="top"></td>
            <td>
                @Html.TextBox("Search_String")
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" data-toggle="modal" data-target="#myModal" value="Search" />
            </td>
        </tr>
    </table>
</div>

<div class="modal fade" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title">Modal title</h4>
            </div>
            <div class="modal-body">
                @{Html.Action("Index","Accounts");}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code>```

}

HomeController.cs

```<code>    public ActionResult Search()
    {
        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem() { Text = "Account Number", Value = "Account_ID" });
        items.Add(new SelectListItem() { Text = "Last Name", Value = "Last_Name" });
        items.Add(new SelectListItem() { Text = "Phone Number", Value = "Phone_Number" });
        ViewBag.Search_Type = items;
        return PartialView();
    }

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Search(Search search)
    {

        return PartialView("~/Accounts/Index");
        //return RedirectToAction("Index", "Accounts");
    }
</code>```

AccountController.cs (I want to call Index() from this Controller)

```<code>public ActionResult Index(string Search_Type, string Search_String)
    {
        if (Search_String == null)
        {
            var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Address)
                .Include(a => a.Account_Contact);
            return PartialView(accounts.ToList());
        }
        else
        {
            if (Search_Type == "Account_ID")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Address)
                .Include(a => a.Account_Contact)
                .Where(a => a.Account_ID.ToString() == Search_String);
                return PartialView(accounts.ToList());
            }
            else if (Search_Type == "Last_Name")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Where(b => b.Account_Person.Any(c => c.Person.Last_Name.StartsWith(Search_String)))
                .Include(a => a.Account_Contact)
                .Include(a => a.Account_Address);
                return PartialView(accounts.ToList());
            }
            else if (Search_Type == "Phone_Number")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Contact)
                .Where(b => b.Account_Contact.Any(c => c.Contact.Value == Search_String && c.Contact.Contact_Type.Name.Contains("Phone")))
                .Include(a => a.Account_Address);
                return PartialView(accounts.ToList());
            }
            else
            {
                var accounts = db.Accounts
                    .Include(a => a.Account_Type)
                    .Include(a => a.Account_Person)
                    .Include(a => a.Account_Address)
                    .Include(a => a.Account_Contact);
                return PartialView(accounts.ToList());
            }
        }
</code>```

Account Index.cshtml (I want to display this in the modal popup)

```<code>@model IEnumerable<CustomerRelationshipManager.Models.Account>

@{
ViewBag.Title = "Home";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>Account #</th>
    <th>Contact Name(s)</th>
    <th>Address</th>
    <th>Contact</th>
</tr>
w2
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Account_ID)
            <span> </span>
        </td>
        <td>
            @foreach (var i in item.Account_Person)
            {
                <span>
                    <b>@Html.DisplayFor(x => i.Person_Type.Name)</b>
                    <br />
                    @Html.DisplayFor(x => i.Person.First_Name)

                    @Html.DisplayFor(x => i.Person.Last_Name)
                </span>
                <br />
            }
        </td>
        <td>
            @foreach (var i in item.Account_Address)
            {
                <span>
                    <b>@Html.DisplayFor(x => i.Address_Type.Name)</b>
                    <br />
                    @Html.DisplayFor(x => i.Address.Address1)
                    <br />
                    @Html.DisplayFor(x => i.Address.Address2)
                    @if (i.Address.Address2 != null)
                    { <br />}
                    @Html.DisplayFor(x => i.Address.City)

                    @Html.DisplayFor(x => i.Address.State)

                    @Html.DisplayFor(x => i.Address.Postal_Code)
                    <br />
                    @Html.DisplayFor(x => i.Address.Country)
                    <br />
                </span>
            }
        </td>
        <td>
            @foreach (var i in item.Account_Contact)
            {
                <span>
                    <b>@Html.DisplayFor(x => i.Contact.Contact_Type.Name)</b>
                    <br />
                    @Html.DisplayFor(x => i.Contact.Value)
                    <br />
                </span>

            }

        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.Account_ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.Account_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Account_ID })
        </td>
    </tr>
}
</code>```

答:
I figured it out!

I moved the modal  outside of the HTML.BeginForm in the Search.cshtml.  Then, I simplified the input on the form and removed the data-toggle and data-target properties.

```<code>@model CustomerRelationshipManager.Models.Search

@{
  ViewBag.Title = "Search";
}
@using (Html.BeginForm("Index", "Accounts", FormMethod.Post, new { id = "searchForm" }))
{

<div style="border: solid 1px #ccc; padding: 30px 0 30px 30px; border-radius: 5px;
width: 325px; margin: auto; display: table;">
    <table>
    <tr>
        <td valign="top">
            Search By:
        </td>
        <td>
            @Html.DropDownList("Search_Type", "Search_Type")
        </td>
    </tr>
    <tr>
        <td valign="top"></td>
        <td>
            @Html.TextBox("Search_String")
        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <input type="submit" id="submit" value="Search" />
        </td>
    </tr>
</table>
</div>
}
<div class="modal fade" id="myModal">
    <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title">Modal</h4>
        </div>
        <div class="modal-body">

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</code>```

I moved the javascript to the bottom of the _layout.cshtml shared file.

```<code>@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

<script type="text/javascript">
$(document).ready(function () {
    $('#searchForm').submit(function (e) {
        e.preventDefault();
        var $form = $(this);
        $.post($form.attr("action"), $form.serialize()).done(function (res) {
            $mymodal = $("#myModal");
            //update the modal's body with the response received
            $mymodal.find("div.modal-body").html(res);
            // Show the modal
            $mymodal.modal("show");
        });
    });

   });
</code>```

After figuring that out, I had a LINQ error that I discovered by setting a breakpoint in the Index() function of my AccountsController.  Once I fixed that, the Index() Action in my AccountsController Appeared in my Modal Popup.

HomeController Search() Modal Dialog Displaying AccountsController Index()

Thanks for your help, Shyju!

Title: Showing a partial view in a modal popup

Body:
I have a partial view called Search.cshtml that I display in /Home/Index.  In this file, I have an HTML form that searches and pulls back /Views/Accounts/Index with the search results.  I want to display those results in the modal popup div that is in the Search view.

When I Click the Search (sumbit input) in the code below I get an empty modal.

I am still a novice when it comes to MVC.  I tried a few different results I found on Stack Overflow, but I haven't been able to find the resolution.  The code below at least gives me a modal pop up, although it is blank.

Am I missing something insanely simple?  I have tried everything in the modal-body below (Html.Action, RenderAction, Partial, RenderPartial) and nothing seems to work.  Also, am I barking up the wrong tree there?

I have a couple screenshots and the code below.

/Home/Index with Search partial view

Empty Search Modal

Search.cshtml

@model CustomerRelationshipManager.Models.Search

@{ViewBag.Title = "Search";}
@using (Html.BeginForm("Index", "Accounts", new { id = "searchForm" }))
{

                Search By:

                @Html.DropDownList("Search_Type", "Search_Type")

                @Html.TextBox("Search_String")

                <input type="submit" data-toggle="modal" data-target="#myModal" value="Search" />

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

                @{Html.Action("Index","Accounts");}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

}

HomeController.cs

    public ActionResult Search()
    {
        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem() { Text = "Account Number", Value = "Account_ID" });
        items.Add(new SelectListItem() { Text = "Last Name", Value = "Last_Name" });
        items.Add(new SelectListItem() { Text = "Phone Number", Value = "Phone_Number" });
        ViewBag.Search_Type = items;
        return PartialView();
    }

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Search(Search search)
    {

        return PartialView("~/Accounts/Index");
        //return RedirectToAction("Index", "Accounts");
    }

AccountController.cs (I want to call Index() from this Controller)

public ActionResult Index(string Search_Type, string Search_String)
    {
        if (Search_String == null)
        {
            var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Address)
                .Include(a => a.Account_Contact);
            return PartialView(accounts.ToList());
        }
        else
        {
            if (Search_Type == "Account_ID")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Address)
                .Include(a => a.Account_Contact)
                .Where(a => a.Account_ID.ToString() == Search_String);
                return PartialView(accounts.ToList());
            }
            else if (Search_Type == "Last_Name")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Where(b => b.Account_Person.Any(c => c.Person.Last_Name.StartsWith(Search_String)))
                .Include(a => a.Account_Contact)
                .Include(a => a.Account_Address);
                return PartialView(accounts.ToList());
            }
            else if (Search_Type == "Phone_Number")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Contact)
                .Where(b => b.Account_Contact.Any(c => c.Contact.Value == Search_String && c.Contact.Contact_Type.Name.Contains("Phone")))
                .Include(a => a.Account_Address);
                return PartialView(accounts.ToList());
            }
            else
            {
                var accounts = db.Accounts
                    .Include(a => a.Account_Type)
                    .Include(a => a.Account_Person)
                    .Include(a => a.Account_Address)
                    .Include(a => a.Account_Contact);
                return PartialView(accounts.ToList());
            }
        }

Account Index.cshtml (I want to display this in the modal popup)

@model IEnumerable<CustomerRelationshipManager.Models.Account>

@{
ViewBag.Title = "Home";
}

Index

@Html.ActionLink("Create New", "Create")

    Account #
    Contact Name(s)
    Address
    Contact

w2
@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.Account_ID)

            @foreach (var i in item.Account_Person)
            {

                    @Html.DisplayFor(x => i.Person_Type.Name)

                    @Html.DisplayFor(x => i.Person.First_Name)

                    @Html.DisplayFor(x => i.Person.Last_Name)

            }

            @foreach (var i in item.Account_Address)
            {

                    @Html.DisplayFor(x => i.Address_Type.Name)

                    @Html.DisplayFor(x => i.Address.Address1)

                    @Html.DisplayFor(x => i.Address.Address2)
                    @if (i.Address.Address2 != null)
                    {
}
                    @Html.DisplayFor(x => i.Address.City)

                    @Html.DisplayFor(x => i.Address.State)

                    @Html.DisplayFor(x => i.Address.Postal_Code)

                    @Html.DisplayFor(x => i.Address.Country)

            }

            @foreach (var i in item.Account_Contact)
            {

                    @Html.DisplayFor(x => i.Contact.Contact_Type.Name)

                    @Html.DisplayFor(x => i.Contact.Value)

            }

            @Html.ActionLink("Edit", "Edit", new { id = item.Account_ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.Account_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Account_ID })

}

Body:
I figured it out!

I moved the modal  outside of the HTML.BeginForm in the Search.cshtml.  Then, I simplified the input on the form and removed the data-toggle and data-target properties.

@model CustomerRelationshipManager.Models.Search

@{
  ViewBag.Title = "Search";
}
@using (Html.BeginForm("Index", "Accounts", FormMethod.Post, new { id = "searchForm" }))
{

<div style="border: solid 1px #ccc; padding: 30px 0 30px 30px; border-radius: 5px;
width: 325px; margin: auto; display: table;">
    <table>
    <tr>
        <td valign="top">
            Search By:
        </td>
        <td>
            @Html.DropDownList("Search_Type", "Search_Type")
        </td>
    </tr>
    <tr>
        <td valign="top"></td>
        <td>
            @Html.TextBox("Search_String")
        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <input type="submit" id="submit" value="Search" />
        </td>
    </tr>
</table>
</div>
}
<div class="modal fade" id="myModal">
    <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Modal</h4>
        </div>
        <div class="modal-body">

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

I moved the javascript to the bottom of the _layout.cshtml shared file.

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

<script type="text/javascript">
$(document).ready(function () {
    $('#searchForm').submit(function (e) {
        e.preventDefault();
        var $form = $(this);
        $.post($form.attr("action"), $form.serialize()).done(function (res) {
            $mymodal = $("#myModal");
            //update the modal's body with the response received
            $mymodal.find("div.modal-body").html(res);
            // Show the modal
            $mymodal.modal("show");
        });
    });

   });

After figuring that out, I had a LINQ error that I discovered by setting a breakpoint in the Index() function of my AccountsController.  Once I fixed that, the Index() Action in my AccountsController Appeared in my Modal Popup.

HomeController Search() Modal Dialog Displaying AccountsController Index()

Thanks for your help, Shyju!


问:
Loop through all pixels and get/set individual pixel color in OpenGL?
I wrote a little thingy with Processing that I now would like to make a Mac OS X Screen Saver of. However, diving in to OpenGL was not as easy as I thought it would be.

Basically I want to loop through all pixels on screen and based on that pixels color set another pixels color.

The Processing code looks like this:

```<code>void setup(){
  size(500,500, P2D);
  frameRate(30);
  background(255);
}

void draw(){
 for(int x = 0; x<width; x++){
  for(int y = 0; y<height; y++){
     float xRand2 = x+random(2);
     float yRand2 = y+random(2);

     int xRand = int(xRand2);
     int yRand = int(yRand2);

     if(get(x,y) == -16777216){
     set(x+xRand, y+yRand, #FFFFFF);
     }
     else if(get(x,y) == -1){
     set(x+xRand, y+yRand, #000000);
     }
   }
 }
}
</code>```

It's not very pretty and nor is it very effective. However, I'd like to find out how to do something similiar with OpenGL. I don't even know where to start.

答: If you don't want to go the shader route, try doing all your pixel modification in the CPU on a 2D memory array, then use glDrawPixels every frame to push your pixels to the screen.  It won't be very hardware accelerated, but it might be fine for your purposes.  Another thing to try is to use glTexImage2D to bind your new pixel data every frame to a texture and then render a textured quad to the entire screen.  I'm not sure which will be faster.  My advice is to try these things before jumping into the complexity of shaders.</p>

Body:
I wrote a little thingy with Processing that I now would like to make a Mac OS X Screen Saver of. However, diving in to OpenGL was not as easy as I thought it would be.

Basically I want to loop through all pixels on screen and based on that pixels color set another pixels color.

The Processing code looks like this:

void setup(){
  size(500,500, P2D);
  frameRate(30);
  background(255);
}

void draw(){
 for(int x = 0; x<width; x++){
  for(int y = 0; y<height; y++){
     float xRand2 = x+random(2);
     float yRand2 = y+random(2);

     int xRand = int(xRand2);
     int yRand = int(yRand2);

     if(get(x,y) == -16777216){
     set(x+xRand, y+yRand, #FFFFFF);
     }
     else if(get(x,y) == -1){
     set(x+xRand, y+yRand, #000000);
     }
   }
 }
}

It's not very pretty and nor is it very effective. However, I'd like to find out how to do something similiar with OpenGL. I don't even know where to start.


问:
How should I replace a reference to an IP in Docker Swarm
I am trying to install ELK in Docker Swarm mode.

Then, I need to tell filebeat to send logs to logstash.

Here is my filebeat config file:

```<code>#=========================== Filebeat prospectors =============================
## Each - is a prospector. Most options can be set at the prospector level, so
## you can use different prospectors for various configurations.
## Below are the prospector specific configurations.
filebeat.prospectors:
- input_type: log
  enabled: true
  paths:
{% for log in in_filebeat_dict.filebeat.logs | default([]) %}
    - {{ log }}
{% endfor %}

#================================ Outputs =====================================
# Configure what output to use when sending the data collected by the beat.
output.logstash:
  hosts: ["{{ in_filebeat_dict.filebeat.output.logstash }}:{{ in_filebeat_dict.filebeat.output.port}}"]
</code>```

but in_filebeat_dict.filebeat.output.logstash is an IP and in Swarm mode, Swarm will not decide where to install containers, so I'm a bit stuck here...

Any ideas ???

答: In swarm mode discovery works over ne --name parameter. So when you deploy logstash with --name logstash other services can access it by calling the name logstash. But remember, they need to be in the same network which is not ingress. Create a new overlay network if you haven't done it yet and assign all services to that.

Body:
I am trying to install ELK in Docker Swarm mode.

Then, I need to tell filebeat to send logs to logstash.

Here is my filebeat config file:

#=========================== Filebeat prospectors =============================
## Each - is a prospector. Most options can be set at the prospector level, so
## you can use different prospectors for various configurations.
## Below are the prospector specific configurations.
filebeat.prospectors:
- input_type: log
  enabled: true
  paths:
{% for log in in_filebeat_dict.filebeat.logs | default([]) %}
    - {{ log }}
{% endfor %}

#================================ Outputs =====================================
# Configure what output to use when sending the data collected by the beat.
output.logstash:
  hosts: ["{{ in_filebeat_dict.filebeat.output.logstash }}:{{ in_filebeat_dict.filebeat.output.port}}"]

but in_filebeat_dict.filebeat.output.logstash is an IP and in Swarm mode, Swarm will not decide where to install containers, so I'm a bit stuck here...

Any ideas ???


问:
Swift: Gesture Recognizer doesn't register Taps after changing alpha to 0 and back to 1
the UIView in question is headerView:

```<code>    if isShown {
        stack.alpha = 1.0
        self.isStackShown = true
        DispatchQueue.main.async {
            self.headerView.isHidden = !isShown
            self.stack.addArrangedSubview(self.headerView)

            // add touch gesture recognizer to stack view header
            let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
            self.headerView.addGestureRecognizer(tapFind)
        }
    } else {
        stack.alpha = 0.0
        self.isStackShown = false
        DispatchQueue.main.async {
            self.headerView.isHidden = isShown
            self.stack.removeArrangedSubview(self.headerView)
        }
    }
</code>```

The tap gesture recognizer is not registering any taps

self.stack is the stack view which contains the headerView

The condition for either showing or hiding the headerView is being handled in a different method and just passes the boolean self.isStackShown to this method to show/hide accordingly.

答:
Looks like you are adding multiple gesture recognizers when changing back the alpha to 1.0 and they aren't able to recognize simultaneously. Remove all gesture recognizers when hiding and removing the headerView since you don't need one anymore and add one back when adding back the headerView and it should work. Or you can also let the gesture recognizer be when hiding the headerView since it won't work anyway and check if one exists before adding another.

```<code>if isShown {
    stack.alpha = 1.0
    self.isStackShown = true
    DispatchQueue.main.async {
        self.headerView.isHidden = !isShown
        self.stack.addArrangedSubview(self.headerView)

        // add touch gesture recognizer to stack view header
        let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
        self.headerView.addGestureRecognizer(tapFind)
    }
} else {
    stack.alpha = 0.0
    self.isStackShown = false
    DispatchQueue.main.async {
        self.headerView.isHidden = isShown
        self.headerView.gestureRecognizers?.forEach({self.headerView.removeGestureRecognizer($0)})
        self.stack.removeArrangedSubview(self.headerView)
    }
}
</code>```

or

```<code>if isShown {
    stack.alpha = 1.0
    self.isStackShown = true
    DispatchQueue.main.async {
        self.headerView.isHidden = !isShown
        self.stack.addArrangedSubview(self.headerView)
        if self.headerView.gestureRecognizers?.isEmpty != false{
           // add touch gesture recognizer to stack view header
           let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
           self.headerView.addGestureRecognizer(tapFind)
        }
    }
} else {
    stack.alpha = 0.0
    self.isStackShown = false
    DispatchQueue.main.async {
        self.headerView.isHidden = isShown
        self.stack.removeArrangedSubview(self.headerView)
    }
}
</code>```

Body:
the UIView in question is headerView:

    if isShown {
        stack.alpha = 1.0
        self.isStackShown = true
        DispatchQueue.main.async {
            self.headerView.isHidden = !isShown
            self.stack.addArrangedSubview(self.headerView)

            // add touch gesture recognizer to stack view header
            let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
            self.headerView.addGestureRecognizer(tapFind)
        }
    } else {
        stack.alpha = 0.0
        self.isStackShown = false
        DispatchQueue.main.async {
            self.headerView.isHidden = isShown
            self.stack.removeArrangedSubview(self.headerView)
        }
    }

The tap gesture recognizer is not registering any taps

self.stack is the stack view which contains the headerView

The condition for either showing or hiding the headerView is being handled in a different method and just passes the boolean self.isStackShown to this method to show/hide accordingly.

Body:
Looks like you are adding multiple gesture recognizers when changing back the alpha to 1.0 and they aren't able to recognize simultaneously. Remove all gesture recognizers when hiding and removing the headerView since you don't need one anymore and add one back when adding back the headerView and it should work. Or you can also let the gesture recognizer be when hiding the headerView since it won't work anyway and check if one exists before adding another.

if isShown {
    stack.alpha = 1.0
    self.isStackShown = true
    DispatchQueue.main.async {
        self.headerView.isHidden = !isShown
        self.stack.addArrangedSubview(self.headerView)

        // add touch gesture recognizer to stack view header
        let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
        self.headerView.addGestureRecognizer(tapFind)
    }
} else {
    stack.alpha = 0.0
    self.isStackShown = false
    DispatchQueue.main.async {
        self.headerView.isHidden = isShown
        self.headerView.gestureRecognizers?.forEach({self.headerView.removeGestureRecognizer($0)})
        self.stack.removeArrangedSubview(self.headerView)
    }
}

or

if isShown {
    stack.alpha = 1.0
    self.isStackShown = true
    DispatchQueue.main.async {
        self.headerView.isHidden = !isShown
        self.stack.addArrangedSubview(self.headerView)
        if self.headerView.gestureRecognizers?.isEmpty != false{
           // add touch gesture recognizer to stack view header
           let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
           self.headerView.addGestureRecognizer(tapFind)
        }
    }
} else {
    stack.alpha = 0.0
    self.isStackShown = false
    DispatchQueue.main.async {
        self.headerView.isHidden = isShown
        self.stack.removeArrangedSubview(self.headerView)
    }
}


问:
Bingind data to linechart
i have datatable which has 2 columns and 8 rows and the output is like below;

```<code>Size     Improvement
--------------------
256       -26.05
512       -646.13
768       -38.96
1024      0
1280      1.13
1536      1.34
1792      1.34
2048      1.34
</code>```

I want to assign 'Size' column on X-axis and 'Improvement' column on Y-axis and i want to show only improvement column values on line chart.

However when i bind the datatable 'Size' column goes to on 'Y-axis' and X-axis display nothing.

How can i control the columns on axis?

答:
I am not sure if you need UltraChart or UltraDataChart. If you need UltraChart you should use Scatter chart, and not Line chart. Also you will need to add some labels to your data like this:

```<code>var dt = new DataTable();
dt.Columns.Add("label");
dt.Columns.Add("Size", typeof(int));
dt.Columns.Add("Improvement", typeof(double));

dt.Rows.Add(new object[] { "a", 256, -26.05 });
dt.Rows.Add(new object[] { "b", 512, -646.13 });
dt.Rows.Add(new object[] { "c", 768, -38.96 });
dt.Rows.Add(new object[] { "d", 1024, 0 });
dt.Rows.Add(new object[] { "e", 1280, 1.13 });
dt.Rows.Add(new object[] { "f", 1536, 1.34 });
dt.Rows.Add(new object[] { "g", 1792, 1.34 });
dt.Rows.Add(new object[] { "h", 2048, 1.34 });
</code>```

Then set the type of your chart to ScatterChart, bind the data and ConnectWithLines property to true like this:

```<code>this.ultraChart1.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.ScatterChart;
this.ultraChart1.DataSource = dt;
this.ultraChart1.DataBind();
this.ultraChart1.ScatterChart.ConnectWithLines = true;
</code>```

If you need UltraDataChart you should use ScatterLineSeries as shown in Infragistics online help here - "Scatter Line Series"

Title: Bingind data to linechart

Body:
i have datatable which has 2 columns and 8 rows and the output is like below;

Size     Improvement
--------------------
256       -26.05
512       -646.13
768       -38.96
1024      0
1280      1.13
1536      1.34
1792      1.34
2048      1.34

I want to assign 'Size' column on X-axis and 'Improvement' column on Y-axis and i want to show only improvement column values on line chart.

However when i bind the datatable 'Size' column goes to on 'Y-axis' and X-axis display nothing.

How can i control the columns on axis?

Body:
I am not sure if you need UltraChart or UltraDataChart. If you need UltraChart you should use Scatter chart, and not Line chart. Also you will need to add some labels to your data like this:

var dt = new DataTable();
dt.Columns.Add("label");
dt.Columns.Add("Size", typeof(int));
dt.Columns.Add("Improvement", typeof(double));

dt.Rows.Add(new object[] { "a", 256, -26.05 });
dt.Rows.Add(new object[] { "b", 512, -646.13 });
dt.Rows.Add(new object[] { "c", 768, -38.96 });
dt.Rows.Add(new object[] { "d", 1024, 0 });
dt.Rows.Add(new object[] { "e", 1280, 1.13 });
dt.Rows.Add(new object[] { "f", 1536, 1.34 });
dt.Rows.Add(new object[] { "g", 1792, 1.34 });
dt.Rows.Add(new object[] { "h", 2048, 1.34 });

Then set the type of your chart to ScatterChart, bind the data and ConnectWithLines property to true like this:

this.ultraChart1.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.ScatterChart;
this.ultraChart1.DataSource = dt;
this.ultraChart1.DataBind();
this.ultraChart1.ScatterChart.ConnectWithLines = true;

If you need UltraDataChart you should use ScatterLineSeries as shown in Infragistics online help here - "Scatter Line Series"


问:
Can any one please suggest which sql query is better approach for large data set in mysql
I have to find the max id row for same group in a table and show the roe details.Using following two approach we can achieve it. But want know which will be good approach for large data. Or any other new approach that will take less time to execute?

Approach 1:

```<code>select a.* from tab1 a left join (SELECT max(id) as id,name from tab1
GROUP by name) as tab2 on a.id=tab2.id where a.id=tab2.id
</code>```

Approach 2:

```<code>SELECT id,name from tab1 where id in(SELECT MAX(id) FROM tab1 GROUP by name)
</code>```

答:
You can also use a window function to avoid a self-join:

```<code>SELECT id, name
FROM (
  SELECT
    id,
    name,
    RANK() OVER(PARTITION BY name ORDER BY Id DESC) AS IdRankPerGroup
  FROM tab1
) src
WHERE IdRankPerGroup = 1
</code>```

The RANK() function orders each row per "name" group and assigns a ranking based on the "id" value within each group.  Then in the outer query, you just get the rows with a ranking = 1.

Try all three queries, check out the EXPLAIN plans, and see which one works best with large amounts of data.

Body:
I have to find the max id row for same group in a table and show the roe details.Using following two approach we can achieve it. But want know which will be good approach for large data. Or any other new approach that will take less time to execute?

Approach 1:

select a.* from tab1 a left join (SELECT max(id) as id,name from tab1
GROUP by name) as tab2 on a.id=tab2.id where a.id=tab2.id

Approach 2:

SELECT id,name from tab1 where id in(SELECT MAX(id) FROM tab1 GROUP by name)

Body:
You can also use a window function to avoid a self-join:

SELECT id, name
FROM (
  SELECT
    id,
    name,
    RANK() OVER(PARTITION BY name ORDER BY Id DESC) AS IdRankPerGroup
  FROM tab1
) src
WHERE IdRankPerGroup = 1

The RANK() function orders each row per "name" group and assigns a ranking based on the "id" value within each group.  Then in the outer query, you just get the rows with a ranking = 1.

Try all three queries, check out the EXPLAIN plans, and see which one works best with large amounts of data.


问:
Use CSS selectors to collect HTML elements from a streaming parser (e.g. SAX stream)
How to parse CSS (CSS3) selector and use it (in jQuery-like way) to collect HTML elements not from DOM (from tree structure), but from stream (e.g. SAX), i.e. using sequential access event based parser?

By the way, are there any CSS selectors (or their combination) that need access to DOM (Wikipedia SAX page says that XPath selectors "need to be able to access any node at any time in the parsed XML tree")?

I am most interested in implementing selector combinators, e.g. 'A B' descendant selector.

I prefer solutions describing algorithm, or in Perl (for HTML::Zoom).

答:
What does a browser do to create the DOM out of a stream? I guess there lies the answer to your question because it must be storing the discovered elements in a form which facilitates a CSS selector query. If you can afford reading the source code for an open source browser parser, then I think you can reuse it.

I would not do so, honestly. Rather I would reuse an existing SAX based parser (maybe you rewrite another with perl), and that go through the entire string.
When handlers fire, use them to construct an in memory database for elements. Create a virtual "table" for every element with it's #number [for references] , tagName, parent #number, next #number and its opening tag char offset in the source mother string.
As well, create a table for every attribute ever found, and fill it with a record for each tag with that attribute value.

Now it's all about the process of creating a database, tables and indices.


问:
Docker Hub: How do I pull an older version of a 3rd party image?
How do I pull an older build of a 3rd party image from Docker Hub?

For example I would like to pull this build of appropriate/curl.

I've tried using the "Build Code" as the tag, as well as the partial SHA256 of the image shown at the end of the build, and neither work.

Note: this is different from Docker: How do I pull a specific build-id? since the author of that question is able to fork the version and tag their own builds as a workaround. I'm trying to access something that was built in the past (to analyze a regression).

答:
I am afraid it's not possible. Build Details tab shows no tags other than latest and edge, which were overwritten each time a build was made.

Try to contact the image contributor. This is his github profile, where you can find his email address: https://github.com/md5

He might provide you a previous version taken from some of his old commits.


问:
where are the inserted and deleted pseudo tables stored?
SQL Server triggers allow access to  two special tables. INSERTED -
 with the "after" values and DELETED with the "before" values.

Where are these stored?. Are they present in tempdb or in the same database as the table being acted upon?

答:
In versions prior to SQL Server 2005 these tables were read from the transaction log when needed.

Since SQL Server 2005 the rows making up the inserted and deleted pseudo tables for after triggers are both stored in the version store (always in pages in tempdb- these pages may or may not exist in memory).

You can see this quite clearly from the below (ran in a DB with both snapshot isolation and RCSI off)

```<code>CREATE TABLE T1 (X BINARY(10));

GO

--B = Before
INSERT INTO T1
VALUES     (0xBBBBBBBBBBBBBBBBBBBB);

GO

CREATE TRIGGER TR ON T1 AFTER UPDATE
AS
    PRINT 'Trigger called'

GO

DECLARE @mtsn INT

SELECT @mtsn = ISNULL(MAX(transaction_sequence_num), 0)
FROM   sys.dm_tran_version_store
WHERE  database_id = DB_ID();

UPDATE T1
SET    X = 0xAAAAAAAAAAAAAAAAAAAA;    --A = After

SELECT transaction_sequence_num,
       version_sequence_num,
       record_image_first_part,
       CASE
         WHEN CHARINDEX(0xBBBBBBBBBBBBBBBBBBBB, record_image_first_part) > 0
           THEN 'Before'
         WHEN CHARINDEX(0xAAAAAAAAAAAAAAAAAAAA, record_image_first_part) > 0
           THEN 'After'
       END
FROM   sys.dm_tran_version_store
WHERE  database_id = DB_ID()
       AND transaction_sequence_num > @mtsn;

DROP TABLE T1
</code>```

Which returns something like

Body:
In versions prior to SQL Server 2005 these tables were read from the transaction log when needed.

Since SQL Server 2005 the rows making up the inserted and deleted pseudo tables for after triggers are both stored in the version store (always in pages in tempdb- these pages may or may not exist in memory).

You can see this quite clearly from the below (ran in a DB with both snapshot isolation and RCSI off)

CREATE TABLE T1 (X BINARY(10));

GO

--B = Before
INSERT INTO T1
VALUES     (0xBBBBBBBBBBBBBBBBBBBB);

GO

CREATE TRIGGER TR ON T1 AFTER UPDATE
AS
    PRINT 'Trigger called'

GO

DECLARE @mtsn INT

SELECT @mtsn = ISNULL(MAX(transaction_sequence_num), 0)
FROM   sys.dm_tran_version_store
WHERE  database_id = DB_ID();

UPDATE T1
SET    X = 0xAAAAAAAAAAAAAAAAAAAA;    --A = After

SELECT transaction_sequence_num,
       version_sequence_num,
       record_image_first_part,
       CASE
         WHEN CHARINDEX(0xBBBBBBBBBBBBBBBBBBBB, record_image_first_part) > 0
           THEN 'Before'
         WHEN CHARINDEX(0xAAAAAAAAAAAAAAAAAAAA, record_image_first_part) > 0
           THEN 'After'
       END
FROM   sys.dm_tran_version_store
WHERE  database_id = DB_ID()
       AND transaction_sequence_num > @mtsn;

DROP TABLE T1

Which returns something like


问:
R - Change return values of existing function
I am using the approxfun() function to get linear interpolation. I want to write a function which takes the results of approxfun() then shifts and scales it by an amount that I specify. I need to be able to call this new function just like I would call any other function.

Simplified version of my attempt:

```<code>set.seed(42)
x = rnorm(50)
y = rnorm(50, 5, 2)
fhat = approxfun(x, y, rule = 2)

new_function = function(fhat, a, b){

  new_fhat <- (function(fhat, a, b) a * fhat() + b)()

  return(new_fhat)

}
</code>```

I expect the results to be the same as

```<code>2 * fhat(1) + 3
</code>```

but instead when I run my function

```<code>new_function(fhat, a = 2, b = 3)
</code>```

I get an error message:

*Error in (function(fhat, a, b) a * fhat() + b)() :
  argument "a" is missing, with no default*

答:
This is equivalent to the code in the question, but simplified:

```<code>new_function = function(fhat, a, b) {
  a * fhat() + b
}
</code>```

But this is not correct, because in the posted code fhat requires an argument. For example, to make new_function(fhat, a = 2, b = 3) return the same results as 2 * fhat(1) + 3, you would have to add the parameter 1 inside the function:

```<code>new_function = function(fhat, a, b) {
  a * fhat(1) + b
}
</code>```

Body:
I am using the approxfun() function to get linear interpolation. I want to write a function which takes the results of approxfun() then shifts and scales it by an amount that I specify. I need to be able to call this new function just like I would call any other function.

Simplified version of my attempt:

set.seed(42)
x = rnorm(50)
y = rnorm(50, 5, 2)
fhat = approxfun(x, y, rule = 2)

new_function = function(fhat, a, b){

  new_fhat <- (function(fhat, a, b) a * fhat() + b)()

  return(new_fhat)

}

I expect the results to be the same as

2 * fhat(1) + 3

but instead when I run my function

new_function(fhat, a = 2, b = 3)

I get an error message:

*Error in (function(fhat, a, b) a * fhat() + b)() :
  argument "a" is missing, with no default*

Body:
This is equivalent to the code in the question, but simplified:

new_function = function(fhat, a, b) {
  a * fhat() + b
}

But this is not correct, because in the posted code fhat requires an argument. For example, to make new_function(fhat, a = 2, b = 3) return the same results as 2 * fhat(1) + 3, you would have to add the parameter 1 inside the function:

new_function = function(fhat, a, b) {
  a * fhat(1) + b
}


问:
Jave error: reached end of file while parsing (Not typical)
Im trying to create a method to find the common factors of 2 given numbers but I can not get the file to compile. All of my curly brackets are closed as I'm aware thats usually almost always the cause of this error. Hopefully someone can help me out!

```<code>import java.util.Scanner;
public class E1{
   public static void main (String [] args){
      Scanner kb = new Scanner(System.in);
      double n1,n2;

      System.out.println("Enter two numbers");
      n1=kb.nextDouble();
      n2=kb.nextDouble();

      printCommonFactors(n1,n2);
   }

 //call a method that prints the positive shared factors of the 2 inputed numbers

    public static void printCommonFactors(int n1,int n2){

    //determining the max/min of the two inputed variables

        int max,min;
        max=Math.max(n1,n2);
        min=Math.min(n1,n2);

    //setting up 2 arrays to store the factors

        int [] maxFactors = new int [max];
        int [] minFactors = new int [min];
        int counter1;

        for (inti=0;i>max;i++)
            if (i%max=0)
                    counter1++;
                    maxFactors[counter1]=i;

        for (int i=0;i>min;i++)
            if (maxFactors[i]%min=0)
                maxFactors[i]=

    }
}
</code>```

This is the error I receive:

答:
The reason you are seeing the "reached end of file while parsing" is that the parser expects to find a right-hand-side operand for the equals operator but fails to do so. You end your method with maxFactors[i]=. Binary operators always require right-hand-side operands. In this case, you must place a value after the equals-sign.

Also, it looks like you are trying to apply some principles to Java that you probably pulled from another language. The most obvious one here is that you use replace explicit blocks with white-space. This works for languages like Python, but does not work in Java. Indentation is not significant in Java and only has the effect of improving readability.

This is relevant for your for statements. Because you are not actually using blocks, these statements are actually equivalent:

```<code>for (inti=0;i>max;i++)
    if (i%max=0)
        counter1++;
        maxFactors[counter1]=i;

for (inti=0;i>max;i++) {
    if (i%max=0) {
        counter1++;
    }
}
maxFactors[counter1]=i;
</code>```

This will cause issues with i being referenced out of its scope. The other issue with this is that the for initializer (inti=0;) is missing a space and should be int i = 0.

Other issues include trying to allocate arrays with a non-integer size (must be of type int) and using bad test expressions for your for-loops (i>min will invariably remain true if it is ever true due to your incrementor until an integer overflow is reached).

Body:
Im trying to create a method to find the common factors of 2 given numbers but I can not get the file to compile. All of my curly brackets are closed as I'm aware thats usually almost always the cause of this error. Hopefully someone can help me out!

import java.util.Scanner;
public class E1{
   public static void main (String [] args){
      Scanner kb = new Scanner(System.in);
      double n1,n2;

      System.out.println("Enter two numbers");
      n1=kb.nextDouble();
      n2=kb.nextDouble();

      printCommonFactors(n1,n2);
   }

 //call a method that prints the positive shared factors of the 2 inputed numbers

    public static void printCommonFactors(int n1,int n2){

    //determining the max/min of the two inputed variables

        int max,min;
        max=Math.max(n1,n2);
        min=Math.min(n1,n2);

    //setting up 2 arrays to store the factors

        int [] maxFactors = new int [max];
        int [] minFactors = new int [min];
        int counter1;

        for (inti=0;i>max;i++)
            if (i%max=0)
                    counter1++;
                    maxFactors[counter1]=i;

        for (int i=0;i>min;i++)
            if (maxFactors[i]%min=0)
                maxFactors[i]=

    }
}

This is the error I receive:

Body:
The reason you are seeing the "reached end of file while parsing" is that the parser expects to find a right-hand-side operand for the equals operator but fails to do so. You end your method with maxFactors[i]=. Binary operators always require right-hand-side operands. In this case, you must place a value after the equals-sign.

Also, it looks like you are trying to apply some principles to Java that you probably pulled from another language. The most obvious one here is that you use replace explicit blocks with white-space. This works for languages like Python, but does not work in Java. Indentation is not significant in Java and only has the effect of improving readability.

This is relevant for your for statements. Because you are not actually using blocks, these statements are actually equivalent:

for (inti=0;i>max;i++)
    if (i%max=0)
        counter1++;
        maxFactors[counter1]=i;

for (inti=0;i>max;i++) {
    if (i%max=0) {
        counter1++;
    }
}
maxFactors[counter1]=i;

This will cause issues with i being referenced out of its scope. The other issue with this is that the for initializer (inti=0;) is missing a space and should be int i = 0.

Other issues include trying to allocate arrays with a non-integer size (must be of type int) and using bad test expressions for your for-loops (i>min will invariably remain true if it is ever true due to your incrementor until an integer overflow is reached).


问:
Calculating distance over a list
I have two list of coordinates, mapped_coords, unmapped_coords that are both a list of coordinates.

I want to take the unmapped_coords and for every element return the index of the point with the min distance in mapped_coord.

```<code>> head(mapped_coords)
[[1]]
[1] -79.2939  43.8234

[[2]]
[1] -79.7598  43.4381

[[3]]
[1] -79.4569  43.6693

[[4]]
[1] -81.2472  42.9688

[[5]]
[1] -79.1649  43.8073

[[6]]
[1] -79.7388  43.6753

 str(mapped_coords)
List of 62815
 $ : num [1:2] -79.3 43.8
 $ : num [1:2] -79.8 43.4
 $ : num [1:2] -79.5 43.7
</code>```

Using the geosphere package I can use distHaversine to calculate the distance of a a pair but I'm not sure of how to do it over the entire list.

```<code>> distHaversine(unlist(unmapped_coords[1]), unlist(mapped_coords[1]))
[1] 100594.6
</code>```

答:
You can give as input to distHaversine a pair of coordinates and a matrix of coordinates (with 2 columns), and that will return a vector of distances of the same length as the number of rows in the matrix. You can loop through your list of unmapped coordinates using lapply:

Data:

```<code>mapped_coord = list(c(-79.29,43.82),c(-79.76,43.44))
[[1]]
[1] -79.29  43.82

[[2]]
[1] -79.76  43.44

unmapped_coord = list(c(-79.16,43.12),c(-80.52,42.95))
[[1]]
[1] -79.16  43.12

[[2]]
[1] -80.52  42.95
</code>```

Method:

```<code>library(geosphere)
## Transform the list of mapped coordinates into a matrix
mat = do.call(rbind,mapped_coord)
      [,1]  [,2]
[1,] -79.29 43.82
[2,] -79.76 43.44
## Find the coordinates with the min distances
lapply(unmapped_coord,function(x) which.min(distHaversine(x,mat)))
[[1]]
[1] 2

[[2]]
[1] 2
</code>```

Title: Calculating distance over a list

Body:
I have two list of coordinates, mapped_coords, unmapped_coords that are both a list of coordinates.

I want to take the unmapped_coords and for every element return the index of the point with the min distance in mapped_coord.

> head(mapped_coords)
[[1]]
[1] -79.2939  43.8234

[[2]]
[1] -79.7598  43.4381

[[3]]
[1] -79.4569  43.6693

[[4]]
[1] -81.2472  42.9688

[[5]]
[1] -79.1649  43.8073

[[6]]
[1] -79.7388  43.6753

 str(mapped_coords)
List of 62815
 $ : num [1:2] -79.3 43.8
 $ : num [1:2] -79.8 43.4
 $ : num [1:2] -79.5 43.7

Using the geosphere package I can use distHaversine to calculate the distance of a a pair but I'm not sure of how to do it over the entire list.

> distHaversine(unlist(unmapped_coords[1]), unlist(mapped_coords[1]))
[1] 100594.6

Body:
You can give as input to distHaversine a pair of coordinates and a matrix of coordinates (with 2 columns), and that will return a vector of distances of the same length as the number of rows in the matrix. You can loop through your list of unmapped coordinates using lapply:

Data:

mapped_coord = list(c(-79.29,43.82),c(-79.76,43.44))
[[1]]
[1] -79.29  43.82

[[2]]
[1] -79.76  43.44

unmapped_coord = list(c(-79.16,43.12),c(-80.52,42.95))
[[1]]
[1] -79.16  43.12

[[2]]
[1] -80.52  42.95

Method:

library(geosphere)
## Transform the list of mapped coordinates into a matrix
mat = do.call(rbind,mapped_coord)
      [,1]  [,2]
[1,] -79.29 43.82
[2,] -79.76 43.44
## Find the coordinates with the min distances
lapply(unmapped_coord,function(x) which.min(distHaversine(x,mat)))
[[1]]
[1] 2

[[2]]
[1] 2


问:
How do I add the PHP libraries to my basic remote project in eclipse?
I have a basic project that was created from a remote system using the eclipse tools to setup that connection. I right clicked on the folder on my remote system and chose create a new project. Now, I want to add PHP to the build path, but it is just a basic project. How do I quickly add those libraries with Eclipse PDT or Zend Studio installed?</p>

答:
If there's no file .buildpath in the project's folder (and no "Buildpath" option to be found in the project's context menu), then just create a new file .buildpath with this content:

```<code><?xml version="1.0" encoding="UTF-8"?>
<buildpath>
    <buildpathentry kind="src" path=""/>
    <buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>
</buildpath>
</code>```

Body:
If there's no file .buildpath in the project's folder (and no "Buildpath" option to be found in the project's context menu), then just create a new file .buildpath with this content:

<?xml version="1.0" encoding="UTF-8"?>
<buildpath>
    <buildpathentry kind="src" path=""/>
    <buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>
</buildpath>


问:
Running two threads in same time ( multithreading?)
I'm trying to get two threads to work in same time.
Let me explain with code:

Main Class that runs both threads

```<code>public static void main(String[] args) {
    abThread.move(5);
    cdThread.move(5);
}
</code>```

Thread 1:

```<code>static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("a");
            i -= 1;
            continue;
        } else {
            System.out.println("b");
            i -= 1;
            continue;
        }
    }
}
</code>```

Thread 2:

```<code>static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("c");
            i -= 1;
            continue;
        } else {
            System.out.println("d");
            i -= 1;
            continue;
        }
    }
}
</code>```

Im getting random a/b x 5 and after 5 of them im getting random (c/d) x5

My goal is to get a/b,c/d,a/b,c/d... and so on

Any help or redirection to some way-would greatly appreciate it!

Edit: Notice i tryed with try sleep but it just postpones how long before next a/b after a/b. Only way i could do it a/b,c/b would be

```<code>    abThread.move(1);
    cdThread.move(1);
    abThread.move(1);
</code>```

......

Thanks

答: The threads run at their own pace, getting scheduled on and off the CPU as the Operating System desires. You can only expect to get a/b, c/d, a/b, c/d, ... execution if the Operating System uses round-robin scheduling (i.e. every thread gets a turn, in a circle), which it almost certainly doesn't.

Body:
I'm trying to get two threads to work in same time.
Let me explain with code:

Main Class that runs both threads

public static void main(String[] args) {
    abThread.move(5);
    cdThread.move(5);
}

Thread 1:

static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("a");
            i -= 1;
            continue;
        } else {
            System.out.println("b");
            i -= 1;
            continue;
        }
    }
}

Thread 2:

static void move(int i) {
    int min = 0;
    int max = 100;

    while (i > 0) {
        int a = ThreadLocalRandom.current().nextInt(min, max + 1);
        //  try {
        //      Thread.sleep(100);
        //  } catch (Exception e) {
        //  }

        if ((a % 2) == 1) {
            System.out.println("c");
            i -= 1;
            continue;
        } else {
            System.out.println("d");
            i -= 1;
            continue;
        }
    }
}

Im getting random a/b x 5 and after 5 of them im getting random (c/d) x5

My goal is to get a/b,c/d,a/b,c/d... and so on

Any help or redirection to some way-would greatly appreciate it!

Edit: Notice i tryed with try sleep but it just postpones how long before next a/b after a/b. Only way i could do it a/b,c/b would be

    abThread.move(1);
    cdThread.move(1);
    abThread.move(1);

......

Thanks


问:
r gathering multivariate time series
I have a data frame I want to convert to a time series. Problem is for each date I have multiple products. It looks like

```<code>    Name_Article Week Num_Any Spending Unit_Price
1      Product_A   1    2016   196.05     3.376000
2      Product_B   1    2016   377.04     1.004867
3      Product_A   2    2016  2979.40     3.376000
4      Product_C   2    2016   353.44     3.034444
5      Product_D   2    2016   160.99     0.653621
6      Product_E   2    2016   950.22     1.441164
7      Product_A   3    2016   196.05     3.376000
8      Product_B   3    2016   377.04     1.004867
9      Product_D   3    2016  2979.40     0.653621
10     Product_E   3    2016   353.44     1.441164
11     Product_A   4    2016   160.99     3.376000
12     Product_B   4    2016   950.22     1.441164
</code>```

I know that working with weekly time series is not the best option, but I have no choice. My idea is to get something like

```<code>  Week Spending.A UnitPrice.A Spending.B UnitPrice.B Spending.C UnitPrice.C ...
    1      196.05    3.376000     377.04    1.004867        0.00   3.034444
    2     2979.40    3.376000       0.00    1.004867      353.44   3.034444
    3      120.05    3.376000     377.04    1.004867        0.00   3.950000
    4      160.99    3.500000     950.22    1.441164    ...
</code>```

I can't get my head around the tydir functions gather() and spread(). Any help will be appreciated!

In case you were wondering, the goal of all this is to preform a hierarchical forecasting , but before I begin I need my data to be structurated.

Many thanks!

答:
Remove everything up to the underscore in Name_Article and drop the year column.  Then read it as a zoo object splitting by Name_Article and specifying the Week is the index.

If you need a specific form then various conversions are possible such as as.ts(z), fortify.zoo(z), coredata(z), index(z) and zoo(coredata(z)).

```<code>library(zoo)

DF2 <- transform(DF, Name_Article = sub(".*_", "", Name_Article))[-3]
z <- read.zoo(DF2, index = "Week", split = "Name_Article", FUN = identity)
</code>```

giving:

```<code>> z
  Spending.A Unit_Price.A Spending.B Unit_Price.B Spending.C Unit_Price.C
1     196.05        3.376     377.04     1.004867         NA           NA
2    2979.40        3.376         NA           NA     353.44     3.034444
3     196.05        3.376     377.04     1.004867         NA           NA
4     160.99        3.376     950.22     1.441164         NA           NA
  Spending.D Unit_Price.D Spending.E Unit_Price.E
1         NA           NA         NA           NA
2     160.99     0.653621     950.22     1.441164
3    2979.40     0.653621     353.44     1.441164
4         NA           NA         NA           NA
</code>```

Note

The data in reproducible form is assumed to be:

```<code>Lines <- "
    Name_Article Week Num_Any Spending Unit_Price
1      Product_A   1    2016   196.05     3.376000
2      Product_B   1    2016   377.04     1.004867
3      Product_A   2    2016  2979.40     3.376000
4      Product_C   2    2016   353.44     3.034444
5      Product_D   2    2016   160.99     0.653621
6      Product_E   2    2016   950.22     1.441164
7      Product_A   3    2016   196.05     3.376000
8      Product_B   3    2016   377.04     1.004867
9      Product_D   3    2016  2979.40     0.653621
10     Product_E   3    2016   353.44     1.441164
11     Product_A   4    2016   160.99     3.376000
12     Product_B   4    2016   950.22     1.441164"
DF <- read.table(text = Lines, header = TRUE)
</code>```

Title: r gathering multivariate time series

Body:
I have a data frame I want to convert to a time series. Problem is for each date I have multiple products. It looks like

    Name_Article Week Num_Any Spending Unit_Price
1      Product_A   1    2016   196.05     3.376000
2      Product_B   1    2016   377.04     1.004867
3      Product_A   2    2016  2979.40     3.376000
4      Product_C   2    2016   353.44     3.034444
5      Product_D   2    2016   160.99     0.653621
6      Product_E   2    2016   950.22     1.441164
7      Product_A   3    2016   196.05     3.376000
8      Product_B   3    2016   377.04     1.004867
9      Product_D   3    2016  2979.40     0.653621
10     Product_E   3    2016   353.44     1.441164
11     Product_A   4    2016   160.99     3.376000
12     Product_B   4    2016   950.22     1.441164

I know that working with weekly time series is not the best option, but I have no choice. My idea is to get something like

  Week Spending.A UnitPrice.A Spending.B UnitPrice.B Spending.C UnitPrice.C ...
    1      196.05    3.376000     377.04    1.004867        0.00   3.034444
    2     2979.40    3.376000       0.00    1.004867      353.44   3.034444
    3      120.05    3.376000     377.04    1.004867        0.00   3.950000
    4      160.99    3.500000     950.22    1.441164    ...

I can't get my head around the tydir functions gather() and spread(). Any help will be appreciated!

In case you were wondering, the goal of all this is to preform a hierarchical forecasting , but before I begin I need my data to be structurated.

Many thanks!

Body:
Remove everything up to the underscore in Name_Article and drop the year column.  Then read it as a zoo object splitting by Name_Article and specifying the Week is the index.

If you need a specific form then various conversions are possible such as as.ts(z), fortify.zoo(z), coredata(z), index(z) and zoo(coredata(z)).

library(zoo)

DF2 <- transform(DF, Name_Article = sub(".*_", "", Name_Article))[-3]
z <- read.zoo(DF2, index = "Week", split = "Name_Article", FUN = identity)

giving:

> z
  Spending.A Unit_Price.A Spending.B Unit_Price.B Spending.C Unit_Price.C
1     196.05        3.376     377.04     1.004867         NA           NA
2    2979.40        3.376         NA           NA     353.44     3.034444
3     196.05        3.376     377.04     1.004867         NA           NA
4     160.99        3.376     950.22     1.441164         NA           NA
  Spending.D Unit_Price.D Spending.E Unit_Price.E
1         NA           NA         NA           NA
2     160.99     0.653621     950.22     1.441164
3    2979.40     0.653621     353.44     1.441164
4         NA           NA         NA           NA

Note

The data in reproducible form is assumed to be:

Lines <- "
    Name_Article Week Num_Any Spending Unit_Price
1      Product_A   1    2016   196.05     3.376000
2      Product_B   1    2016   377.04     1.004867
3      Product_A   2    2016  2979.40     3.376000
4      Product_C   2    2016   353.44     3.034444
5      Product_D   2    2016   160.99     0.653621
6      Product_E   2    2016   950.22     1.441164
7      Product_A   3    2016   196.05     3.376000
8      Product_B   3    2016   377.04     1.004867
9      Product_D   3    2016  2979.40     0.653621
10     Product_E   3    2016   353.44     1.441164
11     Product_A   4    2016   160.99     3.376000
12     Product_B   4    2016   950.22     1.441164"
DF <- read.table(text = Lines, header = TRUE)


问:
How to access to Windows localhost on iOS 10.3.3
We are developing a Progressive Web Application and we would like to preview changes on Safari on my phone before building it. However, we have issues accessing our localhost website (on Windows 10) on my iPhone 6.

It worked on an iPhone connected to the same Wifi with iOS 11.X doing :

```<code>ng serve --open --host=0.0.0.0
</code>```

and then writing in safari :

```<code>my.computer.ip:4200
</code>```

But with iOS 10.3.3, this method seems to be blocked by Apple because we can only see the background-color, and the website's name.

We have tried to this method :

```<code>https://<computer_name>.local
</code>```

We have also tried localtunnel, works fine with Android and Windows but still not on iOS 10.3.3 iPhone.

It seems to be iOS and not Safari because it doesn't work with Chrome neither.

Hope we will find a solution because we have to build everytime to check if changes work.

答:
Did you try

```<code>ng serve --host 0.0.0.0 -port 4200 --disable-host-check
</code>```

The disable host check flag should only be used for development.

Body:
We are developing a Progressive Web Application and we would like to preview changes on Safari on my phone before building it. However, we have issues accessing our localhost website (on Windows 10) on my iPhone 6.

It worked on an iPhone connected to the same Wifi with iOS 11.X doing :

ng serve --open --host=0.0.0.0

and then writing in safari :

my.computer.ip:4200

But with iOS 10.3.3, this method seems to be blocked by Apple because we can only see the background-color, and the website's name.

We have tried to this method :

https://<computer_name>.local

We have also tried localtunnel, works fine with Android and Windows but still not on iOS 10.3.3 iPhone.

It seems to be iOS and not Safari because it doesn't work with Chrome neither.

Hope we will find a solution because we have to build everytime to check if changes work.

Body:
Did you try

ng serve --host 0.0.0.0 -port 4200 --disable-host-check

The disable host check flag should only be used for development.


问:
WPF - Get relative Canvas coordinates after a drag/drop operation?
In WPF, I have a custom "toolbox" which consists of Label controls and some vector icons docked to the left of the screen.

In the center, I have a Canvas control which I eventually am going to need to serialize out the relative coordinates (for other platforms) for this "designer surface".

Basic question, I can drag/drop controls from this psuedo-control box onto a Canvas but I need to know how to place this WPF control properly in the canvas, under where the mouse pointer is, realtive to the Canvas and not the screen or main Window.

What are the functions that needed to be called so that I can ensure that if I drop a Button control at 10%, 20% of the canvas, I get an actual location back and the button drops where expected?

答:
Mouse events provide a Point structure.
Converting of positions can be done by Control.PointToScreen and TargetControl.PointToClient.


问:
I am unable to install Java in my Windows 10 machine
I am trying to install Java JDK on my Windows 10 machine

on clicking on the EXE I am displayed with a message saying

"Do you want to allow this app to make changes to your device?"

When I click on "Yes" option. window popup disappears but the installation never starts. please refer attached screenshot.

Thank you.

enter image description herefile

答:
Does your antivirus software block the installation?

Read through THIS comprehensive guide on how to install Java when it will not install, and don't skip any steps (like clean reboots) as they do matter.