问:
How can I compute simple addition on multiple .xyz files?
I am currently trying to write a Python program that will take 2 existing .xyz files (containing 3 columns of values separated by spaces), loop through them, add numbers from equivalent positions in each column of the list, then write those values to a separate .txt file in the same position.

For example, if I have the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 1 1 1
(atom symbol) 2 2 2
(atom symbol) 3 3 3
```

<p>and the list:</p>

<pre class="lang-none prettyprint-override"><code>(line denoting number of atoms)
(comment line)
(atom symbol) 3 3 3
(atom symbol) 2 2 2
(atom symbol) 1 1 1
</code>```

I want to make python create a new file in the form:

(line denoting number of atoms)
(comment line)
(atom symbol) 4 4 4
(atom symbol) 4 4 4
(atom symbol) 4 4 4
```

<p>Currently my is giving me the error:</p>

<pre class="lang-none prettyprint-override"><code>TypeError: float() argument must be a string or a number
</code>```

and my code is:

```<code>def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
        for line1 in myfile_1.readlines():
            parts1 = line1.split('\n')
        for line2 in myfile_2.readlines():
            parts2 = line2.split('\n')

    with open(outfile, 'w') as outputfile:
        totalenergy = float(parts1) + float(parts2)

    print("The output was printed to:", outfile)

sumen()
</code>```

答:
Your looping algorithm is wrong. What you want is to parse file1 and file2 line by line, and work on one line of each file at a time before moving to the next line.

I suggest you rewrite it like this:

```<code>with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2, open(outfile, 'w') as myfile_3:
    f3 = []
    for (line1, line2) in zip(myfile_1.readlines(), myfile_2.readlines()):
        values1 = line1.split()[1:]
        values2 = line2.split()[1:]
        f3.append(' '.join([str(float(x) + float(y)) for x, y in zip(values1, values2)])+'\n')
        pass
    myfile_3.writelines(f3)
</code>```

Body:
I am currently trying to write a Python program that will take 2 existing .xyz files (containing 3 columns of values separated by spaces), loop through them, add numbers from equivalent positions in each column of the list, then write those values to a separate .txt file in the same position.

For example, if I have the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 1 1 1
(atom symbol) 2 2 2
(atom symbol) 3 3 3

and the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 3 3 3
(atom symbol) 2 2 2
(atom symbol) 1 1 1

I want to make python create a new file in the form:

(line denoting number of atoms)
(comment line)
(atom symbol) 4 4 4
(atom symbol) 4 4 4
(atom symbol) 4 4 4

Currently my is giving me the error:

TypeError: float() argument must be a string or a number

and my code is:

def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
        for line1 in myfile_1.readlines():
            parts1 = line1.split('\n')
        for line2 in myfile_2.readlines():
            parts2 = line2.split('\n')

    with open(outfile, 'w') as outputfile:
        totalenergy = float(parts1) + float(parts2)

    print("The output was printed to:", outfile)

sumen()

Body:
Your looping algorithm is wrong. What you want is to parse file1 and file2 line by line, and work on one line of each file at a time before moving to the next line.

I suggest you rewrite it like this:

with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2, open(outfile, 'w') as myfile_3:
    f3 = []
    for (line1, line2) in zip(myfile_1.readlines(), myfile_2.readlines()):
        values1 = line1.split()[1:]
        values2 = line2.split()[1:]
        f3.append(' '.join([str(float(x) + float(y)) for x, y in zip(values1, values2)])+'\n')
        pass
    myfile_3.writelines(f3)


来源: stackexchange

问:
How to make intellij to omit lombok annotations
I am using lombok annotations (@Getter,@Setter). I use Auto format in Intellij (automatic after every commit). The problem is that it always stack them. So from this:

```<code>@Getter @Setter
@OneToMany(mappedBy = "objectName", cascade = CascadeType.ALL)
@Fetch(FetchMode.SUBSELECT)
@OrderBy(Object.NAME)
private Set<Object> exmaple = new HashSet<>();
</code>```

I get this:

```<code>@Getter
@Setter
@OneToMany(mappedBy = "objectName", cascade = CascadeType.ALL)
@Fetch(FetchMode.SUBSELECT)
@OrderBy(Object.NAME)
private Set<Object> exmaple = new HashSet<>();
</code>```

If I change in Settings->Editor->Java->Wrapping and braces->Annotation parameters to wrap always by definition it wraps everything. If check Align when multiline nothing changes.

Is it possible to make intellij auto-format mechanism to ignore certain (f.e. lombok) annotations ? or any other way to make auto-format put them next to each other instead stack them ?

答: Go Setting → Editor → Code Style → Java → Wrapping and Braces tab and try to change Field annotations to 'Do not wrap'

ContentLicense: CC BY-SA 3.0

Body:
I am using lombok annotations (@Getter,@Setter). I use Auto format in Intellij (automatic after every commit). The problem is that it always stack them. So from this:

@Getter @Setter
@OneToMany(mappedBy = "objectName", cascade = CascadeType.ALL)
@Fetch(FetchMode.SUBSELECT)
@OrderBy(Object.NAME)
private Set<Object> exmaple = new HashSet<>();

I get this:

@Getter
@Setter
@OneToMany(mappedBy = "objectName", cascade = CascadeType.ALL)
@Fetch(FetchMode.SUBSELECT)
@OrderBy(Object.NAME)
private Set<Object> exmaple = new HashSet<>();

If I change in Settings->Editor->Java->Wrapping and braces->Annotation parameters to wrap always by definition it wraps everything. If check Align when multiline nothing changes.

Is it possible to make intellij auto-format mechanism to ignore certain (f.e. lombok) annotations ? or any other way to make auto-format put them next to each other instead stack them ?


问:
RestTemplate and acessing json
I have seen the responses from many other posts but would like to understand if there is a better way to do the same thing.

Requirement:-
I am using restTemplate to talk to web service which returns JSON output which is dynamic. As a consumer I don't want to access all fields but is interested in few of them. I am using Spring framework with Jackson parser and found the way of accessing it

```<code>     String  response = restTemplate.getForObject(targetUrl, String.class);
     System.out.println(response);
     ObjectMapper mapper = new ObjectMapper();
     JsonNode rootNode = mapper.readValue(response, JsonNode.class);
     JsonNode uri = rootNode.get("uri");
     System.out.println(uri.asText());
</code>```

Do you know any better way to do it? Mapping to java Object is something that I dont want to do as the json output is not in my control

答:
If your RestTemplate is configured with the default HttpMessageConverters, which is provided by Jackson2ObjectMapperBuilder, you may directly get a JsonNode from restTemplate.getForObject.

For example,

```<code>ArrayNode resources = restTemplate.getForObject("/resources", ArrayNode.class);
</code>```

Or,

```<code>ObjectNode resource = restTemplate.getForObject("/resources/123", ObjectNode.class);
</code>```

Note that ArrayNode and ObjectNode are sub-classes of JsonNode.

Title: RestTemplate and acessing json

Body:
I have seen the responses from many other posts but would like to understand if there is a better way to do the same thing.

Requirement:-
I am using restTemplate to talk to web service which returns JSON output which is dynamic. As a consumer I don't want to access all fields but is interested in few of them. I am using Spring framework with Jackson parser and found the way of accessing it

     String  response = restTemplate.getForObject(targetUrl, String.class);
     System.out.println(response);
     ObjectMapper mapper = new ObjectMapper();
     JsonNode rootNode = mapper.readValue(response, JsonNode.class);
     JsonNode uri = rootNode.get("uri");
     System.out.println(uri.asText());

Do you know any better way to do it? Mapping to java Object is something that I dont want to do as the json output is not in my control

Body:
If your RestTemplate is configured with the default HttpMessageConverters, which is provided by Jackson2ObjectMapperBuilder, you may directly get a JsonNode from restTemplate.getForObject.

For example,

ArrayNode resources = restTemplate.getForObject("/resources", ArrayNode.class);

Or,

ObjectNode resource = restTemplate.getForObject("/resources/123", ObjectNode.class);

Note that ArrayNode and ObjectNode are sub-classes of JsonNode.


问:
How can I access a delphi control from outside the form's unit?
I'm trying to call the Enabled property of a Timer from a procedure defined like this: procedure Slide(Form: TForm; Show: Boolean); and not with a fixed form name (like: Form2.Timer...)

After putting the form's unit in the uses list, this works: Form2.Timer1.Enabled := True;
but the following is not working: Form.Timer1.Enabled := True; (where Form is the form passed as parameter to the procedure.

How to get access to the Timer component on my form?

Thanks in advance.

答:
A simple (and OOP) way to implement this is to use interfaces.

Declare an interface ISlideable which defines a SlideTimer property (with getter and setter methods) and then write the Slide method like

```<code>Slide(const Target: ISlideable; Show: Boolean);
</code>```

And every form which should be passed says that it is Slideable

```<code>MyFormN = class(TForm, ISlideable)
...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
A simple (and OOP) way to implement this is to use interfaces.

Declare an interface ISlideable which defines a SlideTimer property (with getter and setter methods) and then write the Slide method like

Slide(const Target: ISlideable; Show: Boolean);

And every form which should be passed says that it is Slideable

MyFormN = class(TForm, ISlideable)
...


问:
Display unique array entries and sum of related entry from separate array
I'm trying to take two arrays that are related, filter one to retrieve the unique values and the other needs to have the sums for the unique values. The indexes for Array 1 match the index for Array 2 that I need to add all the values together to get the sum. For example:

Array 1:

```<code>var arr1 = [7012, 7013, 7015, 7012];
</code>```

Array 2:

```<code>var arr2 = [10, 20, 25, 10];
</code>```

Expected Output:

(first explanation was not great, changing this)

```<code>newArray1 = [7012, 7013, 7015];
newArray2 = [20, 20, 25];
</code>```

Note: I am using Firebase to retrieve the values into the arrays, these are not going to be set indexes.

I'm using Set() to retrieve the unique values:

```<code>var newArr = [...new Set(arr1)];
</code>```

which works perfectly fine.

The trouble I'm having is getting the related values from Array 2 and making a sum. I can create the sum fine by using .reduce() but I'm having trouble figuring out how to get the Array 2 values into a new array based on what they're related to in Array 1.

答:
If I understand correctly you want an array that will include the respective sums from array2 for the unique values of array1. Using a Map we can get the unique values, and the corresponding sums. You can then use Map#values to get the sums of array2, Map#keys to get the unique values of array1, and map#entries to get tuples of unique value and sum.

const arr1 = [7012, 7013, 7015, 7012];
const arr2 = [10, 20, 25, 10];

const map = arr1.reduce((map, v, i) => {
  const sum = map.get(v) || 0;

  return map.set(v, sum + arr2[i]);
}, new Map());

const arr1Unique = [...map.keys()];
const arr2Sums = [...map.values()];
const tuples = [...map.entries()];

console.log(arr1Unique);
console.log(arr2Sums);
console.log(tuples);```

Body:
I'm trying to take two arrays that are related, filter one to retrieve the unique values and the other needs to have the sums for the unique values. The indexes for Array 1 match the index for Array 2 that I need to add all the values together to get the sum. For example:

Array 1:

var arr1 = [7012, 7013, 7015, 7012];

Array 2:

var arr2 = [10, 20, 25, 10];

Expected Output:

(first explanation was not great, changing this)

newArray1 = [7012, 7013, 7015];
newArray2 = [20, 20, 25];

Note: I am using Firebase to retrieve the values into the arrays, these are not going to be set indexes.

I'm using Set() to retrieve the unique values:

var newArr = [...new Set(arr1)];

which works perfectly fine.

The trouble I'm having is getting the related values from Array 2 and making a sum. I can create the sum fine by using .reduce() but I'm having trouble figuring out how to get the Array 2 values into a new array based on what they're related to in Array 1.


问:
Access listbox - Search for more than one field
I have a listbox on a form that searches for different records.
I need to modify the after update event macro so that the Where Condition matches 2 fields in the same record. In this case both the work order and the part number.

```<code>WO  | PN
----|-----
123 | red
123 | green
123 | blue
456 | red
456 | yellow
</code>```

The default access code is:

```<code>="[workOrder] = " & "'" & [Screen].[ActiveControl] & "'"
</code>```

so right now it matches only the first column (work order).

I want to modify this listbox to search for both [workOrder] and another text field called [partNumber].

I've tried:

```<code>="[workOrder] = " & "'" & [Screen].[ActiveControl].[Column](0) & "'" AND "[partNumber] = " & "'" & [Screen].[ActiveControl].[Column](1) & "'"
</code>```

but it doesn't work. Found this but it doesn't work either.

edited to add details:

The main form: see how the work order matches the selection on the left but the part number doesn't.

The macro in the after update event of the listbox with the default code created by the access wizard. (CercaRecord = FindRecord)

答:
Not sure where you use the expression you are building, but the AND must be part of the string.

```<code>="[workOrder] = '" & [Screen].[ActiveControl].[Column](0) & "' AND [partNumber] = '" & [Screen].[ActiveControl].[Column](1) & "'"
</code>```

If workOrder is a number column, remove the '' around the first part.

Note how the syntax coloring is showing what is part of the string and what is not.

Body:
I have a listbox on a form that searches for different records.
I need to modify the after update event macro so that the Where Condition matches 2 fields in the same record. In this case both the work order and the part number.

WO  | PN
----|-----
123 | red
123 | green
123 | blue
456 | red
456 | yellow

The default access code is:

="[workOrder] = " & "'" & [Screen].[ActiveControl] & "'"

so right now it matches only the first column (work order).

I want to modify this listbox to search for both [workOrder] and another text field called [partNumber].

I've tried:

="[workOrder] = " & "'" & [Screen].[ActiveControl].[Column](0) & "'" AND "[partNumber] = " & "'" & [Screen].[ActiveControl].[Column](1) & "'"

but it doesn't work. Found this but it doesn't work either.

edited to add details:

The main form: see how the work order matches the selection on the left but the part number doesn't.

The macro in the after update event of the listbox with the default code created by the access wizard. (CercaRecord = FindRecord)

Body:
Not sure where you use the expression you are building, but the AND must be part of the string.

="[workOrder] = '" & [Screen].[ActiveControl].[Column](0) & "' AND [partNumber] = '" & [Screen].[ActiveControl].[Column](1) & "'"

If workOrder is a number column, remove the '' around the first part.

Note how the syntax coloring is showing what is part of the string and what is not.


问:
Promise chain not executing in expected order - nodejs
I have a chain of 4 promises, and 1 function at the end. The final function is executing before the previous promises in the chain have resolved.

Can someone explain to me why this might be happening?

Here is the promise chain:

updateGdax(db)
  .then(updateBitstamp(db))
  .then(updateBitfinex(db))
  .then(updatePoloniex(db))
  .then(coinMarketData.updateCoinMarketData(db))
  .then(addRates(db)); //this function is executing after the first promise in the chain.```

I would like each function to execute after the one listed before it, so addRates(db) should be executed last.

I can post the code from the promise functions if needed for further analyses, but I really just want to understand WHY this would happen, as my understanding is that functions in a promise chain won't execute unless the previous promise in the chain has resolved.

答:
Unless those update functions in the then calls are partially applied (unless they return a function), they are being executed before the then is called. You need to wrap them in an anonymous function to have them executed in order. Do what the other answer says or use fat arrows:

```<code>updateGdax(db)
  .then(()=>updateBitstamp(db))
  .then(()=>updateBitfinex(db))
  .then(()=>updatePoloniex(db))
  .then(()=>coinMarketData.updateCoinMarketData(db))
  .then(()=>addRates(db));
</code>```

If your update functions could be rewritten to return the db after completing, then you could rewrite the calls like so, point free style:

```<code>updateGdax(db)
  .then(updateBitstamp)
  .then(updateBitfinex)
  .then(updatePoloniex)
  .then(coinMarketData.updateCoinMarketData)
  .then(addRates);
</code>```

Each function, would then look something like this:

```<code>function updateGdax(db) {
   return db.doSomething().then(()=> db)
}
</code>```

Follow that pattern, and you have yourself some nice looking javascript.

Body:
I have a chain of 4 promises, and 1 function at the end. The final function is executing before the previous promises in the chain have resolved.

Can someone explain to me why this might be happening?

Here is the promise chain:

updateGdax(db)
  .then(updateBitstamp(db))
  .then(updateBitfinex(db))
  .then(updatePoloniex(db))
  .then(coinMarketData.updateCoinMarketData(db))
  .then(addRates(db)); //this function is executing after the first promise in the chain.

I would like each function to execute after the one listed before it, so addRates(db) should be executed last.

I can post the code from the promise functions if needed for further analyses, but I really just want to understand WHY this would happen, as my understanding is that functions in a promise chain won't execute unless the previous promise in the chain has resolved.

Body:
Unless those update functions in the then calls are partially applied (unless they return a function), they are being executed before the then is called. You need to wrap them in an anonymous function to have them executed in order. Do what the other answer says or use fat arrows:

updateGdax(db)
  .then(()=>updateBitstamp(db))
  .then(()=>updateBitfinex(db))
  .then(()=>updatePoloniex(db))
  .then(()=>coinMarketData.updateCoinMarketData(db))
  .then(()=>addRates(db));

If your update functions could be rewritten to return the db after completing, then you could rewrite the calls like so, point free style:

updateGdax(db)
  .then(updateBitstamp)
  .then(updateBitfinex)
  .then(updatePoloniex)
  .then(coinMarketData.updateCoinMarketData)
  .then(addRates);

Each function, would then look something like this:

function updateGdax(db) {
   return db.doSomething().then(()=> db)
}

Follow that pattern, and you have yourself some nice looking javascript.


问:
How does gmail signature work?
This is pretty much a curiosity question.

Yesterday I created a new signature for Gmail, using HTML.

The code was pretty basic (tables and inline CSS) but then when it came to the point to actually add it to Gmail, the code was not rendering and it was printed as words instead.

After a bit of googling, I realized that to be able to display HTML content on Gmail signature, I have to copy the result from a web page and then paste it into the textbox so that it would work, and actually...it does.

Now, I just wonder why this?

I mean, why copying the result from web page works while pasting the HTML code itself doesn't?

Thanks

答:
Gmail uses a rich text editor that has its own code that runs when you paste into it.  Most people don't use HTML and so Google hasn't implemented the ability to write HTML into it.  They do this to prevent problems with people adding symbols like < > and & into their signatures that would cause issues if parsed as HTML.

If you put the HTML into a website first and then copy it, you are actually copying and pasting the output of the HTML rather than the actual code.  Google is set up to handle pasting formatted content which is why this approach works differently.

Title: How does gmail signature work?


问:
Default value for fields
I have problem accessing fields from an object in a python script I did. Basically it boils down to this little piece of code:

```<code>from enum import Enum

class AbstractFoo:
    def __init__(self, foo='works', bar='nope'):
        self.foo = foo
        self.bar = bar

class Foo(Enum):
    test = AbstractFoo('bla', 'tada')
</code>```

So when in the python console I try to access an element of my enum with:

```<code>Foo.test.foo
</code>```

I would expect it to print me 'bla' which is the value I pass to the constructor (or at least it should print 'works' which would be the default value I've assigned).

What I actually get is

```<code>AttributeError: 'Foo' object has no attribute 'foo'
</code>```

you can probably tell by now that I'm pretty new to python and especially the concept objects in python (I mostly write code in Java which might lead to some missconceptions from my part about the behaviour of objects in python).

What I figured out though is that I can do:

```<code>Foo.test.foo = 'whatever'
</code>```

and assign a value to foo in this way. But when doing this I can also assign a value to a field I haven't even specified in the constructor such as:

```<code>Foo.test.noField = 'shouldn't even exist'
</code>```

and it will work just as fine which I don't understand at all.

I would be really glad about some clarification how objects work in python and/or how I could realize an enum of a class in python.

EDIT: Apparently the code behaves the way I want it to if I remove the inheritance from Enum.

答:
That can be quite confusing, since you are literally saying that test is something and then it is not anymore. That is because Enum is a special kind of class that takes all of its members and "converts" them into instance of the class. So the type of test is not AbstractFoo anymore, but instead Foo. However, you can get back the original value assigned to the enum instance with the value property:

```<code>from enum import Enum

class AbstractFoo:
    def __init__(self, foo='works', bar='nope'):
        self.foo = foo
        self.bar = bar

class Foo(Enum):
    test = AbstractFoo('bla', 'tada')

print(Foo.test.value.foo)

>>> bla
</code>```

Title: Default value for fields

Body:
I have problem accessing fields from an object in a python script I did. Basically it boils down to this little piece of code:

from enum import Enum

class AbstractFoo:
    def __init__(self, foo='works', bar='nope'):
        self.foo = foo
        self.bar = bar

class Foo(Enum):
    test = AbstractFoo('bla', 'tada')

So when in the python console I try to access an element of my enum with:

Foo.test.foo

I would expect it to print me 'bla' which is the value I pass to the constructor (or at least it should print 'works' which would be the default value I've assigned).

What I actually get is

AttributeError: 'Foo' object has no attribute 'foo'

you can probably tell by now that I'm pretty new to python and especially the concept objects in python (I mostly write code in Java which might lead to some missconceptions from my part about the behaviour of objects in python).

What I figured out though is that I can do:

Foo.test.foo = 'whatever'

and assign a value to foo in this way. But when doing this I can also assign a value to a field I haven't even specified in the constructor such as:

Foo.test.noField = 'shouldn't even exist'

and it will work just as fine which I don't understand at all.

I would be really glad about some clarification how objects work in python and/or how I could realize an enum of a class in python.

EDIT: Apparently the code behaves the way I want it to if I remove the inheritance from Enum.

Body:
That can be quite confusing, since you are literally saying that test is something and then it is not anymore. That is because Enum is a special kind of class that takes all of its members and "converts" them into instance of the class. So the type of test is not AbstractFoo anymore, but instead Foo. However, you can get back the original value assigned to the enum instance with the value property:

from enum import Enum

class AbstractFoo:
    def __init__(self, foo='works', bar='nope'):
        self.foo = foo
        self.bar = bar

class Foo(Enum):
    test = AbstractFoo('bla', 'tada')

print(Foo.test.value.foo)

>>> bla


问:
The breakpoint will not currently be hit. No symbols have been loaded
I am struggling with breakPoint issue in VS 2012 for more than hours. I am from eclipse background, there I never heard about such issues.

Problem :

The breakpoint will not currently be hit. No symbols have been loaded
for this document.

I have placed the break point in click action of Jquery.

I found the issue using the IE script debugging., The file loaded was old file., i.e I have modified a lot, but I can see no changes in the one which is loaded in IE. How to fix the bug

What I have Tried :

I know this question is duplicate, but being a newbie to VS and C#., I could not understand the older answers.  For example, in this answer, he told to choose Debug -> Windows -> Modules. But I doesn't have Modules under windows in VS 2012. Also even though I read, I could not understand the explanation.

Also I am quite new to term Assemblies and PDB. Though, I located PDB files as he said. But how to open the .pdb file?

Need :
Could anyone explain me the same answer in easier term (with more explanation).

答: Try deleting all breakpoints and restarting debugging in Visual Studio.</p>


问:
Is there an easy way to create a database diagram in SQL Server
I'm not sure if I have worded this question properly I will explain what I am trying to acheieve further.

I am looking to create a graphical representation of an existing database showing table relationships Key relationships etc.

I have seen posts around the internet that suggest you can just go; New > Database Diagram. But I have seen nothing to this effect in Management Studio

Something similar to this:

答: If there is an database diagram drawn for the database it should be visible if you collapse DataBase Diagrams under your database. If you are trying to create one that is the way to go about it create new database diagram.</p>


问:
window pip install scrapy error "running build_ext error: [Error 5]"
How can I avoid this error?</p>

```<code>    running build_ext
    error: [Error 5]

    ----------------------------------------
Command "C:\Python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\
\users\\admini~1\\appdata\\local\\temp\\pip-build-zc67ii\\Twisted\\setup.py';f=g
etattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.c
lose();exec(compile(code, __file__, 'exec'))" install --record c:\users\admini~1
\appdata\local\temp\pip-pxb6xl-record\install-record.txt --single-version-extern
ally-managed --compile" failed with error code 1 in c:\users\admini~1\appdata\lo
cal\temp\pip-build-zc67ii\Twisted\

C:\Users\Administrator>
</code>```

答:
Installing Scrapy on Windows can be a real struggle.

That's why the  scrapy documentation recommands to use Anaconda for the scrapy installation. I think you should give it a try if you are working on Windows.

First you need to install Anaconda following this tutorial.

Then you just need to run this command conda install -c conda-forge scrapy
 and you are good to go.

Body:
How can I avoid this error?

    running build_ext
    error: [Error 5]

    ----------------------------------------
Command "C:\Python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\
\users\\admini~1\\appdata\\local\\temp\\pip-build-zc67ii\\Twisted\\setup.py';f=g
etattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.c
lose();exec(compile(code, __file__, 'exec'))" install --record c:\users\admini~1
\appdata\local\temp\pip-pxb6xl-record\install-record.txt --single-version-extern
ally-managed --compile" failed with error code 1 in c:\users\admini~1\appdata\lo
cal\temp\pip-build-zc67ii\Twisted\

C:\Users\Administrator>


问:
how to set smooth scrolling offset when it is reached width <480 px
```<code>$(document).ready(function () {
    $("a.smooth-scroll").click(function (event) {
        event.preventDefault();
        var section = $(this).attr("href"); //get or return section id #about etc

        var section = $(this).attr("href");
        $("html,body").animate({
            scrollTop: $(section).offset().top - 64
        }, 1250, "easeInOutExpo");
    });

});
</code>```

This the code for smooth scrolling. It is working correctly in desktop screen but when it comes to mobile devices   i need to set the offset().top-64 to offset().top-50.How to do that? I tried using resize function but is not working.

答:
Just try to check the current window size, and set the value of 50 or 64 according to width you got.</p>

```<code>$(document).ready(function () {
$("a.smooth-scroll").click(function (event) {
    event.preventDefault();
    var section = $(this).attr("href"); //get or return section id #about etc

    var section = $(this).attr("href");
    var value = ($(window).width() < 480) ? 50 : 64);
    $("html,body").animate({
        scrollTop: $(section).offset().top - value
    }, 1250, "easeInOutExpo");
});
</code>```

Body:
$(document).ready(function () {
    $("a.smooth-scroll").click(function (event) {
        event.preventDefault();
        var section = $(this).attr("href"); //get or return section id #about etc

        var section = $(this).attr("href");
        $("html,body").animate({
            scrollTop: $(section).offset().top - 64
        }, 1250, "easeInOutExpo");
    });

});

This the code for smooth scrolling. It is working correctly in desktop screen but when it comes to mobile devices   i need to set the offset().top-64 to offset().top-50.How to do that? I tried using resize function but is not working.

Body:
Just try to check the current window size, and set the value of 50 or 64 according to width you got.

$(document).ready(function () {
$("a.smooth-scroll").click(function (event) {
    event.preventDefault();
    var section = $(this).attr("href"); //get or return section id #about etc

    var section = $(this).attr("href");
    var value = ($(window).width() < 480) ? 50 : 64);
    $("html,body").animate({
        scrollTop: $(section).offset().top - value
    }, 1250, "easeInOutExpo");
});


问:
Clear Interval issue for a nested setInterval
I'm trying to clearInterval an interval that is already set.
My first setInterval object has a piece of code that does something every 12 seconds, also within the same function, there is another setInterval object that does something every 1 second within this 12 sec timeframe.

So the problem here is, I can do clearInterval for the main (outer) setInterval object, but nothing happens to the inner.

Please refer to the Code snippet.

```<code>start.addEventListener("click", function() {

    interval = setInterval(function() {

        Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

        interval1 = setInterval(startTimer, 1000);

    }, 12000);

});

stop.addEventListener("click", function() {
    clearInterval(interval);
    clearInterval(interval1);
});
</code>```

So, I tried to clear interval the inner setInterval object first and then outer later, still no luck and nothing happens.

Any quick solutions, suggestions are really appreciated as I can't proceed any further with this issue on the way.

Thanks in advance.

答:
You should move the interval and interval1 variable declaration to a higher scope, so all functions can reach their values.

```<code>var interval;
var interval1;

start.addEventListener("click", function() {

    interval = setInterval(function() {

        Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

        interval1 = setInterval(startTimer, 1000);

    }, 12000);

});

stop.addEventListener("click", function() {
    clearInterval(interval);
    clearInterval(interval1);
});
</code>```

Body:
I'm trying to clearInterval an interval that is already set.
My first setInterval object has a piece of code that does something every 12 seconds, also within the same function, there is another setInterval object that does something every 1 second within this 12 sec timeframe.

So the problem here is, I can do clearInterval for the main (outer) setInterval object, but nothing happens to the inner.

Please refer to the Code snippet.

start.addEventListener("click", function() {

    interval = setInterval(function() {

        Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

        interval1 = setInterval(startTimer, 1000);

    }, 12000);

});

stop.addEventListener("click", function() {
    clearInterval(interval);
    clearInterval(interval1);
});

So, I tried to clear interval the inner setInterval object first and then outer later, still no luck and nothing happens.

Any quick solutions, suggestions are really appreciated as I can't proceed any further with this issue on the way.

Thanks in advance.

Body:
You should move the interval and interval1 variable declaration to a higher scope, so all functions can reach their values.

var interval;
var interval1;

start.addEventListener("click", function() {

    interval = setInterval(function() {

        Object.assign(h1.style, { color: selectedColor, borderbottom: '4px solid ' + selectedColor });

        interval1 = setInterval(startTimer, 1000);

    }, 12000);

});

stop.addEventListener("click", function() {
    clearInterval(interval);
    clearInterval(interval1);
});


问:
How can I query MongoDB based on Carbon dates?
Here's a snippet of code that I would expect would return one result:

```<code>    $today = new Carbon();
    $newUser = new User();
    $newUser->yesterday = $today->subDay();
    $newUser->save();

    $matches = User::where('yesterday', '<', $today)->get();

    return $matches;
</code>```

And yet I get an empty array. Can someone help me identify the problem here?

I do believe it has to do with the way that I'm saving the yesterday property. If it were an ISODate, this query would work properly. Maybe I'm missing something obvious in converting Carbon objects to ISODates...

Any help appreciated.

答:
I would recommend using the dates property on the appropriate laravel model (which works extremely well with carbon)

```<code>class User extends Model
{
    protected $dates = ['yesterday'];

    public function yourfunction(){

    }
}
</code>```

The laravel docs has a good guide on how to use the dates property here

Body:
Here's a snippet of code that I would expect would return one result:

    $today = new Carbon();
    $newUser = new User();
    $newUser->yesterday = $today->subDay();
    $newUser->save();

    $matches = User::where('yesterday', '<', $today)->get();

    return $matches;

And yet I get an empty array. Can someone help me identify the problem here?

I do believe it has to do with the way that I'm saving the yesterday property. If it were an ISODate, this query would work properly. Maybe I'm missing something obvious in converting Carbon objects to ISODates...

Any help appreciated.

Body:
I would recommend using the dates property on the appropriate laravel model (which works extremely well with carbon)

class User extends Model
{
    protected $dates = ['yesterday'];

    public function yourfunction(){

    }
}

The laravel docs has a good guide on how to use the dates property here


问:
How OrderBy afterwards HasMany and BelongsTo Relationships
I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.

```<code>Models: Review
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
    }
Models: Giochi
    public function review()
    {
            return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
    }
    public function infogiochi()
    {
            return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
    }
Models: InfoGiochi
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
    }
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();
</code>```

Here is a screenshot of my json:

How do I order content for review table IDs?

答:
You can modify your relationship query when you fire it:</p>

```<code>Giochi::with([
     'Review' => function ($query) { return $query->orderBy('id','DESC'); },
     'InfoGiochi'
])->orderBy('id','DESC');
</code>```

Body:
I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.

Models: Review
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
    }
Models: Giochi
    public function review()
    {
            return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
    }
    public function infogiochi()
    {
            return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
    }
Models: InfoGiochi
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
    }
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();

Here is a screenshot of my json:

How do I order content for review table IDs?

Body:
You can modify your relationship query when you fire it:

Giochi::with([
     'Review' => function ($query) { return $query->orderBy('id','DESC'); },
     'InfoGiochi'
])->orderBy('id','DESC');


问:
Hover for single line
I have a fiddle. The fiddle has 2 text (Read More) in a single line. I am wondering, how can I change the Read More text to:
"Read" = Bold

 "More"=Italic  on hover?.

At this moment, without hover it is "Read" = regular  "More"=bold italic

I do know that for hovering an element, the code should be like this:

```<code>p:hover {
  /* Write code here*/
}
</code>```

But I am not sure how to apply the same hover to the above fiddle.

READ MORE
```

答:
Add the :hover event to the parent class and then set a different style to each sub-class.

.readmore:hover .bold {
  font-weight: bold;
}

.readmore:hover .italic {
  font-style: italic;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="readmore"><span class="bold">READ</span> <span class="italic">MORE</span></p></code>```

Title: Hover for single line

Body:
I have a fiddle. The fiddle has 2 text (Read More) in a single line. I am wondering, how can I change the Read More text to:
"Read" = Bold

 "More"=Italic  on hover?.

At this moment, without hover it is "Read" = regular  "More"=bold italic

I do know that for hovering an element, the code should be like this:

p:hover {
  /* Write code here*/
}

But I am not sure how to apply the same hover to the above fiddle.

READ MORE

Body:
Add the :hover event to the parent class and then set a different style to each sub-class.

.readmore:hover .bold {
  font-weight: bold;
}

.readmore:hover .italic {
  font-style: italic;
}

<p class="readmore"><span class="bold">READ</span> <span class="italic">MORE</span></p>


问:
Calling a service on input change and update view
I'm writing a simple component which takes as input an Id and calls a service method to return an entity to display:

```<code>@Input() id: string;

ngOnInit(): void {
    if (this.id != undefined && this.id != "") {
        this.detailSubscription=this.service.load(this.id)
            .subscribe(result => {

                    this.detail$ = result;
                    this.cd.detectChanges();
            });
    }
}

ngOnDestroy() {
   this.cd.detach();
   this.detailSubscription.unsubscribe();
}
</code>```

This componet works only the first time. If input Id changes it doesen't update the view.

I also tried to put service call inside onChanges method, but it won't works due to unsubscribe that is called only once on onDestroy method.

How to achieve this?

答:
Using a getter/setter approach you can easily intercept the direct change of the id input property. For example:</p>

```<code>private _id:string;
@Input('id')
set id(value:string){
   this._id = value;
   this.fetch();
}

get id(){
   return this._id;
}

 fetch(){
 if (this.id !== "") {
        this.detailSubscription=this.service.load(this.id)
            .subscribe(result => {

                this.detail$ = result;
        });
 }

}

ngOnDestroy() {
   this.detailSubscription.unsubscribe();
}
</code>```

Body:
I'm writing a simple component which takes as input an Id and calls a service method to return an entity to display:

@Input() id: string;

ngOnInit(): void {
    if (this.id != undefined && this.id != "") {
        this.detailSubscription=this.service.load(this.id)
            .subscribe(result => {

                    this.detail$ = result;
                    this.cd.detectChanges();
            });
    }
}

ngOnDestroy() {
   this.cd.detach();
   this.detailSubscription.unsubscribe();
}

This componet works only the first time. If input Id changes it doesen't update the view.

I also tried to put service call inside onChanges method, but it won't works due to unsubscribe that is called only once on onDestroy method.

How to achieve this?

Body:
Using a getter/setter approach you can easily intercept the direct change of the id input property. For example:

private _id:string;
@Input('id')
set id(value:string){
   this._id = value;
   this.fetch();
}

get id(){
   return this._id;
}

 fetch(){
 if (this.id !== "") {
        this.detailSubscription=this.service.load(this.id)
            .subscribe(result => {

                this.detail$ = result;
        });
 }

}

ngOnDestroy() {
   this.detailSubscription.unsubscribe();
}


问:
embed swf with action script 3 in flex
I'm very new in flash and flex and my first task is to be able to embed an SWF made in adobe cs4 using actionscript 3... the problem is I'm not able to embed it in Flex, it is weird though that if for example i add a sound to the swf file to be embedded in flash i'm able to hear the sound but it is not showing up (not visible) in the flex generated swf file

One other thing is if i try to set the flash swf to be embedded to use actionscript 2 then it gets shown in the flex generated swf but if i really need to be able to use actionscript 3 so no use for that

答:
What is your code for embedding it ?

I suggest you to take a look at SWFLoader. Here is some code and samples:

http://livedocs.adobe.com/flex/3/html/help.html?content=controls_15.html

Title: embed swf with action script 3 in flex


问:
vkCreateSwapchainKHR fails with VK_ERROR_OUT_OF_DEVICE_MEMORY
I am attempting to create a swapchain after successfully creating an instance, surface, and device. However, vkCreateSwapchainKHR is failing with VK_ERROR_OUT_OF_DEVICE_MEMORY.

What does this mean and what are the possible causes?

Device info:

Device Name: GeForce GTX 970

Driver Version: 1602764800

Vulkan API Version: 4194346

API dump:
https://pastebin.com/pXebGX5t

EDIT: I think it may be related to pNext having a value here. It is set to NULL in my code so something deeper might be happening like a problem with my binding...

```<code>vkCreateDevice(physicalDevice, pCreateInfo, pAllocator, pDevice) returns VkResult VK_SUCCESS (0):
    physicalDevice:                 VkPhysicalDevice = 0000000004D768D0
    pCreateInfo:                    const VkDeviceCreateInfo* = 000000000022EAD0:
        sType:                          VkStructureType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO (3)
        pNext:                          const void* = 000000000022EB20
        flags:                          VkDeviceCreateFlags = 0
</code>```

答:
Based on the dump your swapchain requested format is a depth format (VK_FORMAT_D24_UNORM_S8_UINT).

That is highly suspicious.

Also something the validation layers probably check (there should be supported vs requested format check). So do yourself a favor and enable them.

Body:
I am attempting to create a swapchain after successfully creating an instance, surface, and device. However, vkCreateSwapchainKHR is failing with VK_ERROR_OUT_OF_DEVICE_MEMORY.

What does this mean and what are the possible causes?

Device info:

Device Name: GeForce GTX 970

Driver Version: 1602764800

Vulkan API Version: 4194346

API dump:
https://pastebin.com/pXebGX5t

EDIT: I think it may be related to pNext having a value here. It is set to NULL in my code so something deeper might be happening like a problem with my binding...

vkCreateDevice(physicalDevice, pCreateInfo, pAllocator, pDevice) returns VkResult VK_SUCCESS (0):
    physicalDevice:                 VkPhysicalDevice = 0000000004D768D0
    pCreateInfo:                    const VkDeviceCreateInfo* = 000000000022EAD0:
        sType:                          VkStructureType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO (3)
        pNext:                          const void* = 000000000022EB20
        flags:                          VkDeviceCreateFlags = 0


问:
Grep in screen not saving output to logfile
I am trying to perform a very long grep scan trough my files. Because Screen will close after execution, I am trying to write to a log file to save the output of grep. The following command appeared:

```<code> screen fgrep "needle" /mnt/Volume_volume/haystack/* >> /mnt/Volume_volume/log.txt
</code>```

Unfortunately the log file is empty. What went wrong? Does the output of screen get saved instead of grep? How do I fix this?

答:
The command you wrote means: run screen fgrep "needle" /mnt/Volume_volume/haystack/* and append the result of this command to file /mnt/Volume_volume/log.txt. And screen displays noting on its output, so that's what you are getting in the log file.

If you really want to use screen, the proper command would be something like this:

```<code>screen bash -c 'fgrep "needle" /mnt/Volume_volume/haystack/* >> /mnt/Volume_volume/log.txt'
</code>```

but I suspect simple:

```<code>nohup fgrep "needle" /mnt/Volume_volume/haystack/* >> /mnt/Volume_volume/log.txt &
</code>```

would work for you too.

Body:
I am trying to perform a very long grep scan trough my files. Because Screen will close after execution, I am trying to write to a log file to save the output of grep. The following command appeared:

 screen fgrep "needle" /mnt/Volume_volume/haystack/* >> /mnt/Volume_volume/log.txt

Unfortunately the log file is empty. What went wrong? Does the output of screen get saved instead of grep? How do I fix this?

Body:
The command you wrote means: run screen fgrep "needle" /mnt/Volume_volume/haystack/* and append the result of this command to file /mnt/Volume_volume/log.txt. And screen displays noting on its output, so that's what you are getting in the log file.

If you really want to use screen, the proper command would be something like this:

screen bash -c 'fgrep "needle" /mnt/Volume_volume/haystack/* >> /mnt/Volume_volume/log.txt'

but I suspect simple:

nohup fgrep "needle" /mnt/Volume_volume/haystack/* >> /mnt/Volume_volume/log.txt &

would work for you too.


问:
Calculating an average temperature using Python and weather API
I am trying to calculate an average 10-day temperature by finding the average daily temperature between high and low, and then dividing the average in total time frame by 10. I am using the weather APi, running on the command line with a postcode. Currently I have invalid syntax errors but can't figure out what's wrong- perhaps I am missing a bracket or using an incorrect one.
Error is: print city ['city']
        ^
SyntaxError: invalid syntax

Any help would be appreciated.

```<code>from weather import Weather
import sys

if len(sys.argv) > 1:
    weather = Weather ()
    location = weather.lookup_by_location((sys.argv[1]))
    forecast = location.forecast()
    city = location.location()

    average = 0

for f in location.forecast():
    averageTotal = f(f[int('high')] + f[int('low')] / 2

   print city ['city']
   print "10 day average temperature:" + str(averageTotal / 10)

else:
    print "You must supply a postcode to get the atmospheric pressure."
</code>```

答:
Welcome to python! Your code can be fixed via static code analyzers like pylint. Try to use it. Also the average that you are calculating for a 10 day period was overwriting itself when you assign a new value to averageTotal in the for loop. Here's a better way of writing it.

```<code>import sys
from weather import Weather

if len(sys.argv) > 1:
    weather = Weather()
    location = weather.lookup_by_location((sys.argv[1]))
    forecast = location.forecast()
    city = location.location()
    average = 0

print city['city']
averageTotal = 0
for f in location.forecast():
    averageTotal += (int(f['high']) + int(f['low']))

print "10 day average temperature:" + str(averageTotal / 10)
</code>```

P.S. Don't use for-else if you are new to python. It will just confuse you. If you would like to read what it does then please refer to this.

Body:
I am trying to calculate an average 10-day temperature by finding the average daily temperature between high and low, and then dividing the average in total time frame by 10. I am using the weather APi, running on the command line with a postcode. Currently I have invalid syntax errors but can't figure out what's wrong- perhaps I am missing a bracket or using an incorrect one.
Error is: print city ['city']
        ^
SyntaxError: invalid syntax

Any help would be appreciated.

from weather import Weather
import sys

if len(sys.argv) > 1:
    weather = Weather ()
    location = weather.lookup_by_location((sys.argv[1]))
    forecast = location.forecast()
    city = location.location()

    average = 0

for f in location.forecast():
    averageTotal = f(f[int('high')] + f[int('low')] / 2

   print city ['city']
   print "10 day average temperature:" + str(averageTotal / 10)

else:
    print "You must supply a postcode to get the atmospheric pressure."

Body:
Welcome to python! Your code can be fixed via static code analyzers like pylint. Try to use it. Also the average that you are calculating for a 10 day period was overwriting itself when you assign a new value to averageTotal in the for loop. Here's a better way of writing it.

import sys
from weather import Weather

if len(sys.argv) > 1:
    weather = Weather()
    location = weather.lookup_by_location((sys.argv[1]))
    forecast = location.forecast()
    city = location.location()
    average = 0

print city['city']
averageTotal = 0
for f in location.forecast():
    averageTotal += (int(f['high']) + int(f['low']))

print "10 day average temperature:" + str(averageTotal / 10)

P.S. Don't use for-else if you are new to python. It will just confuse you. If you would like to read what it does then please refer to this.


问:
Closing the web browser not a tab which was opened
I have a requirement to close the complete browser windows instead of closing a particular tab which I have opened.

I am able to close the tab which I have opened using javascript, but need to close the complete window.

答: It is not possible to close the entire browser via JavaScript</p>


问:
How to properly work with RxJS Observables when they needed as sync data
Hopefully topic is more or less understandable.

I'm quite new to RxJS and Redux world. I'm working on Angular 2+ app with Observables and NgRX store.

In store I have different parts. Here what I need is to get properties from one slice and pass it to downloadService which accept Array of custom AssetFile objects with different properties.

```<code>  constructor(
    private store: Store<AppState>,
    private downloadService: DownloadService) {
    this.selectedAssets$=this.store.select('selectedAssets')
    this.selectedAssets$.subscribe(asset => this.assetsSelected = asset)
   }
</code>```

Not sure if I did that part properly. In the UI once one Asset selected it dispatched to Store.selectedAssets. Here I assign it to this.selectedAssets$ and make another variable this.assetsSelected which suppose to be an Array of those selected objects.

Then I have this function to "prepare" files for download. Each Asset has property assetFiles which type is File[] in the end I need just Array of those files.

```<code>  prepareFilesToDownload(){
      let files = []
      let preparedFiles = this.assetsSelected.map(asset => {
      asset.assetFiles.map(file=>{
        files.push(file)
      })
    })
    return files
  }
</code>```

This code works, but I believe it's not proper way of doing things like this. I've just lost a bit.

Probably I can achieve this result with less code and directly from this Observable this.selectedAssets$=this.store.select('selectedAssets')

UPDATE:

```<code>constructor(
    private store: Store<AppState>,
    private downloadService: DownloadService) {
    this.selectedAssets$=this.store.select('selectedAssets')
   }
</code>```

Here I used flatten method from Ramda to combine array of array to single array.

```<code>  prepareFilesToDownload(){
    let files
    this.selectedAssets$.subscribe(
      assets => {
        files = R.flatten(assets.map(asset =>  asset.assetFiles.map(file => file)))
      }
    ).unsubscribe();
    return files
  }
</code>```

Looks a bit better, but still not sure if it's proper way to work with Observables or not. I think better will be just return this array straight from this.selectedAssets$ observable using RxJS operators. But can't find right way to do so.

One side question. Is it right to .subscribe and .unsubscribe as in second example or maybe I can use .take(1) instead?

答:
I think your second option is much better and you were on the spot regarding removing the local variable and the subscribe. If I get it properly, once the user select "download" (or do some action with the files), you use the get files and the processing. In this case why not trigger the entire chain in one place?

```<code>this.selectedAssets$
  .map(this.prepareFiles)
  .do(this.downloadFiles) // or process files
  .take(1)
  .subscribe(); // you must do this to make the observable hot
</code>```

This also relates to the unsubscribe. Not sure it works, and even if it does, it is less readable and standard than the take(1).

Body:
Hopefully topic is more or less understandable.

I'm quite new to RxJS and Redux world. I'm working on Angular 2+ app with Observables and NgRX store.

In store I have different parts. Here what I need is to get properties from one slice and pass it to downloadService which accept Array of custom AssetFile objects with different properties.

  constructor(
    private store: Store<AppState>,
    private downloadService: DownloadService) {
    this.selectedAssets$=this.store.select('selectedAssets')
    this.selectedAssets$.subscribe(asset => this.assetsSelected = asset)
   }

Not sure if I did that part properly. In the UI once one Asset selected it dispatched to Store.selectedAssets. Here I assign it to this.selectedAssets$ and make another variable this.assetsSelected which suppose to be an Array of those selected objects.

Then I have this function to "prepare" files for download. Each Asset has property assetFiles which type is File[] in the end I need just Array of those files.

  prepareFilesToDownload(){
      let files = []
      let preparedFiles = this.assetsSelected.map(asset => {
      asset.assetFiles.map(file=>{
        files.push(file)
      })
    })
    return files
  }

This code works, but I believe it's not proper way of doing things like this. I've just lost a bit.

Probably I can achieve this result with less code and directly from this Observable this.selectedAssets$=this.store.select('selectedAssets')

UPDATE:

constructor(
    private store: Store<AppState>,
    private downloadService: DownloadService) {
    this.selectedAssets$=this.store.select('selectedAssets')
   }

Here I used flatten method from Ramda to combine array of array to single array.

  prepareFilesToDownload(){
    let files
    this.selectedAssets$.subscribe(
      assets => {
        files = R.flatten(assets.map(asset =>  asset.assetFiles.map(file => file)))
      }
    ).unsubscribe();
    return files
  }

Looks a bit better, but still not sure if it's proper way to work with Observables or not. I think better will be just return this array straight from this.selectedAssets$ observable using RxJS operators. But can't find right way to do so.

One side question. Is it right to .subscribe and .unsubscribe as in second example or maybe I can use .take(1) instead?

Body:
I think your second option is much better and you were on the spot regarding removing the local variable and the subscribe. If I get it properly, once the user select "download" (or do some action with the files), you use the get files and the processing. In this case why not trigger the entire chain in one place?

this.selectedAssets$
  .map(this.prepareFiles)
  .do(this.downloadFiles) // or process files
  .take(1)
  .subscribe(); // you must do this to make the observable hot

This also relates to the unsubscribe. Not sure it works, and even if it does, it is less readable and standard than the take(1).


问:
R: Efficiently filter numeric vector by selecting multiple subregions
I have a relatively large numeric vector x, and I'm only interested in values that are found within n subregions specified by lower and upper bounds (inclusive). What is the most efficient (most important), and concise (less important as long as code is readable) method of accomplishing this? I need the output to be a vector of logical (or integer) values so that I can index another vector with the selected regions.

Let's say I have the following data:

```<code>x <- 1:20
lower <- c(0.8, 3.9,  9, 12, 19)
upper <- c(2.1, 6.1, 13, 17, 19)
</code>```

The output should be:

```<code>out <- c(TRUE,  TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE,
         TRUE,  TRUE, TRUE,  TRUE, TRUE, TRUE, TRUE,  FALSE, TRUE, FALSE)
</code>```

I have a solution but it seems a bit hacky to me and I have no idea if it's efficient:

```<code>library(dplyr)
library(purrr)

out.list <- map2(lower, upper, ~ between(x, .x, .y))
out.mat <- do.call(rbind, out.list)
out.vec <- apply(out.mat, 2, any)

# Check output
all(out.vec == out)
[1] TRUE
</code>```

Although x is not expected to be much larger than a million elements, I will need to repeat the process for many different values of x.

Edit: Updated example with floating point and overlapping bounds.

Update: I think this question is more concise and general than the linked one. I would have selected the deleted data.table answer instead of the selected answer in the linked question (which had a preference for dplyr/tidyr).

```<code>library(data.table)
library(microbenchmark)

lower <- runif(100, 0.5, 8.5)
upper <- runif(100, 0, 1)
x <- runif(1e5, 1, 10)

microbenchmark(inrange = inrange(x, lower, upper),
               sapply = sapply(x,function(v){ any(v >= lower & v <= upper) }))

   expr        min         lq       mean    median         uq      max neval
inrange   5.757293   5.991459   6.527294   6.10907   6.417622  10.0425   100
 sapply 280.412724 290.914073 300.813885 295.15648 300.568322 356.7478   100
</code>```

答:
What about this ?</p>

```<code>out <- sapply(x,function(v){ any(v >= lower & v <= upper) })

> out
[1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE
[12]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE
</code>```

Body:
I have a relatively large numeric vector x, and I'm only interested in values that are found within n subregions specified by lower and upper bounds (inclusive). What is the most efficient (most important), and concise (less important as long as code is readable) method of accomplishing this? I need the output to be a vector of logical (or integer) values so that I can index another vector with the selected regions.

Let's say I have the following data:

x <- 1:20
lower <- c(0.8, 3.9,  9, 12, 19)
upper <- c(2.1, 6.1, 13, 17, 19)

The output should be:

out <- c(TRUE,  TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE,
         TRUE,  TRUE, TRUE,  TRUE, TRUE, TRUE, TRUE,  FALSE, TRUE, FALSE)

I have a solution but it seems a bit hacky to me and I have no idea if it's efficient:

library(dplyr)
library(purrr)

out.list <- map2(lower, upper, ~ between(x, .x, .y))
out.mat <- do.call(rbind, out.list)
out.vec <- apply(out.mat, 2, any)

# Check output
all(out.vec == out)
[1] TRUE

Although x is not expected to be much larger than a million elements, I will need to repeat the process for many different values of x.

Edit: Updated example with floating point and overlapping bounds.

Update: I think this question is more concise and general than the linked one. I would have selected the deleted data.table answer instead of the selected answer in the linked question (which had a preference for dplyr/tidyr).

library(data.table)
library(microbenchmark)

lower <- runif(100, 0.5, 8.5)
upper <- runif(100, 0, 1)
x <- runif(1e5, 1, 10)

microbenchmark(inrange = inrange(x, lower, upper),
               sapply = sapply(x,function(v){ any(v >= lower & v <= upper) }))

   expr        min         lq       mean    median         uq      max neval
inrange   5.757293   5.991459   6.527294   6.10907   6.417622  10.0425   100
 sapply 280.412724 290.914073 300.813885 295.15648 300.568322 356.7478   100

Body:
What about this ?

out <- sapply(x,function(v){ any(v >= lower & v <= upper) })

> out
[1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE
[12]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE


问:
How to handle multiple configurations using chef
I have a web objects application that runs on multiple ports (around 20 ports) on each host.

For each port there is a different set of start up parameters ( eg different java_opts for each port. So each host will have 20 sets of  "port - java_opts" combination ).

In my production environment, I have 40 such hosts.

I have written a chef cookbook to deploy this app but i am unable to figure out how to handle different java_opts for each port across all these hosts.

1.How can I handle this in chef.
2. I also want to have the ability to handle these java_opts dynamically. ie during a situation, I should be able to pass a different set of java_opts to a host.

答: Have you looked into attributes in Chef? Assuming your nodes are connected to Chef server, you should be able to create an attribute "Java_ops port" for each host with a value of the desired ports. Another option is to use data bags, but I think your situation is better suited for attributes. </p>


问:
Access multiple versions of a package in Java
We have several applications that use Apache HTTPClient 3 to make HTTP requests. Recently we have also began creating web service clients that use HTTPClient 4 for various reasons. The Apache stance is that "major releases are not backwards compatible". While I would love to update all of our projects to use version 4, that's simply not feasible.

So, while my main question is rather general, my particular question is. How can I use HTTPClient version 3 and 4 in the same application? In our case an application can be a web, desktop, or command line app.

I have read the SO question for java-dynamically-load-multiple-versions-of-same-class which seems semi close but I don't care so much about the dynamic part. In fact I would like the JARs to be shipped with the app (example, WEB-INF/lib for web apps) I also see OSGi mentioned a lot in questions similar to this one but it seems to be overkill or perhaps overly complex (maybe a simple example could prove otherwise).

In the end I want to be able to hand a team a set of jars that they can drop in and it just works independent of their project using HTTP Client 3.

答:
An easy but straightforward solution would be you get the sources for HttpClient3 and HttpClient4, and refactor the package names to something like

org.apache.commons.httpclient3 for HttpClient3 and org.apache.commons.httpclient4 for HttpClient4 to avoid collision. Then compile, package, done.

Now it is easy to switch between the two implementations and they don't collide in the classloader.


答:
You can wrap each word in a span tag and use nth-child to target them on hover:

.readmore:hover span:nth-child(2){
  font-style: italic;
}
.readmore:hover span:nth-child(1){
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="readmore"><span>READ</span> <span>MORE</span></p></code>```

https://jsfiddle.net/vmxj2pLs/2/

Title: Hover for single line

Body:
You can wrap each word in a span tag and use nth-child to target them on hover:

.readmore:hover span:nth-child(2){
  font-style: italic;
}
.readmore:hover span:nth-child(1){
  font-weight: bold;
}

<p class="readmore"><span>READ</span> <span>MORE</span></p>

https://jsfiddle.net/vmxj2pLs/2/


问:
ERROR - error from worker No such file or directory: 'filepath'
I have a sample data set present in my local and I'm trying to do some basic opertaions on a cluster.

```<code>    import dask.dataframe as ddf
    from dask.distributed import Client
    client = Client('Ip address of the scheduler')
    import dask.dataframe as ddf
    csvdata = ddf.read_csv('Path to the CSV file')
</code>```

Client is connected to a scheduler which in turn is connected to two workers(on other machines).

My Questions may be pretty trivial.

Should this csv file be present on other worker nodes?

I seem to get file not found errors.

Using,

```<code>futures=client.scatter(csvdata)
x = ddf.from_delayed([future], meta=df)
#Price is a column in the data
df.Price.sum().compute(get=client.get) #returns" dd.Scalar<series-..., dtype=float64>" How do I access it?
client.submit(sum, x.Price)  #returns "distributed.utils - ERROR - 6dc5a9f58c30954f77913aa43c792cc8"
</code>```

Also, I did refer this
Loading local file from client onto dask distributed cluster and http://distributed.readthedocs.io/en/latest/manage-computation.html

I thinking I'm mixing up a lot of things here and my understanding is muddled up.
Any help would be really appreciated.

答:
Yes, here dask.dataframe is assuming that the files you refer to in your client code are also accessible by your workers.  If this is not the case then you will have you read in your data explicitly in your local machine and scatter it out to your workers.

It looks like you're trying to do exactly this, except that you're scattering dask dataframes rather than pandas dataframes.  You will actually have to concretely load pandas data from disk before you scatter it.  If your data fits in memory then you should be able to do exactly what you're doing now, but replace the dd.read_csv call with pd.read_csv

```<code>csvdata = pandas.read_csv('Path to the CSV file')
[future] = client.scatter([csvdata])
x = ddf.from_delayed([future], meta=df).repartition(npartitions=10).persist()
#Price is a column in the data
df.Price.sum().compute(get=client.get)  # Should return an integer
</code>```

If your data is too large then you might consider using dask locally to read and scatter data to your cluster piece by piece.

```<code>import dask.dataframe as dd
ddf = dd.read_csv('filename')
futures = ddf.map_partitions(lambda part: c.scatter([part])[0]).compute(get=dask.get)  # single threaded local scheduler

ddf = dd.from_delayed(list(futures), meta=ddf.meta)
</code>```

Body:
I have a sample data set present in my local and I'm trying to do some basic opertaions on a cluster.

    import dask.dataframe as ddf
    from dask.distributed import Client
    client = Client('Ip address of the scheduler')
    import dask.dataframe as ddf
    csvdata = ddf.read_csv('Path to the CSV file')

Client is connected to a scheduler which in turn is connected to two workers(on other machines).

My Questions may be pretty trivial.

Should this csv file be present on other worker nodes?

I seem to get file not found errors.

Using,

futures=client.scatter(csvdata)
x = ddf.from_delayed([future], meta=df)
#Price is a column in the data
df.Price.sum().compute(get=client.get) #returns" dd.Scalar<series-..., dtype=float64>" How do I access it?
client.submit(sum, x.Price)  #returns "distributed.utils - ERROR - 6dc5a9f58c30954f77913aa43c792cc8"

Also, I did refer this
Loading local file from client onto dask distributed cluster and http://distributed.readthedocs.io/en/latest/manage-computation.html

I thinking I'm mixing up a lot of things here and my understanding is muddled up.
Any help would be really appreciated.

Body:
Yes, here dask.dataframe is assuming that the files you refer to in your client code are also accessible by your workers.  If this is not the case then you will have you read in your data explicitly in your local machine and scatter it out to your workers.

It looks like you're trying to do exactly this, except that you're scattering dask dataframes rather than pandas dataframes.  You will actually have to concretely load pandas data from disk before you scatter it.  If your data fits in memory then you should be able to do exactly what you're doing now, but replace the dd.read_csv call with pd.read_csv

csvdata = pandas.read_csv('Path to the CSV file')
[future] = client.scatter([csvdata])
x = ddf.from_delayed([future], meta=df).repartition(npartitions=10).persist()
#Price is a column in the data
df.Price.sum().compute(get=client.get)  # Should return an integer

If your data is too large then you might consider using dask locally to read and scatter data to your cluster piece by piece.

import dask.dataframe as dd
ddf = dd.read_csv('filename')
futures = ddf.map_partitions(lambda part: c.scatter([part])[0]).compute(get=dask.get)  # single threaded local scheduler

ddf = dd.from_delayed(list(futures), meta=ddf.meta)


问:
How to call one controller's function from another controller
I was wondering if is it possible to call one controller's function from another controller. This way i tried but failed:

```<code><div ng-app="MyApp">
    <div ng-controller="Ctrl1">
        <button ng-click="func1()">func1</button>
    </div>
    <br>
    <div ng-controller="Ctrl2">
        <button ng-click="func2()">func2</button>
    </div>
</div>
</code>```

```<code>var app = angular.module('MyApp', []);

app.controller('Ctrl1', function($scope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $scope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    $scope.$emit("MyFunction");
  }

});
</code>```

when func2 is calling then i used $scope.$emit("MyFunction"); to call Ctrl1 MyFunction but it does not worked. so is it not possible ?

please put some light here.

答:
As you asked here for a solution using a service, here is an example.

I created 2 controllers (FirstCtrl, SecondCtrl) that use a single service (Data).

Note that the function alertName() is defined on the service, and each controller can use it because the service is injected in each controller.

var myApp = angular.module('myApp', []);

myApp.service('Data', function() {
  var name = 'Mistalis';
  return {
    alertName: function() {
      alert(name);
    }
  };
});

myApp.controller('FirstCtrl', function($scope, Data) {
  $scope.showName = function() {
    Data.alertName();
  }
});

myApp.controller('SecondCtrl', function($scope, Data) {
  $scope.showName = function() {
    Data.alertName();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="FirstCtrl">
    Controller 1<br/>
    <button ng-click="showName()">Show name from service</button>
  </div>
  <hr>
  <div ng-controller="SecondCtrl">
    Controller 2<br/>
    <button ng-click="showName()">Show name from service</button>
  </div>
</div></code>```

Body:
I was wondering if is it possible to call one controller's function from another controller. This way i tried but failed:

        <button ng-click="func1()">func1</button>

        <button ng-click="func2()">func2</button>

var app = angular.module('MyApp', []);

app.controller('Ctrl1', function($scope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $scope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    $scope.$emit("MyFunction");
  }

});

when func2 is calling then i used $scope.$emit("MyFunction"); to call Ctrl1 MyFunction but it does not worked. so is it not possible ?

please put some light here.

Body:
As you asked here for a solution using a service, here is an example.

I created 2 controllers (FirstCtrl, SecondCtrl) that use a single service (Data).

Note that the function alertName() is defined on the service, and each controller can use it because the service is injected in each controller.

var myApp = angular.module('myApp', []);

myApp.service('Data', function() {
  var name = 'Mistalis';
  return {
    alertName: function() {
      alert(name);
    }
  };
});

myApp.controller('FirstCtrl', function($scope, Data) {
  $scope.showName = function() {
    Data.alertName();
  }
});

myApp.controller('SecondCtrl', function($scope, Data) {
  $scope.showName = function() {
    Data.alertName();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="FirstCtrl">
    Controller 1<br/>
    <button ng-click="showName()">Show name from service</button>
  </div>
  <hr>
  <div ng-controller="SecondCtrl">
    Controller 2<br/>
    <button ng-click="showName()">Show name from service</button>
  </div>
</div>


问:
PHP Include Function Efficiency
If I use PHP's include function to import parts of the page that are repeated like navigation, header and footer for example - will that make the code more or less efficient or would it be the same?
Thanks</p>

答: The include()-function reads the entire content of the file you are including, then execute it and then paste the result right where it is called. So regarding code speed, it would be less efficient. However, if you don't include extremely large files then it shouldn't make much of a difference.

Title: PHP Include Function Efficiency


问:
What is the best way to get up to speed on BizTalk?
How should an experienced .NET & SQL developer go about becoming a BizTalk expert for a project starting in 1 month? How should I spend my limited time to gain some practical skill & knowledge in BizTalk so I can "walk the talk"?

I am self employed, and would not be willing to spend more than USD300. I have the book "Professional BizTalk Server 2006" by Wrox, but have not found it to be a particularly good learning resource (very dry, needs more real world examples).

答:
Start with the advice of tomasr.

Then, try and build something as real as possible. Biztalk is the kind of product where everything seems fine when you read the book and follow the examples, then you sit down to do something and you are thinking "what do I do now".


问:
MPI Ring Leader Election returns segmentation fault
This is what I am trying to achieve.

```<code>Blue is the message.
Yellow is when the specific node changes the leader known to it.
Green is the final election of each node.
</code>```

The code seems correct to me but it's always stuck inside the while loop no matter what I tried. For a small number of nodes during runtime it returns a segmentation fault after a while.

```<code>election_status=0;
firstmsg[0]=world_rank;     // self rank
firstmsg[1]=0;              // counter for hops
chief=world_rank;           // each node declares himself as leader
counter=0;                  // message counter for each node

// each node sends the first message to the next one
MPI_Send(&firstmsg, 2, MPI_INT, (world_rank+1)%world_size, 1, MPI_COMM_WORLD);
printf("Sent ID with counter to the right node [%d -> %d]\n",world_rank, (world_rank+1)%world_size);

while (election_status==0){
    // EDIT: Split MPI_Recv for rank 0 and rest
    if (world_rank==0){
        MPI_Recv(&incoming, 2, MPI_INT, world_size-1, 1, MPI_COMM_WORLD, &status);
    }
    else {
        MPI_Recv(&incoming, 2, MPI_INT, (world_rank-1)%world_size, 1, MPI_COMM_WORLD, &status);
    }
    counter=counter+1;
    if (incoming[0]<chief){
        chief=incoming[0];
    }
    incoming[1]=incoming[1]+1;

    // if message is my own and hopped same times as counter
    if (incoming[0]==world_rank && incoming[1]==counter) {
        printf("Node %d declares node %d a leader.\n", world_rank, chief);
        election_status=1;
    }
    //sends the incremented message to the next node
    MPI_Send(&incoming, 2, MPI_INT, (world_rank+1)%world_size, 1, MPI_COMM_WORLD);
}

MPI_Finalize();
</code>```

答:
In order to determine some minimum number among a number of ranks for all ranks, use MPI_Allreduce!

MPI_Send is blocking. It can block forever until a matching receive is posted. Your program deadlocks on the first call to MPI_Send - and any successive once should it complete by coincidence. To avoid that specifically use MPI_Sendrecv.

(world_rank-1)%world_size will produce -1 for world_rank == 0. Using -1 as rank number is not valid. It might coincidentially be MPI_ANY_SOURCE.

Body:
This is what I am trying to achieve.

Blue is the message.
Yellow is when the specific node changes the leader known to it.
Green is the final election of each node.

The code seems correct to me but it's always stuck inside the while loop no matter what I tried. For a small number of nodes during runtime it returns a segmentation fault after a while.

election_status=0;
firstmsg[0]=world_rank;     // self rank
firstmsg[1]=0;              // counter for hops
chief=world_rank;           // each node declares himself as leader
counter=0;                  // message counter for each node

// each node sends the first message to the next one
MPI_Send(&firstmsg, 2, MPI_INT, (world_rank+1)%world_size, 1, MPI_COMM_WORLD);
printf("Sent ID with counter to the right node [%d -> %d]\n",world_rank, (world_rank+1)%world_size);

while (election_status==0){
    // EDIT: Split MPI_Recv for rank 0 and rest
    if (world_rank==0){
        MPI_Recv(&incoming, 2, MPI_INT, world_size-1, 1, MPI_COMM_WORLD, &status);
    }
    else {
        MPI_Recv(&incoming, 2, MPI_INT, (world_rank-1)%world_size, 1, MPI_COMM_WORLD, &status);
    }
    counter=counter+1;
    if (incoming[0]<chief){
        chief=incoming[0];
    }
    incoming[1]=incoming[1]+1;

    // if message is my own and hopped same times as counter
    if (incoming[0]==world_rank && incoming[1]==counter) {
        printf("Node %d declares node %d a leader.\n", world_rank, chief);
        election_status=1;
    }
    //sends the incremented message to the next node
    MPI_Send(&incoming, 2, MPI_INT, (world_rank+1)%world_size, 1, MPI_COMM_WORLD);
}

MPI_Finalize();


问:
Multer limit images accepted
I am working with Multer and Multer S3 to allow users to upload images on a Node project. I am wanting the user to be able to upload 3 images regardless of their size but no more. If a user tries to select say 6 images I get this error page:

```<code>Error: Unexpected field
   at makeError
</code>```

How would I change my code below to not allow a user to select/upload more than 3 images and/or handle the error in a better way.

Partial Code:

```<code>router.post("/", upload.array('image', 3), function(req, res, next){

          var filepath = undefined;

          var filepath2 = undefined;

          var filepath3 = undefined;

        if(req.files[0]) {
            filepath = req.files[0].key;
        }

          if(req.files[1]) {
            filepath2 = req.files[1].key;
        }

         if(req.files[2]) {
            filepath3 = req.files[2].key;
        }.....
</code>```

Update:

I added this and now I land on a "too many files" error page if the user tries to upload more than 3. Now I just have to figure out how to redirect if too many files.

```<code>  var upload = multer({
    limits : { files: 3 },
</code>```

答:
I played around with multer and here is something that I was able to get working.

Define your multer setup like this

```<code>var upload = multer().array('image', 3);
</code>```

Then modify your function to this,

```<code>router.post("/", function(req, res, next){
   upload(req, res, function (err) {
        if (err) {
           //redirect your user here ...
           return;
        }

        //no multer error proceed with your normal operation ...

   })
});
</code>```

Title: Multer limit images accepted

Body:
I am working with Multer and Multer S3 to allow users to upload images on a Node project. I am wanting the user to be able to upload 3 images regardless of their size but no more. If a user tries to select say 6 images I get this error page:

Error: Unexpected field
   at makeError

How would I change my code below to not allow a user to select/upload more than 3 images and/or handle the error in a better way.

Partial Code:

router.post("/", upload.array('image', 3), function(req, res, next){

          var filepath = undefined;

          var filepath2 = undefined;

          var filepath3 = undefined;

        if(req.files[0]) {
            filepath = req.files[0].key;
        }

          if(req.files[1]) {
            filepath2 = req.files[1].key;
        }

         if(req.files[2]) {
            filepath3 = req.files[2].key;
        }.....

Update:

I added this and now I land on a "too many files" error page if the user tries to upload more than 3. Now I just have to figure out how to redirect if too many files.

  var upload = multer({
    limits : { files: 3 },

Body:
I played around with multer and here is something that I was able to get working.

Define your multer setup like this

var upload = multer().array('image', 3);

Then modify your function to this,

router.post("/", function(req, res, next){
   upload(req, res, function (err) {
        if (err) {
           //redirect your user here ...
           return;
        }

        //no multer error proceed with your normal operation ...

   })
});

ContentLicense: CC BY-SA 4.0


问:
Scipy Newton Krylov Expects Square Matrix
I am trying to use scipy.optimize.newton_krylov() to solve a least-squares optimization problem, i.e. finding x such that (Ax - b)**2 = 0. My understanding is that A has to be mxn with m>n, b has to be mx1, and x will be nx1. When I try to run the optimization, I get an error:

```<code>ValueError: expected square matrix, but got shape=(40, 6)
</code>```

Presumably this error concerns the computation of the Jacobian and not my input matrix A? But if so, how can I change the values I am providing to the functions to resolve this problem? Any advice would be appreciated.

The following code reproduces the error:

```<code>import numpy as np
from scipy.optimize import newton_krylov

A = np.random.uniform(0, 1, (40,6))
b = np.arange(40)
x0 = np.ones(6)

def F(x):
    return (A.dot(x) - b)**2

x = newton_krylov(F, np.ones(6))
</code>```

答:
Krylov method requires the first argument (function F(x) in your case) to be a square matrix.

This seems like a homework question but the answer will be adjusting matrix A to make it square. Examples: https://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/optimize.html#kk

Body:
I am trying to use scipy.optimize.newton_krylov() to solve a least-squares optimization problem, i.e. finding x such that (Ax - b)**2 = 0. My understanding is that A has to be mxn with m>n, b has to be mx1, and x will be nx1. When I try to run the optimization, I get an error:

ValueError: expected square matrix, but got shape=(40, 6)

Presumably this error concerns the computation of the Jacobian and not my input matrix A? But if so, how can I change the values I am providing to the functions to resolve this problem? Any advice would be appreciated.

The following code reproduces the error:

import numpy as np
from scipy.optimize import newton_krylov

A = np.random.uniform(0, 1, (40,6))
b = np.arange(40)
x0 = np.ones(6)

def F(x):
    return (A.dot(x) - b)**2

x = newton_krylov(F, np.ones(6))


问:
jQuery onChange event handler firing function twice
This is the table http://jsfiddle.net/djochw6L/1/
The event is supposed to fire when I enter value in the item column

```<code>$(document).on('change', '.item', function() {
    var ite = $(this).closest('tr');
    getdetails(ite);
})//event

function getdetails(dat){
    var itemName = $(dat).find('.item').val();
    alert (itemName);
};
</code>```

The event handler works correct for the first row. But from the second row onwards it fires twice. Why is this?

答:
try adding return false:</p>

```<code>$(document).on('change', '.item', function () {
    var ite = $(this).closest('tr');
    getdetails(ite);
    return false;
}) //event
</code>```

Body:
This is the table http://jsfiddle.net/djochw6L/1/
The event is supposed to fire when I enter value in the item column

$(document).on('change', '.item', function() {
    var ite = $(this).closest('tr');
    getdetails(ite);
})//event

function getdetails(dat){
    var itemName = $(dat).find('.item').val();
    alert (itemName);
};

The event handler works correct for the first row. But from the second row onwards it fires twice. Why is this?

Body:
try adding return false:

$(document).on('change', '.item', function () {
    var ite = $(this).closest('tr');
    getdetails(ite);
    return false;
}) //event


问:
Spark dataframe databricks csv appends extra double quotes
It seems that when I apply CONCAT on a dataframe in spark sql and store that dataframe as csv file in a HDFS location, then  there are extra double quotes added to that concat column alone in the ouput file .

This double quotes are not added when I appy show.This double quotes are added only when I store that dataframe as a csv file

It seems that I need to remove the  extra double quotes that gets added when I save the dataframe as csv file.

I am using the com.databricks:spark-csv_2.10:1.1.0 jar

Spark Version is 1.5.0-cdh5.5.1

Input :

```<code> campaign_file_name_1, campaign_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,    1
 campaign_file_name_1, campaign_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,    2
</code>```

Expected output :

```<code> campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,     campaign_name_1"="1,  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   campaign_name_1"="2,  2017-06-06 17:09:31
</code>```

Spark Code :

```<code>  object campaignResultsMergerETL extends BaseETL {

  val now  = ApplicationUtil.getCurrentTimeStamp()
  val conf = new Configuration()
  val fs  = FileSystem.get(conf)
  val log = LoggerFactory.getLogger(this.getClass.getName)

  def main(args: Array[String]): Unit = {
    //---------------------
    code for sqlContext Initialization
    //---------------------
    val campaignResultsDF  = sqlContext.read.format("com.databricks.spark.avro").load(campaignResultsLoc)
    campaignResultsDF.registerTempTable("campaign_results")
    val campaignGroupedDF =  sqlContext.sql(
   """
    |SELECT campaign_file_name,
    |campaign_name,
    |tracker_id,
    |SUM(campaign_measure) AS campaign_measure
    |FROM campaign_results
    |GROUP BY campaign_file_name,campaign_name,tracker_id
  """.stripMargin)

    campaignGroupedDF.registerTempTable("campaign_results_full")

    val campaignMergedDF =  sqlContext.sql(
  s"""
    |SELECT campaign_file_name,
    |tracker_id,
    |CONCAT(campaign_name,'\"=\"' ,campaign_measure),
    |"$now" AS audit_timestamp
    |FROM campaign_results_full
  """.stripMargin)

   campaignMergedDF.show(20)
   saveAsCSVFiles(campaignMergedDF, campaignResultsExportLoc, numPartitions)

   }

    def saveAsCSVFiles(campaignMeasureDF:DataFrame,hdfs_output_loc:String,numPartitions:Int): Unit =
    {
       log.info("saveAsCSVFile method started")
       if (fs.exists(new Path(hdfs_output_loc))){
          fs.delete(new Path(hdfs_output_loc), true)
       }
     campaignMeasureDF.repartition(numPartitions).write.format("com.databricks.spark.csv").save(hdfs_output_loc)
       log.info("saveAsCSVFile method ended")
    }

 }
</code>```

Result of campaignMergedDF.show(20) is correct and works fine.

```<code> campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,   campaign_name_1"="1,  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   campaign_name_1"="2,  2017-06-06 17:09:31
</code>```

Result of saveAsCSVFiles : This is incorrect .

```<code> campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,   "campaign_name_1""=""1",  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   "campaign_name_1""=""2",  2017-06-06 17:09:31
</code>```

Could some one help me on this issue?

答:
When you are using

```<code>write.format("com.databricks.spark.csv").save(hdfs_output_loc)
</code>```

In order to write a text which includes " into a csv file, you are facing problems as the " sign is defined as default quote by spark-csv

Replacing the default quote from " to something else (e.g. NULL) should allow you to write " to the file as is.

```<code>write.format("com.databricks.spark.csv").option("quote", "\u0000").save(hdfs_output_loc)
</code>```

Explanation:

You are using the default spark-csv:

escape value which is \

quote value which is "

spark-csv doc

quote: by default the quote character is ", but can be set to any character. Delimiters inside quotes are ignored

escape: by default the escape character is \, but can be set to any character. Escaped quote characters are ignored

This answer suggested the following:

The way to turn off the default escaping of the double quote character
  (") with the backslash character () - i.e. to avoid escaping for all
  characters entirely, you must add an .option() method call with just
  the right parameters after the .write() method call. The goal of the
  option() method call is to change how the csv() method "finds"
  instances of the "quote" character as it is emitting the content. To
  do this, you must change the default of what a "quote" actually means;
  i.e. change the character sought from being a double quote character
  (") to a Unicode "\u0000" character (essentially providing the Unicode
  NUL character assuming it won't ever occur within the document).

Body:
It seems that when I apply CONCAT on a dataframe in spark sql and store that dataframe as csv file in a HDFS location, then  there are extra double quotes added to that concat column alone in the ouput file .

This double quotes are not added when I appy show.This double quotes are added only when I store that dataframe as a csv file

It seems that I need to remove the  extra double quotes that gets added when I save the dataframe as csv file.

I am using the com.databricks:spark-csv_2.10:1.1.0 jar

Spark Version is 1.5.0-cdh5.5.1

Input :

 campaign_file_name_1, campaign_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,    1
 campaign_file_name_1, campaign_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,    2

Expected output :

 campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,     campaign_name_1"="1,  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   campaign_name_1"="2,  2017-06-06 17:09:31

Spark Code :

  object campaignResultsMergerETL extends BaseETL {

  val now  = ApplicationUtil.getCurrentTimeStamp()
  val conf = new Configuration()
  val fs  = FileSystem.get(conf)
  val log = LoggerFactory.getLogger(this.getClass.getName)

  def main(args: Array[String]): Unit = {
    //---------------------
    code for sqlContext Initialization
    //---------------------
    val campaignResultsDF  = sqlContext.read.format("com.databricks.spark.avro").load(campaignResultsLoc)
    campaignResultsDF.registerTempTable("campaign_results")
    val campaignGroupedDF =  sqlContext.sql(
   """
    |SELECT campaign_file_name,
    |campaign_name,
    |tracker_id,
    |SUM(campaign_measure) AS campaign_measure
    |FROM campaign_results
    |GROUP BY campaign_file_name,campaign_name,tracker_id
  """.stripMargin)

    campaignGroupedDF.registerTempTable("campaign_results_full")

    val campaignMergedDF =  sqlContext.sql(
  s"""
    |SELECT campaign_file_name,
    |tracker_id,
    |CONCAT(campaign_name,'\"=\"' ,campaign_measure),
    |"$now" AS audit_timestamp
    |FROM campaign_results_full
  """.stripMargin)

   campaignMergedDF.show(20)
   saveAsCSVFiles(campaignMergedDF, campaignResultsExportLoc, numPartitions)

   }

    def saveAsCSVFiles(campaignMeasureDF:DataFrame,hdfs_output_loc:String,numPartitions:Int): Unit =
    {
       log.info("saveAsCSVFile method started")
       if (fs.exists(new Path(hdfs_output_loc))){
          fs.delete(new Path(hdfs_output_loc), true)
       }
     campaignMeasureDF.repartition(numPartitions).write.format("com.databricks.spark.csv").save(hdfs_output_loc)
       log.info("saveAsCSVFile method ended")
    }

 }

Result of campaignMergedDF.show(20) is correct and works fine.

 campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,   campaign_name_1"="1,  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   campaign_name_1"="2,  2017-06-06 17:09:31

Result of saveAsCSVFiles : This is incorrect .

 campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,   "campaign_name_1""=""1",  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   "campaign_name_1""=""2",  2017-06-06 17:09:31

Could some one help me on this issue?

Body:
When you are using

write.format("com.databricks.spark.csv").save(hdfs_output_loc)

In order to write a text which includes " into a csv file, you are facing problems as the " sign is defined as default quote by spark-csv

Replacing the default quote from " to something else (e.g. NULL) should allow you to write " to the file as is.

write.format("com.databricks.spark.csv").option("quote", "\u0000").save(hdfs_output_loc)

Explanation:

You are using the default spark-csv:

escape value which is \

quote value which is "

spark-csv doc

quote: by default the quote character is ", but can be set to any character. Delimiters inside quotes are ignored

escape: by default the escape character is \, but can be set to any character. Escaped quote characters are ignored

This answer suggested the following:

The way to turn off the default escaping of the double quote character
  (") with the backslash character () - i.e. to avoid escaping for all
  characters entirely, you must add an .option() method call with just
  the right parameters after the .write() method call. The goal of the
  option() method call is to change how the csv() method "finds"
  instances of the "quote" character as it is emitting the content. To
  do this, you must change the default of what a "quote" actually means;
  i.e. change the character sought from being a double quote character
  (") to a Unicode "\u0000" character (essentially providing the Unicode
  NUL character assuming it won't ever occur within the document).


问:
How to improve performance when searching by id in Elasticsearch
I am using Elasticsearch 5.1.

The cluster consists of 5 nodes and uses 16gb memory.

I store some data in the ES using the document's ID, and retrieve the data through the get request using the ES JAVA Client.

I have tried several tests.

Sometimes the response time is slightly slower.

Perhaps it seems to be late when the first request occurs after not making a get request on that index for some time.

Is there a way to improve performance when retrieving data through the document's ID?

答:
I have found the reason for poor performance.

I have found that search performance drops when a lot of documents are inserted in bulk in an Elasticsearch cluster.

Resolved after adjusting bulk size.


问:
how to use indexof in array set in angularjs
```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
    $scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
    $scope.onChange = function() {
            var a = this.drop.state;  }
});
</script>
<body>

<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>
</div>
</body>
</code>```

In this code, I can be able to get the selected value from the textbox in the variable a. Now, I need to get the code value of the name selected. Is it possible using indexof(). And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.

答:
```<code><option value="{{x}}" ng-repeat = "x in state"> {{x.name}} </option>
</code>```

If you add the value on your Option, you may get the complete object, and accessing the code and the Value

Body:
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>

In this code, I can be able to get the selected value from the textbox in the variable a. Now, I need to get the code value of the name selected. Is it possible using indexof(). And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.

Body:
<option value="{{x}}" ng-repeat = "x in state"> {{x.name}} </option>

If you add the value on your Option, you may get the complete object, and accessing the code and the Value