问:
Fitting elements into a grid in a responsive way
Consider a
 element that contains <button> elements:

```<code><div id="box">
    <button class="button">1</button>
    <button class="button">2</button>
    <button class="button">3</button>
    ...
</div>
</code>```

I want to fit these elements into a grid pattern, so that

buttons are of equal dimensions and have a fixed minimum width,

a maximal amount of buttons is stacked on each row,

button width is adjusted so that each row is filled completely,

and this behavior persists when #box is resized.

Is there a way to do so using native HTML/CSS features (without using JavaScript)? I tried using the new CSS Flexbox layout:

```<code>#box {
    display: flex;
    width: 500px;
    height: 500px;
}

.button {
    flex: 1 1 auto;
    min-width: 40px;
    height: 40px;
}
</code>```

But this doesn't work..

Thanks for your help!

答:
You can use CSS flex for this, as you suspected.

flex-wrap is what you were missing, as well as using percentages for responsiveness.

#box {
  display: flex;
  flex-wrap: wrap;
}
#box > * {
  flex: 1 0 100px; /* each button should be at least 100px wide */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='box'>
  <button class='button'>1</button>
  <button class='button'>2</button>
  <button class='button'>3</button>
  <button class='button'>4</button>
  <button class='button'>5</button>
  <button class='button'>6</button>
  <button class='button'>7</button>
  <button class='button'>8</button>
  <button class='button'>9</button>
  <button class='button'>10</button>
  <button class='button'>11</button>
  <button class='button'>12</button>
  <button class='button'>13</button>
  <button class='button'>14</button>
  <button class='button'>15</button>
  <button class='button'>16</button>
</div></code>```

Body:
Consider a
 element that contains <button> elements:

    <button class="button">1</button>
    <button class="button">2</button>
    <button class="button">3</button>
    ...

I want to fit these elements into a grid pattern, so that

buttons are of equal dimensions and have a fixed minimum width,

a maximal amount of buttons is stacked on each row,

button width is adjusted so that each row is filled completely,

and this behavior persists when #box is resized.

Is there a way to do so using native HTML/CSS features (without using JavaScript)? I tried using the new CSS Flexbox layout:

#box {
    display: flex;
    width: 500px;
    height: 500px;
}

.button {
    flex: 1 1 auto;
    min-width: 40px;
    height: 40px;
}

But this doesn't work..

Thanks for your help!

Body:
You can use CSS flex for this, as you suspected.

flex-wrap is what you were missing, as well as using percentages for responsiveness.

#box {
  display: flex;
  flex-wrap: wrap;
}
#box > * {
  flex: 1 0 100px; /* each button should be at least 100px wide */
}

<div id='box'>
  <button class='button'>1</button>
  <button class='button'>2</button>
  <button class='button'>3</button>
  <button class='button'>4</button>
  <button class='button'>5</button>
  <button class='button'>6</button>
  <button class='button'>7</button>
  <button class='button'>8</button>
  <button class='button'>9</button>
  <button class='button'>10</button>
  <button class='button'>11</button>
  <button class='button'>12</button>
  <button class='button'>13</button>
  <button class='button'>14</button>
  <button class='button'>15</button>
  <button class='button'>16</button>
</div>


来源: stackexchange

问:
check for the last space in a string?
I have a string that goes "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum." stored in a variable T and I have a variable L which is set to 30.

I am trying to write a loop that will print the string out, but in such a way that only L amount of characters (30 in this case) can fit on the line. If there is a word which goes over the limit (As in, it starts on character 28 and ends on 32), then I am trying to store the index at which point the last space was (The index of the most recent " ") in a variable called s. This is what I have, but I'm not sure where to go from here:

```<code>finalstr = ""
reg = re.compile('[a-z]')
for i in range(0, L):
    if T[i] >= L and reg.search(T[i]):
        finalstr += "\n"
    else:
        finalstr += T[i]

return finalstr
</code>```

What I want to get is:

```<code>Quisque pretium magna ac
aliquet interdum. Mauris
prosuere, risus non
mollis placerat, diam
ligula commodo justo, ac
aliquet velit ante a
ipsum.
</code>```

However, this is the traceback I get, what am I doing wrong?

```<code>Traceback (most recent call last):
File "problem.py", line 146, in <module>
print wrap(T, L)
File "problem.py", line 122, in wrap
if T[i] >= L and reg.search(T[i]):
IndexError: list index out of range
</code>```

答:
I think that the best approach is to split the sentence into a list and use it to count characters. I do not know if I understood correctly the s variable. I stored the white spaces after each last word of each line.

```<code>T = "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum."
L = 30

listofwords = T.split()

totalchars = 0
sentence = []
s=[]
for word in listofwords:
    if totalchars+len(word)+1 < L:
        totalchars+=len(word)+1
        sentence.append(word)
    elif totalchars+len(word)+1 ==L:
        totalchars+=len(word)+1
        sentence.append(word)
        print(' '.join(sentence))
        sentence = [word]
        totalchars = len(word)
    elif totalchars+len(word)+1 > L:
        s.append(totalchars+1)
        print(' '.join(sentence))
        sentence = [word]
        totalchars = len(word)
print(' '.join(sentence))
print(s)
</code>```

ContentLicense: CC BY-SA 3.0

Title: check for the last space in a string?

Body:
I have a string that goes "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum." stored in a variable T and I have a variable L which is set to 30.

I am trying to write a loop that will print the string out, but in such a way that only L amount of characters (30 in this case) can fit on the line. If there is a word which goes over the limit (As in, it starts on character 28 and ends on 32), then I am trying to store the index at which point the last space was (The index of the most recent " ") in a variable called s. This is what I have, but I'm not sure where to go from here:

finalstr = ""
reg = re.compile('[a-z]')
for i in range(0, L):
    if T[i] >= L and reg.search(T[i]):
        finalstr += "\n"
    else:
        finalstr += T[i]

return finalstr

What I want to get is:

Quisque pretium magna ac
aliquet interdum. Mauris
prosuere, risus non
mollis placerat, diam
ligula commodo justo, ac
aliquet velit ante a
ipsum.

However, this is the traceback I get, what am I doing wrong?

Traceback (most recent call last):
File "problem.py", line 146, in <module>
print wrap(T, L)
File "problem.py", line 122, in wrap
if T[i] >= L and reg.search(T[i]):
IndexError: list index out of range

Body:
I think that the best approach is to split the sentence into a list and use it to count characters. I do not know if I understood correctly the s variable. I stored the white spaces after each last word of each line.

T = "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum."
L = 30

listofwords = T.split()

totalchars = 0
sentence = []
s=[]
for word in listofwords:
    if totalchars+len(word)+1 < L:
        totalchars+=len(word)+1
        sentence.append(word)
    elif totalchars+len(word)+1 ==L:
        totalchars+=len(word)+1
        sentence.append(word)
        print(' '.join(sentence))
        sentence = [word]
        totalchars = len(word)
    elif totalchars+len(word)+1 > L:
        s.append(totalchars+1)
        print(' '.join(sentence))
        sentence = [word]
        totalchars = len(word)
print(' '.join(sentence))
print(s)


问:
Nokogiri example not showing array (Ruby)
When I try to run this via terminal I can parse/display the data but when I type in pets_array = []

I am not seeing anything

My code is as follows:

```<code>require 'HTTParty'
require 'Nokogiri'
require 'JSON'
require 'Pry'
require 'csv'

page = HTTParty.get('https://newyork.craigslist.org/search/pet?s=0')

parse_page = Nokogiri::HTML(page)

pets_array = []

parse_page.css('.content').css('.row').css('.result-title hdrlnk').map do |a|
  post_name = a.text
  pets_array.push(post_name)
end

CSV.open('pets.csv', 'w') do |csv|
  csv << pets_array
end

Pry.start(binding)
</code>```

答:
Maybe to be precise you could access each anchor tag with class .result-title.hdrlnk inside .result-info, .result-row, .rows and .content:

```<code>page = HTTParty.get 'https://newyork.craigslist.org/search/pet?s=0'
parse_page = Nokogiri::HTML page
pets_array = parse_page.css('.content .rows .result-row .result-info .result-title.hdrlnk').map &:text
p pets_array
# ["Mini pig", "Black Russian Terrier", "2 foster or forever homes needed Asap!", ...]
</code>```

As you're using map, you can use the pets_array variable to store the text on each iterated element, no need to push.

If you want to write the data stored in the array, then you can push is directly, no need to redefined as an empty array (the reason because you get a blank csv file):

```<code>require 'httparty'
require 'nokogiri'
require 'csv'

page = HTTParty.get 'https://newyork.craigslist.org/search/pet?s=0'
parse_page = Nokogiri::HTML page
pets_array = parse_page.css('.content .rows .result-row .result-info .result-title.hdrlnk').map &:text
CSV.open('pets.csv', 'w') { |csv| csv << pets_array }
</code>```

Body:
When I try to run this via terminal I can parse/display the data but when I type in pets_array = []

I am not seeing anything

My code is as follows:

require 'HTTParty'
require 'Nokogiri'
require 'JSON'
require 'Pry'
require 'csv'

page = HTTParty.get('https://newyork.craigslist.org/search/pet?s=0')

parse_page = Nokogiri::HTML(page)

pets_array = []

parse_page.css('.content').css('.row').css('.result-title hdrlnk').map do |a|
  post_name = a.text
  pets_array.push(post_name)
end

CSV.open('pets.csv', 'w') do |csv|
  csv << pets_array
end

Pry.start(binding)

Body:
Maybe to be precise you could access each anchor tag with class .result-title.hdrlnk inside .result-info, .result-row, .rows and .content:

page = HTTParty.get 'https://newyork.craigslist.org/search/pet?s=0'
parse_page = Nokogiri::HTML page
pets_array = parse_page.css('.content .rows .result-row .result-info .result-title.hdrlnk').map &:text
p pets_array
# ["Mini pig", "Black Russian Terrier", "2 foster or forever homes needed Asap!", ...]

As you're using map, you can use the pets_array variable to store the text on each iterated element, no need to push.

If you want to write the data stored in the array, then you can push is directly, no need to redefined as an empty array (the reason because you get a blank csv file):

require 'httparty'
require 'nokogiri'
require 'csv'

page = HTTParty.get 'https://newyork.craigslist.org/search/pet?s=0'
parse_page = Nokogiri::HTML page
pets_array = parse_page.css('.content .rows .result-row .result-info .result-title.hdrlnk').map &:text
CSV.open('pets.csv', 'w') { |csv| csv << pets_array }


问:
SQL Schema Comparison Error "Target is unavailable"
When comparing an SQLServer project in Visual Studio 2015 Update 2 against a database SQL Server 2012, it shows the error "Target is unavailable" or "Source is unavailable" when change the direction.

It used to work properly a couple of months ago. Is there any workaround? I couldn't find any.

答:
I get this error in Visual Studio 2017 when I use SQL Server Authentication but don't save the password. I've tested these steps with Visual Studio 15.6.3 and SQL Server 12.0.5000.0

Fixing the error

This fixes the problem, but the problem comes back the next time I restart Visual Studio.

Go to Tools -> SQL Server -> New Schema Comparison...

Select either Select Source or Select Target

Select Select Connection

Under Recent Connections, find all connections that gave you this error

For each of these, right-click the connection and select Remove from History

Restart Visual Studio

Preventing the error from coming back

Complete Fixing the error above

When you are setting the connection details, check the Remember Password checkbox.

Reproducing the error

If you want to troubleshoot this error, here is how I managed to reproduce it.

Go to Tools -> SQL Server -> New Schema Comparison...

Select a source and target connection

For at least one connection, use SQL Server Authentication but don't select Remember Password

Press Compare

Ensure it works without errors

Restart Visual Studio

Repeat steps 1-4, using the exact same connection details

ContentLicense: CC BY-SA 4.0


问:
Angular - Running repeated tasks in background tabs?
I have an Angular webapp that opens a websocket to my server, and the server sends a new data packet to the app every second. When the websocket in the app receives the message, I do some minor processing and then show the data to the user in a plot.

When I change tabs, it appears that my processing continues to happen once a second, until about 10 minutes have passed while the tab is in the background. Then, my app locks up. If I leave it in the foreground, it eventually "catches back up" and runs my processing routine many times per second - like the function calls are queued up.

The behavior seems to be consistent with both Chrome and Safari on both Linux and Mac.

Does anyone know what is going on here? Why would the background processing suddenly change after a certain period of time?

答:
This is a recent change, aiming to reduce battery consumption. Sadly there is no real opt-out, if your app is running in the background it will get throttled. More details on the article explaining this in details on Google developers portal.

Shipping in Chrome 57, budget-based timer throttling is a further extension of the timer alignment mechanism, placing an additional limit on background timer CPU usage. It operates as follows:

Each background tab has a time budget (in seconds) for running timers in the background.

A page is subjected to time budget limitations after 10 seconds in the background.

A timer task is allowed to run only when the time budget is non-negative.

After a timer has executed, its run time is subtracted from the budget.
  The budget continuously regenerates with time (currently set to a rate of 0.01 seconds per second). Note that this budget regeneration rate can be tweaked as Chrome collects more data about throttling behavior.

There are a number of automatic exemptions from this throttling:

Applications playing audio are considered foreground and aren’t throttled.

Applications with real-time connections (WebSockets and WebRTC), to avoid closing these connections by timeout. The run-timers-once-a-second rule is still applied in these cases.

The particular rule you are affected by is:

Applications with real-time connections (WebSockets and WebRTC), to avoid closing these connections by timeout. The run-timers-once-a-second rule is still applied in these cases.


问:
How to go to last position in Kendo UI with Virtual Scrolling in IE11
After binding the grid it cannot stay put and sends you to the top of the grid losing your place. I managed to write some script to save the users position on the grid, then after binding it scrolls the user back to that saved location:
How to get scrollLeft() from kendoVirtualScrollable

This seems to only work if the user is either at the top of the grid or the bottom of the grid. If the user is in the middle of the grid (during virtual scrolling) it is unable to save the scrollTop().

I put this Dojo together to simplify the issue I am experiencing.

http://dojo.telerik.com/upIto

Press "TEST POSITION" which will bring you to scrollTop: 3360. (Note: The position on the grid. For me the top OrderID was 10328).

Press "TEST POSITION" again(scrollTop has not changed).

The scroll now brings the user to a different location. (my new top OrderID being 10365).

The user has lost their place. Also note how the scroll bar stays in place.

This is undesirable to the user.

Any help with this bug is greatly appreciated.

UPDATE

if i set the scrollTop to 0 before going to new location it seems to bring me generally a row above the position.

I added this:

```<code>   $("#grid div.k-scrollbar-vertical").scrollTop(0);
   $("#grid div.k-virtual-scrollable-wrap").animate({ scrollTop: 0 }, 0);
    $("#grid div.k-scrollbar-vertical").animate({ scrollTop: 0 }, 0);
</code>```

before

```<code>   $("#grid div.k-virtual-scrollable-wrap").animate({ scrollTop: 3360 }, 0);
    $("#grid div.k-scrollbar-vertical").animate({ scrollTop: 3360 }, 0);
</code>```

Pressed the 'TEST POSITION' once: OrderID: 10329. Pressed it again: OrderID 10328.

答:
OK so this is a bug and apparently it has been fixed in the 2017 release.

"From our 2017 R3 release, we officially support the editing with virtual scrolling.

Please check our new demo and advise if there are any scrolling issue after the new implementation:

http://demos.telerik.com/kendo-ui/grid/virtualization-local-data"

-Stefan (Telerik Admin)

Body:
After binding the grid it cannot stay put and sends you to the top of the grid losing your place. I managed to write some script to save the users position on the grid, then after binding it scrolls the user back to that saved location:
How to get scrollLeft() from kendoVirtualScrollable

This seems to only work if the user is either at the top of the grid or the bottom of the grid. If the user is in the middle of the grid (during virtual scrolling) it is unable to save the scrollTop().

I put this Dojo together to simplify the issue I am experiencing.

http://dojo.telerik.com/upIto

Press "TEST POSITION" which will bring you to scrollTop: 3360. (Note: The position on the grid. For me the top OrderID was 10328).

Press "TEST POSITION" again(scrollTop has not changed).

The scroll now brings the user to a different location. (my new top OrderID being 10365).

The user has lost their place. Also note how the scroll bar stays in place.

This is undesirable to the user.

Any help with this bug is greatly appreciated.

UPDATE

if i set the scrollTop to 0 before going to new location it seems to bring me generally a row above the position.

I added this:

   $("#grid div.k-scrollbar-vertical").scrollTop(0);
   $("#grid div.k-virtual-scrollable-wrap").animate({ scrollTop: 0 }, 0);
    $("#grid div.k-scrollbar-vertical").animate({ scrollTop: 0 }, 0);

before

   $("#grid div.k-virtual-scrollable-wrap").animate({ scrollTop: 3360 }, 0);
    $("#grid div.k-scrollbar-vertical").animate({ scrollTop: 3360 }, 0);

Pressed the 'TEST POSITION' once: OrderID: 10329. Pressed it again: OrderID 10328.


问:
How to get relative path from absolute path
There's a part in my apps that displays the file path loaded by the user through OpenFileDialog. It's taking up too much space to display the whole path, but I don't want to display only the filename as it might be ambiguous. So I would prefer to show the file path relative to the assembly/exe directory.

For example, the assembly resides at C:\Program Files\Dummy Folder\MyProgram and the file at C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat then I would like it to show .\Data\datafile1.dat. If the file is in C:\Program Files\Dummy Folder\datafile1.dat, then I would want ..\datafile1.dat. But if the file is at the root directory or 1 directory below root, then display the full path.

What solution would you recommend? Regex?

Basically I want to display useful file path info without taking too much screen space.

EDIT: Just to clarify a little bit more. The purpose of this solution is to help user or myself knowing which file did I loaded last and roughly from which directory was it from. I'm using a readonly textbox to display the path. Most of the time, the file path is much longer than the display space of the textbox. The path is supposed to be informative but not important enough as to take up more screen space.

Alex Brault comment was good, so is Jonathan Leffler. The Win32 function provided by DavidK only help with part of the problem, not the whole of it, but thanks anyway. As for James Newton-King solution, I'll give it a try later when I'm free.

答:
Play with something like:

```<code>private String GetRelativePath(Int32 level, String directory, out String errorMessage) {
        if (level < 0 || level > 5) {
            errorMessage = "Find some more smart input data";
            return String.Empty;
        }
        // ==========================
        while (level != 0) {
            directory = Path.GetDirectoryName(directory);
            level -= 1;
        }
        // ==========================
        errorMessage = String.Empty;
        return directory;
    }
</code>```

And test it

```<code>[Test]
    public void RelativeDirectoryPathTest() {
        var relativePath =
            GetRelativePath(3, AppDomain.CurrentDomain.BaseDirectory, out var errorMessage);
        Console.WriteLine(relativePath);
        if (String.IsNullOrEmpty(errorMessage) == false) {
            Console.WriteLine(errorMessage);
            Assert.Fail("Can not find relative path");
        }
    }
</code>```

OwnerDisplayName: faulty

LastEditorDisplayName: faulty

Body:
Play with something like:

private String GetRelativePath(Int32 level, String directory, out String errorMessage) {
        if (level < 0 || level > 5) {
            errorMessage = "Find some more smart input data";
            return String.Empty;
        }
        // ==========================
        while (level != 0) {
            directory = Path.GetDirectoryName(directory);
            level -= 1;
        }
        // ==========================
        errorMessage = String.Empty;
        return directory;
    }

And test it

[Test]
    public void RelativeDirectoryPathTest() {
        var relativePath =
            GetRelativePath(3, AppDomain.CurrentDomain.BaseDirectory, out var errorMessage);
        Console.WriteLine(relativePath);
        if (String.IsNullOrEmpty(errorMessage) == false) {
            Console.WriteLine(errorMessage);
            Assert.Fail("Can not find relative path");
        }
    }


问:
Rewrite a csv file by rearranging columns and rows
I have a csv file (let's call it input.csv) that looks like this:

```<code>ID; Text_1; Points_1; Text_2; Points_2
1; "Hello world one"; 33; "Hello world two"; 90
2, "Goodbye world one"; 44; "Goodbye world two";100
</code>```

I want to create another csv file (let's call it output.csv) that rearranges the columns like this:

```<code> ID; Field; Sent; Points;
 1; Text_1;"Hello world one"; 33
 1; Text_2;"Hello world two"; 90
 2; Text_1;"Goodbye world one"; 44
 2; Text_2;"Goodbye world two"; 100
</code>```

It does not seem as easy as a priori I thought. I wonder if there is a way to directly transcribe the file. Thanks in advance.

I've tried this with some help, but I have difficulties to read and copy the columns and rows in the order I said.

```<code>with open("results.csv", "r") as text:
    reader = csv.DictReader(text, delimiter=";")

rows = [l.split(";") for l in text.split("\n")]
del filas[0]

newlist = list()
for l in filas:
  newlist.append([l[0], 'Texto_1', l[2]])
  newlist.append([l[0], 'Texto_2', l[4]])
</code>```

答:
You can try this:</p>

```<code>def get_data()
   with open('filename.csv') as f:
      data = [i.strip('\n').split('; ') for i in f]
      header = data[0]
      for i, a in enumerate(data):
          yield [data[0], header[1], data[1], data[2]]
          yield [data[0], header[3], data[3], data[4]]

final_data = ['; '.join(i) for i in get_data()]
</code>```

Body:
I have a csv file (let's call it input.csv) that looks like this:

ID; Text_1; Points_1; Text_2; Points_2
1; "Hello world one"; 33; "Hello world two"; 90
2, "Goodbye world one"; 44; "Goodbye world two";100

I want to create another csv file (let's call it output.csv) that rearranges the columns like this:

 ID; Field; Sent; Points;
 1; Text_1;"Hello world one"; 33
 1; Text_2;"Hello world two"; 90
 2; Text_1;"Goodbye world one"; 44
 2; Text_2;"Goodbye world two"; 100

It does not seem as easy as a priori I thought. I wonder if there is a way to directly transcribe the file. Thanks in advance.

I've tried this with some help, but I have difficulties to read and copy the columns and rows in the order I said.

with open("results.csv", "r") as text:
    reader = csv.DictReader(text, delimiter=";")

rows = [l.split(";") for l in text.split("\n")]
del filas[0]

newlist = list()
for l in filas:
  newlist.append([l[0], 'Texto_1', l[2]])
  newlist.append([l[0], 'Texto_2', l[4]])

Body:
You can try this:

def get_data()
   with open('filename.csv') as f:
      data = [i.strip('\n').split('; ') for i in f]
      header = data[0]
      for i, a in enumerate(data):
          yield [data[0], header[1], data[1], data[2]]
          yield [data[0], header[3], data[3], data[4]]

final_data = ['; '.join(i) for i in get_data()]


问:
PCA() got an unexpected keyword argument 'k'
I am trying t perform pca from a spark application using PySpark API on a python script. I doing This way:

pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
PCAmodel = pca.fit(data)
```

when I run those two code line in the pyspark shell it work and return good results, but in an application script, I am getting the type of error:

PCA() got an unexpected keyword argument 'k'

PS: In both case I am using Spark 2.2.0

where is the problem? why it does work in the PySpark shell and not for the application?

答:
Try renaming your classes:

```<code>from pyspark.ml.feature import PCA as PCAML
from sklearn.decomposition import PCA as PCASK

pca_ml = PCAML(k=3, inputCol="features", outputCol="pcaFeatures")
</code>```

There should be no confusion, then, which one you call.

Body:
I am trying t perform pca from a spark application using PySpark API on a python script. I doing This way:

pca = PCA(k=3, inputCol="features", outputCol="pcaFeatures")
PCAmodel = pca.fit(data)

when I run those two code line in the pyspark shell it work and return good results, but in an application script, I am getting the type of error:

PCA() got an unexpected keyword argument 'k'

PS: In both case I am using Spark 2.2.0

where is the problem? why it does work in the PySpark shell and not for the application?

Body:
Try renaming your classes:

from pyspark.ml.feature import PCA as PCAML
from sklearn.decomposition import PCA as PCASK

pca_ml = PCAML(k=3, inputCol="features", outputCol="pcaFeatures")

There should be no confusion, then, which one you call.


问:
Cannot read property 'substring' of undefined
I have the following code that is causing me an error stating Cannot read property 'substring' of undefined

```<code>      <div class="extra">
        <p><%- blog.body.substring(0, 120) %> ... </p>
        <a href="/blogs/<%= blog._id %>">Read More</a>
      </div>
</code>```

However the error is occuring on my index.js page only when new content is added to the page, not on the existing content. I am using express on the backend. The change that I have made was

```<code>router.post("/blogs", isLoggedIn, function(req, res){
    // create blog
    req.body.blog.body = req.sanitize(req.body.blog.body);
    Blog.create(req.body.blog, function(err, newBlog){
        if(err){
            res.render("blogs/new");
        } else {
            //then, redirect to the index
            res.redirect("/blogs");
        }
    });
});
</code>```

to this

```<code>// CREATE ROUTE
router.post("/blogs", isLoggedIn, function(req, res){
    var title = req.body.title;
    var image = req.body.image;
    var description =  req.body.description;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var blogPost = {title: title, image: image, description: description, author: author}
    req.body.blog.body = req.sanitize(req.body.blog.body);
    Blog.create(blogPost, function(err, newBlog){
        if(err){
            res.render("blogs/new");
        } else {
            //then, redirect to the index
            res.redirect("/blogs");
</code>```

答:
check this out you should pass data to render method to access it in template engine so you don't have any data in page this is why you get undefined  ...

http://expressjs.com/en/api.html#res.render

Body:
I have the following code that is causing me an error stating Cannot read property 'substring' of undefined

<%- blog.body.substring(0, 120) %> ...

        <a href="/blogs/<%= blog._id %>">Read More

However the error is occuring on my index.js page only when new content is added to the page, not on the existing content. I am using express on the backend. The change that I have made was

router.post("/blogs", isLoggedIn, function(req, res){
    // create blog
    req.body.blog.body = req.sanitize(req.body.blog.body);
    Blog.create(req.body.blog, function(err, newBlog){
        if(err){
            res.render("blogs/new");
        } else {
            //then, redirect to the index
            res.redirect("/blogs");
        }
    });
});

to this

// CREATE ROUTE
router.post("/blogs", isLoggedIn, function(req, res){
    var title = req.body.title;
    var image = req.body.image;
    var description =  req.body.description;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var blogPost = {title: title, image: image, description: description, author: author}
    req.body.blog.body = req.sanitize(req.body.blog.body);
    Blog.create(blogPost, function(err, newBlog){
        if(err){
            res.render("blogs/new");
        } else {
            //then, redirect to the index
            res.redirect("/blogs");


问:
Get Oauth Access Token in Python
I am trying to generate a oauth access token for experian's sandbox API (they give information on credit information).
Their tutorial  Says to run this (fake data) to get an access token:

```<code>curl -X POST
-d '{ "username":"youremail@email.com", "password":"YOURPASSWORD"}'
-H "Client_id: 3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9"
-H "Client_secret: ipu3WQDqTEjqZDXW"
-H "Content-Type: application/json"
"https://sandbox-us-api.experian.com/oauth2/v1/token"
</code>```

How would I run this in python? I tried this among a lot of other things:

```<code>data = { "username" : "youremail@email.com", "password":"YOURPASSWORD"}

headers = {"Client_id": "3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9", "Client_secret": "ipu3WQDqTEjqZDXW", "Content-Type": "application/json"}

response = requests.post("https://sandbox-us-
api.experian.com/oauth2/v1/token", data=data, headers=headers)
</code>```

Any help would be greatly appreciated

答:
Almost there, just need to parse the response:</p>

```<code>import json

data = { "username" : "youremail@email.com", "password":"YOURPASSWORD"}

headers = {"Client_id": "3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9", "Client_secret": "ipu3WQDqTEjqZDXW", "Content-Type": "application/json"}

response = requests.post("https://sandbox-us-api.experian.com/oauth2/v1/token", data=data, headers=headers)
if response.status_code in [200]:
    tok_dict = json.loads(response.text)
    print(tok_dict)
    issued_at = tok_dict["issued_at"]
    expires_in = tok_dict["expires_in"]
    token_type = tok_dict["token_type"]
    access_token = tok_dict["access_token"]
else:
    print(response.text)
</code>```

Title: Get Oauth Access Token in Python

Body:
I am trying to generate a oauth access token for experian's sandbox API (they give information on credit information).
Their tutorial  Says to run this (fake data) to get an access token:

curl -X POST
-d '{ "username":"youremail@email.com", "password":"YOURPASSWORD"}'
-H "Client_id: 3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9"
-H "Client_secret: ipu3WQDqTEjqZDXW"
-H "Content-Type: application/json"
"https://sandbox-us-api.experian.com/oauth2/v1/token"

How would I run this in python? I tried this among a lot of other things:

data = { "username" : "youremail@email.com", "password":"YOURPASSWORD"}

headers = {"Client_id": "3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9", "Client_secret": "ipu3WQDqTEjqZDXW", "Content-Type": "application/json"}

response = requests.post("https://sandbox-us-
api.experian.com/oauth2/v1/token", data=data, headers=headers)

Any help would be greatly appreciated

Body:
Almost there, just need to parse the response:

import json

data = { "username" : "youremail@email.com", "password":"YOURPASSWORD"}

headers = {"Client_id": "3QC11Sm45ti8wEG0d9A5hma5XIlGG7U9", "Client_secret": "ipu3WQDqTEjqZDXW", "Content-Type": "application/json"}

response = requests.post("https://sandbox-us-api.experian.com/oauth2/v1/token", data=data, headers=headers)
if response.status_code in [200]:
    tok_dict = json.loads(response.text)
    print(tok_dict)
    issued_at = tok_dict["issued_at"]
    expires_in = tok_dict["expires_in"]
    token_type = tok_dict["token_type"]
    access_token = tok_dict["access_token"]
else:
    print(response.text)


问:
Can I detect element visibility using only CSS?
I checked the API for some pseudo-selector such as :visible or :hidden, but was disappointed to find no such selector exists. Since jQuery has supported these selectors for a while now, I was hoping they'd be implemented. The idea is, that I'd like to show a certain element only when the element next to it is hidden, but I don't want to use JavaScript to do so. Any options?

答:
It depends on what you mean by "next to it".
You can select an element by visibility using attribute-selectors. Or from here:

The CSS attribute selector matches elements based on the presence or value of a given attribute.

To access an element by visibility, you can use for instance the substring matching attribute-selector star [att*=val]. Supposing the style of the div was hidden using visibility: hidden;:

```<code>div[style*="hidden"] {

}
</code>```

Now the question is how do you access the element "next to it".
If the element you try to target comes directly after the hidden one (within same parent) use the + selector:

```<code>div[style*="hidden"] + span {

}
</code>```

If it's before, you are out of luck but can look for some work around in the answers to this question:
Is there a "previous sibling" CSS selector?

Body:
It depends on what you mean by "next to it".
You can select an element by visibility using attribute-selectors. Or from here:

The CSS attribute selector matches elements based on the presence or value of a given attribute.

To access an element by visibility, you can use for instance the substring matching attribute-selector star [att*=val]. Supposing the style of the div was hidden using visibility: hidden;:

div[style*="hidden"] {

}

Now the question is how do you access the element "next to it".
If the element you try to target comes directly after the hidden one (within same parent) use the + selector:

div[style*="hidden"] + span {

}

If it's before, you are out of luck but can look for some work around in the answers to this question:
Is there a "previous sibling" CSS selector?


问:
Extract letters before first number Windows batch file
I'm making a batch program that will go through each line of a text file. Each line will have a similar format in that it is series of letters then either nothing or a number followed by more characters like so:

RRR14

AMRCC1M_08

TT

I need to be able to use both the entire string and just the letters before the first number while running the code (i.e. var1=RRR14 and var2=RRR), but I'm unsure how to extract just the leading letters since the length and values are different for each string. Also since there isn't guaranteed to be a number in the string, I'm not sure how to go about it.

EDIT: Using the suggested solution, I have a new problem. It seems that var2 isn't updating correctly. I run the code:

```<code>for /f "tokens=1" %%a in (%1.txt) do (
for /f "tokens=1 delims=0123456789" %%G in ("%%a") do set var2=%%G
echo %var2%
echo %%a
echo.
)
</code>```

with all the ECHO's to try to debug and I get:

```<code>>set var2=RRR
JIKK
RRR14
</code>```

where JIKK seems to come from JIKK8 (the last line in the text file). Not sure if I'm referencing the variable incorrectly or what's not working here

答:
You can use a FOR /F command and use all 10 numbers as the DELIMS options.

So in your example.

```<code>FOR /F "TOKENS=1 delims=0123456789" %%G IN ("RRR14") DO SET var2=%%G
</code>```

So based on the new code you updated within your question you have two options.

The first option is to just create another parenthesized code block and use the FOR variable directly.

```<code>@ECHO OFF
for /f "tokens=1" %%a in (%1.txt) do (
    for /f "tokens=1 delims=0123456789" %%G in ("%%a") do (
        echo %G%
        echo %%a
        echo.
    )
)
</code>```

Your second option is to use delayed expansion to reference the variable without an additional parenthesized code block.

```<code>@ECHO OFF
setlocal enabledelayedexpansion
for /f "tokens=1" %%a in (%1.txt) do (
    for /f "tokens=1 delims=0123456789" %%G in ("%%a") do set "var2=%%G"
    echo !var2!
    echo %%a
    echo.
)
</code>```

Body:
I'm making a batch program that will go through each line of a text file. Each line will have a similar format in that it is series of letters then either nothing or a number followed by more characters like so:

RRR14

AMRCC1M_08

TT

I need to be able to use both the entire string and just the letters before the first number while running the code (i.e. var1=RRR14 and var2=RRR), but I'm unsure how to extract just the leading letters since the length and values are different for each string. Also since there isn't guaranteed to be a number in the string, I'm not sure how to go about it.

EDIT: Using the suggested solution, I have a new problem. It seems that var2 isn't updating correctly. I run the code:

for /f "tokens=1" %%a in (%1.txt) do (
for /f "tokens=1 delims=0123456789" %%G in ("%%a") do set var2=%%G
echo %var2%
echo %%a
echo.
)

with all the ECHO's to try to debug and I get:

>set var2=RRR
JIKK
RRR14

where JIKK seems to come from JIKK8 (the last line in the text file). Not sure if I'm referencing the variable incorrectly or what's not working here

Body:
You can use a FOR /F command and use all 10 numbers as the DELIMS options.

So in your example.

FOR /F "TOKENS=1 delims=0123456789" %%G IN ("RRR14") DO SET var2=%%G

So based on the new code you updated within your question you have two options.

The first option is to just create another parenthesized code block and use the FOR variable directly.

@ECHO OFF
for /f "tokens=1" %%a in (%1.txt) do (
    for /f "tokens=1 delims=0123456789" %%G in ("%%a") do (
        echo %G%
        echo %%a
        echo.
    )
)

Your second option is to use delayed expansion to reference the variable without an additional parenthesized code block.

@ECHO OFF
setlocal enabledelayedexpansion
for /f "tokens=1" %%a in (%1.txt) do (
    for /f "tokens=1 delims=0123456789" %%G in ("%%a") do set "var2=%%G"
    echo !var2!
    echo %%a
    echo.
)


问:
Send Ajax request with custom cookies to another domain
I have a target URL from server , and want to send some parameter with specific cookies to it, via Ajax in Chrome browser.

Response header of server of target URL (I don't have access to server for any change config or change scripts on it) :

```<code>Cache-Control:max-age=600, private, must-revalidate
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Encoding:gzip
Content-Length:6821
Content-Type:text/html
Date:Thu, 16 Nov 2017 22:50:17 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:Apache
Vary:Accept-Encoding
X-Powered-By:PHP/5.5.38
</code>```

I started for it!

Firstly I try CURL for test access. This works so there is a need for server access and there is no need to set a specific header:

```<code>curl 'http://www.foo.com/bar.php' \
     -H 'Cookie: PHPSESSID=vjjuo34g4gh46ajd471lt8pvn7;' \
     --data 'x=1&y=2' --compressed -s
</code>```

It is only important that the PHPSESSID cookie is sent.

Response: correct, and has access.

See:

Now I try Ajax and the Chrome browser locally:

```<code>$.ajax({
    type: "POST",
    ContentType: "application/json; charset=UTF-8",
    dataType: "json",
    data: {x : '1', y: '2'},
    url: 'http://www.foo.com/bar.php',
    complete: function(data) {
        console.log('RESPONSE TEXT>>>>>>>>', data.responseText);
    }
});
</code>```

I receive the following error message:

Failed to load http://www.foo.com/bar.php: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8888' is therefore not allowed
  access.

See:

I activate the Allow-Control-Allow-Origin chrome extension and run it again.

This time it works. But there is no access because the cookie is not sent.

Response: incorrect, and has not access.

See:

Add a cookie to the Ajax request header:

```<code>beforeSend : function(xhr) {
    xhr.setRequestHeader('Cookie', 'PHPSESSID=vjjuo34g4gh46ajd471lt8pvn7;');
},
</code>```

The cookie is not set and the error appears in the console, Error:

Refused to set unsafe header "Cookie"

Response: incorrect, and has not access.

See:

We add this to the Ajax request to allow us to add a cookie:

```<code>xhrFields: {
    withCredentials: true,
},
</code>```

What happens is that my preferred cookie is not set. But the pre-configured cookies are set to my domain for the requested domain.

(We assume that these are the same cookies that are not the issue.)

But this time the following message appears in the console:

Failed to load http://www.foo.com/bar.php: The value of the
  'Access-Control-Allow-Origin' header in the response must not be the
  wildcard '*' when the request's credentials mode is 'include'. Origin
  'http://localhost:8888' is therefore not allowed access. The
  credentials mode of requests initiated by the XMLHttpRequest is
  controlled by the withCredentials attribute.

Response: correct, but return EMPTY!!! WHY?!

See:

You see that the request contained cookies that were required. But the correct response was not received at data.responseText and JavaScript.

But it is strange that the Developer Tools> Network> Response response text is shown correctly.

Why is this happening and how can I finally get the correct response like CURL request of the first above image?

EDIT:

Output of console.log(data) command. see here:

Seem the red message was changed in this time! and also seem some time to load response data failed in Response tab of chrome!

答:
Header Access-Control-Allow-Origin is set in the server. For receiving a reponse from the server using AJAX you need to add a value to Access-Control-Allow-Origin header that doesn't be the a wildcard *.

I can see you are making a test from your localhost. If you set Access-Control-Allow-Origin: http://localhost/ it won't work. If you can test from your server it may work.

What you can do is a test from a site where you have a domain, and add Access-Control-Allow-Origin: domain to the response.

If you need more information about this topic I recommend you this site:

https://developer.mozilla.org/es/docs/Web/HTTP/Access_control_CORS

Body:
I have a target URL from server , and want to send some parameter with specific cookies to it, via Ajax in Chrome browser.

Response header of server of target URL (I don't have access to server for any change config or change scripts on it) :

Cache-Control:max-age=600, private, must-revalidate
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Encoding:gzip
Content-Length:6821
Content-Type:text/html
Date:Thu, 16 Nov 2017 22:50:17 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:Apache
Vary:Accept-Encoding
X-Powered-By:PHP/5.5.38

I started for it!

Firstly I try CURL for test access. This works so there is a need for server access and there is no need to set a specific header:

curl 'http://www.foo.com/bar.php' \
     -H 'Cookie: PHPSESSID=vjjuo34g4gh46ajd471lt8pvn7;' \
     --data 'x=1&y=2' --compressed -s

It is only important that the PHPSESSID cookie is sent.

Response: correct, and has access.

See:

Now I try Ajax and the Chrome browser locally:

$.ajax({
    type: "POST",
    ContentType: "application/json; charset=UTF-8",
    dataType: "json",
    data: {x : '1', y: '2'},
    url: 'http://www.foo.com/bar.php',
    complete: function(data) {
        console.log('RESPONSE TEXT>>>>>>>>', data.responseText);
    }
});

I receive the following error message:

Failed to load http://www.foo.com/bar.php: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8888' is therefore not allowed
  access.

See:

I activate the Allow-Control-Allow-Origin chrome extension and run it again.

This time it works. But there is no access because the cookie is not sent.

Response: incorrect, and has not access.

See:

Add a cookie to the Ajax request header:

beforeSend : function(xhr) {
    xhr.setRequestHeader('Cookie', 'PHPSESSID=vjjuo34g4gh46ajd471lt8pvn7;');
},

The cookie is not set and the error appears in the console, Error:

Refused to set unsafe header "Cookie"

Response: incorrect, and has not access.

See:

We add this to the Ajax request to allow us to add a cookie:

xhrFields: {
    withCredentials: true,
},

What happens is that my preferred cookie is not set. But the pre-configured cookies are set to my domain for the requested domain.

(We assume that these are the same cookies that are not the issue.)

But this time the following message appears in the console:

Failed to load http://www.foo.com/bar.php: The value of the
  'Access-Control-Allow-Origin' header in the response must not be the
  wildcard '*' when the request's credentials mode is 'include'. Origin
  'http://localhost:8888' is therefore not allowed access. The
  credentials mode of requests initiated by the XMLHttpRequest is
  controlled by the withCredentials attribute.

Response: correct, but return EMPTY!!! WHY?!

See:

You see that the request contained cookies that were required. But the correct response was not received at data.responseText and JavaScript.

But it is strange that the Developer Tools> Network> Response response text is shown correctly.

Why is this happening and how can I finally get the correct response like CURL request of the first above image?

EDIT:

Output of console.log(data) command. see here:

Seem the red message was changed in this time! and also seem some time to load response data failed in Response tab of chrome!


问:
Using \COPY to load CSV with JSON fields into Postgres
I'm attempting to load TSV data from a file into a Postgres table using the \COPY command.

Here's an example data row:

```<code>2017-11-22 23:00:00     "{\"id\":123,\"class\":101,\"level\":3}"
</code>```

Here's the psql command I'm using:

```<code>\COPY bogus.test_table (timestamp, sample_json) FROM '/local/file.txt' DELIMITER E'\t'
</code>```

Here's the error I'm receiving:

```<code>ERROR:  invalid input syntax for type json
DETAIL:  Token "sample_json" is invalid.
CONTEXT:  JSON data, line 1: "{"sample_json...
COPY test_table, line 1, column sample_json: ""{\"id\":123,\"class\":101,\"level\":3}""
</code>```

I verified the JSON is in the correct JSON format and read a couple similar questions, but I'm still not sure what's going on here. An explanation would be awesome

答:
Your json is quoted. It shouldn't have surrounding " characters, and the " characters surrounding the field names shouldn't be escaped.

It should look like this:

```<code>2017-11-22 23:00:00 {"id":123,"class":101,"level":3}
</code>```

Body:
I'm attempting to load TSV data from a file into a Postgres table using the \COPY command.

Here's an example data row:

2017-11-22 23:00:00     "{\"id\":123,\"class\":101,\"level\":3}"

Here's the psql command I'm using:

\COPY bogus.test_table (timestamp, sample_json) FROM '/local/file.txt' DELIMITER E'\t'

Here's the error I'm receiving:

ERROR:  invalid input syntax for type json
DETAIL:  Token "sample_json" is invalid.
CONTEXT:  JSON data, line 1: "{"sample_json...
COPY test_table, line 1, column sample_json: ""{\"id\":123,\"class\":101,\"level\":3}""

I verified the JSON is in the correct JSON format and read a couple similar questions, but I'm still not sure what's going on here. An explanation would be awesome

Body:
Your json is quoted. It shouldn't have surrounding " characters, and the " characters surrounding the field names shouldn't be escaped.

It should look like this:

2017-11-22 23:00:00 {"id":123,"class":101,"level":3}


问:
#Floydhub - Can't Close the browser while the code is running
While i'm running a code script on FloyHub using Jupyter, i can't close the browser tab while it's running. as in the image below

so, how can i close the browser while the code is running ?

Thanks

答: This is, unfortunately, a problem with Jupyter Notebooks itself: https://github.com/jupyter/notebook/issues/1647. In general, since Notebooks are interactive development environments, its good practice to keep the browser open. Otherwise, it's too easy to forgot that you have a running job and then be charged for the duration it is idle.</p>


问:
Fast combination of elements in a list in R
I am trying to find an efficient way to extract all pairwise combinations of vectors stored in a list. The purpose of this code is to compute the average correlation of all possible pairwise combinations of data vector, within a resampling procedure with 100000 iterations.

```<code> # Data simulation
 set.seed(90)
 dummy_data <- matrix(runif(21120),33,640)
 dummy_list <- vector("list",length = 33)
 for (i in 1:33){
  dummy_list[[i]] <- dummy_data[i,]
 }
</code>```

The solution I have found so far is:

```<code>n_iter <- 100000
cor_out <- vector("numeric",length = n_iter)

# For each iteration
for (z in 1:n_iter){

 # Randomly shuffle the data
 dummy_list_resample <- lapply(dummy_list, FUN = function(x){sample(x,size = 640)})
 all_ind <- length(dummy_list_resample)
 combs <- combn(all_ind,2)

 # Initialize list for storing all pairwise observations
 out_list <- vector("list",length(dim(combs)[2]))

 # For each pairwise combination
 for(i in 1:dim(combs)[2]){

   # Identify and extract the data for each pair of subject
   pair <- combs[,i]
   vec1 <- dummy_list_resample[[pair[1]]]
   vec2 <- dummy_list_resample[[pair[2]]]

   out_list[[i]] <- cbind(vec1,vec2)
 }

 # Compute correlation for each pairwise combination
 # and store the average value
 cor_iter <- sapply(out_list, FUN = function(x){cor(x[,1],x[,2])})
 cor_out[z] <- mean(cor_iter)
}
</code>```

which I found rather inefficient because it is really slow (~12 h of computing)

Is there a way to avoid the loop? I am aware of Rcpp as way to speed up iterations, but unfortunately I am not familiar with C++. Any hint or example would be greatly appreciated.

答:
You can concatenate into a matrix, and the cor function takes in a matrix and calculates the pairwise correlation of all columns.

Your original approach:

```<code>list_cor <- function(seed=1) {
  set.seed(seed)
  dummy_list_resample <- lapply(dummy_list, FUN = function(x){sample(x,size = 640)})
  all_ind <- length(dummy_list_resample)
  combs <- combn(all_ind,2)
  # Initialize list for storing all pairwise observations
  out_list <- vector("list",length(dim(combs)[2]))

  # For each pairwise combination
  for(i in 1:dim(combs)[2]){

    # Identify and extract the data for each pair of subject
    pair <- combs[,i]
    vec1 <- dummy_list_resample[[pair[1]]]
    vec2 <- dummy_list_resample[[pair[2]]]

    out_list[[i]] <- cbind(vec1,vec2)
  }

  # Compute correlation for each pairwise combination
  # and store the average value
  cor_iter <- sapply(out_list, FUN = function(x){cor(x[,1],x[,2])})
  mean(cor_iter)
}
</code>```

Matrix approach:

```<code>mat_cor <- function(seed=1) {
  set.seed(seed)
  dummy_list_resample <- lapply(dummy_list, FUN = function(x){sample(x,size = 640)})
  dummy_mat <- do.call(cbind, dummy_list_resample)
  cmat <- cor(dummy_mat)
  mean(cmat[lower.tri(cmat)])
}
</code>```

Speed test:

```<code>library(microbenchmark)
microbenchmark(sapply(1:10, mat_cor), sapply(1:10, list_cor), times=10)

Unit: milliseconds
                   expr      min        lq      mean    median        uq       max neval cld
  sapply(1:10, mat_cor)  17.7916  19.00319  20.43652  20.68327  21.89248  22.72629    10  a
 sapply(1:10, list_cor) 609.1673 622.57560 631.03171 628.26800 633.77480 673.58373    10   b
</code>```

A speed up of ~31.5 times faster.

You can check the results are the same (there is a very small irrelevant difference due to floating point accuracy):

```<code>> mat_cor(1)
[1] 3.210217e-05
> list_cor(1)
[1] 3.210217e-05
</code>```

If you still need more speed up after this, I suggest next looking into the parallel package.

Body:
I am trying to find an efficient way to extract all pairwise combinations of vectors stored in a list. The purpose of this code is to compute the average correlation of all possible pairwise combinations of data vector, within a resampling procedure with 100000 iterations.

 # Data simulation
 set.seed(90)
 dummy_data <- matrix(runif(21120),33,640)
 dummy_list <- vector("list",length = 33)
 for (i in 1:33){
  dummy_list[[i]] <- dummy_data[i,]
 }

The solution I have found so far is:

n_iter <- 100000
cor_out <- vector("numeric",length = n_iter)

# For each iteration
for (z in 1:n_iter){

 # Randomly shuffle the data
 dummy_list_resample <- lapply(dummy_list, FUN = function(x){sample(x,size = 640)})
 all_ind <- length(dummy_list_resample)
 combs <- combn(all_ind,2)

 # Initialize list for storing all pairwise observations
 out_list <- vector("list",length(dim(combs)[2]))

 # For each pairwise combination
 for(i in 1:dim(combs)[2]){

   # Identify and extract the data for each pair of subject
   pair <- combs[,i]
   vec1 <- dummy_list_resample[[pair[1]]]
   vec2 <- dummy_list_resample[[pair[2]]]

   out_list[[i]] <- cbind(vec1,vec2)
 }

 # Compute correlation for each pairwise combination
 # and store the average value
 cor_iter <- sapply(out_list, FUN = function(x){cor(x[,1],x[,2])})
 cor_out[z] <- mean(cor_iter)
}

which I found rather inefficient because it is really slow (~12 h of computing)

Is there a way to avoid the loop? I am aware of Rcpp as way to speed up iterations, but unfortunately I am not familiar with C++. Any hint or example would be greatly appreciated.

Body:
You can concatenate into a matrix, and the cor function takes in a matrix and calculates the pairwise correlation of all columns.

Your original approach:

list_cor <- function(seed=1) {
  set.seed(seed)
  dummy_list_resample <- lapply(dummy_list, FUN = function(x){sample(x,size = 640)})
  all_ind <- length(dummy_list_resample)
  combs <- combn(all_ind,2)
  # Initialize list for storing all pairwise observations
  out_list <- vector("list",length(dim(combs)[2]))

  # For each pairwise combination
  for(i in 1:dim(combs)[2]){

    # Identify and extract the data for each pair of subject
    pair <- combs[,i]
    vec1 <- dummy_list_resample[[pair[1]]]
    vec2 <- dummy_list_resample[[pair[2]]]

    out_list[[i]] <- cbind(vec1,vec2)
  }

  # Compute correlation for each pairwise combination
  # and store the average value
  cor_iter <- sapply(out_list, FUN = function(x){cor(x[,1],x[,2])})
  mean(cor_iter)
}

Matrix approach:

mat_cor <- function(seed=1) {
  set.seed(seed)
  dummy_list_resample <- lapply(dummy_list, FUN = function(x){sample(x,size = 640)})
  dummy_mat <- do.call(cbind, dummy_list_resample)
  cmat <- cor(dummy_mat)
  mean(cmat[lower.tri(cmat)])
}

Speed test:

library(microbenchmark)
microbenchmark(sapply(1:10, mat_cor), sapply(1:10, list_cor), times=10)

Unit: milliseconds
                   expr      min        lq      mean    median        uq       max neval cld
  sapply(1:10, mat_cor)  17.7916  19.00319  20.43652  20.68327  21.89248  22.72629    10  a
 sapply(1:10, list_cor) 609.1673 622.57560 631.03171 628.26800 633.77480 673.58373    10   b

A speed up of ~31.5 times faster.

You can check the results are the same (there is a very small irrelevant difference due to floating point accuracy):

> mat_cor(1)
[1] 3.210217e-05
> list_cor(1)
[1] 3.210217e-05

If you still need more speed up after this, I suggest next looking into the parallel package.


问:
3-Tier BizTalk Architecture Possible?
According to this BizTalk documentation, the HTTP receive adapter must be in the application (middle) layer. This means BizTalk is limited to a 2-tier architecture, which for modern enterprises is a pretty big limitation.

Is the reverse proxy suggestion that Microsoft recommends (on the link above) the common solution to this problem? Has anyone used any other configuration to use the HTTP receive adapter in the web/perimeter layer and been able to negotiate messages through an application layer?

If the reverse proxy method was used, were existing proxy's in the enterprise used or were dedicated proxy's configured for the solution?

答: These days it is becoming more common practice to expose the web service via Azure Service Bus Relay or API in Azure. But yes, it is was common to expose your BizTalk web service via a reverse proxy with proper security in place. If you place your BizTalk server in the DMZ, you have to poke a lot of holes from BizTalk to your internal systems, which is what you want to avoid.</p>

Title: 3-Tier BizTalk Architecture Possible?


问:
Iterating through JSON objects even if key is missing
I have a JSON have the following data:

```<code>        {
       "results":[
          {
             "name":"Sydney Showboats",
             "photos":[
                {
                   "photo_reference":"Pic062"
                }
             ]
          },
          {
             "name":"Blue Line Cruises"
          },
          {
             "name":"Rhythmboat Cruises",
             "photos":[
                {
                   "photo_reference":"Pic678"
                }
             ]
          },
          {
             "name":"Flying Fish Restaurant & Bar",
             "photos":[
                {
                   "photo_reference":"Pic345"
                }
             ]
          }
       ],
       "status":"OK"
    }
</code>```

I'm trying to loop through this JSON to display every name value in the .name div and every image in the .photo div:

```<code>$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    $('.name').html('<p>' + data.results[index].name + '</p>');
    $('.photo').html('<img src="' + data.results[index].photos[0].photo_reference + '.jpg">');
  })
});
</code>```

It works fine with the name value and works fine with the first image too. However, since there is no "photos" property in the second object, the script stops because of an

Uncaught TypeError: Cannot read property '0' of undefined.

So is there a way to either:
Delete the objects which do not have the photos object nested inside?
Use a more complex loop to iterate through the JSON and store every image available?
Any possible solution allowing me to display every image available dynamically?

If anyone can enlighten me it would be gratefully appreciated!

答:
You want to make sure that the current object in the iteration contains that property. One way to check if an object contains a property is using the in operator.

```<code>$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    if ('photos' in data.results[index] && 'name' in data.results[index]){
      $('.name').html('<p>' + data.results[index].name + '</p>');
      $('.photo').html('<img src="' +
      data.results[index].photos[0].photo_reference + '.jpg">');
    }
 })
</code>```

});

Documentation for in operator

Body:
I have a JSON have the following data:

        {
       "results":[
          {
             "name":"Sydney Showboats",
             "photos":[
                {
                   "photo_reference":"Pic062"
                }
             ]
          },
          {
             "name":"Blue Line Cruises"
          },
          {
             "name":"Rhythmboat Cruises",
             "photos":[
                {
                   "photo_reference":"Pic678"
                }
             ]
          },
          {
             "name":"Flying Fish Restaurant & Bar",
             "photos":[
                {
                   "photo_reference":"Pic345"
                }
             ]
          }
       ],
       "status":"OK"
    }

I'm trying to loop through this JSON to display every name value in the .name div and every image in the .photo div:

$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    $('.name').html('
' + data.results[index].name + '
');
    $('.photo').html('');
  })
});

It works fine with the name value and works fine with the first image too. However, since there is no "photos" property in the second object, the script stops because of an

Uncaught TypeError: Cannot read property '0' of undefined.

So is there a way to either:
Delete the objects which do not have the photos object nested inside?
Use a more complex loop to iterate through the JSON and store every image available?
Any possible solution allowing me to display every image available dynamically?

If anyone can enlighten me it would be gratefully appreciated!

Body:
You want to make sure that the current object in the iteration contains that property. One way to check if an object contains a property is using the in operator.

$.getJSON(jsonPlacesUrl, function(data) {
  $.each(data.results, function(index){
    if ('photos' in data.results[index] && 'name' in data.results[index]){
      $('.name').html('<p>' + data.results[index].name + '</p>');
      $('.photo').html('<img src="' +
      data.results[index].photos[0].photo_reference + '.jpg">');
    }
 })

});

Documentation for in operator


问:
For images, what is the benefit of using the name element? name="...."
I want to know what the difference is between alt="" and name=""

Would it be better to put the filename within the alt tag, or the description of the photo?

What makes better sense, both from SEO and validation stand-point?

答:
The alt attribute is intendet to supply an descriptive alternative in text form for the image. So if you have an image that shows a sunflower, you could use:

```<code><img src="sunflower.jpg" alt="image of a sunflower on a sunny day">
</code>```

The name attribute in intended to name the image for scripting so you can access it using images["sunflower"]. But nowadays you should use the id attribute instead.

OwnerDisplayName: Brad

ContentLicense: CC BY-SA 2.5

Body:
The alt attribute is intendet to supply an descriptive alternative in text form for the image. So if you have an image that shows a sunflower, you could use:

<img src="sunflower.jpg" alt="image of a sunflower on a sunny day">

The name attribute in intended to name the image for scripting so you can access it using images["sunflower"]. But nowadays you should use the id attribute instead.

OwnerDisplayName: Gumbo


问:
Chat module integration in code Igniter
i'm developing a website in codeigniter. In my site, i need to integrate live-chat like google chat option for my site user. Can you suggest me any chat code?</p>

答: Google Chat uses the XMPP protocol, you might wanna take a look at the docs. While not a CI solution, XMPPHP is a great class to get you up and running with XMPP. It wouldn't be to hard to port it to a CI library.</p>

Title: Chat module integration in code Igniter


问:
Return sums even if no data exist in given day
I have a table with amounts only on some days, e.g.:

```<code>[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123
</code>```

How can I query the data and get:

```<code>11/1/2017 $173
11/2/2017 $0
11/3/2017 $123
</code>```

I tried like:

```<code>SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);
</code>```

But still it doesn't return 0s for days without data, any ideas?

答:
I suggest you try the following query:</p>

```<code>SELECT DATE_FORMAT(date, "%b") AS month, SUM(total_price) as total
FROM table
WHERE date <= NOW()
and date >= Date_add(Now(),interval - 12 month)
GROUP BY DATE_FORMAT(date, "%m-%Y"))
</code>```

Body:
I have a table with amounts only on some days, e.g.:

[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123

How can I query the data and get:

11/1/2017 $173
11/2/2017 $0
11/3/2017 $123

I tried like:

SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);

But still it doesn't return 0s for days without data, any ideas?

Body:
I suggest you try the following query:

SELECT DATE_FORMAT(date, "%b") AS month, SUM(total_price) as total
FROM table
WHERE date <= NOW()
and date >= Date_add(Now(),interval - 12 month)
GROUP BY DATE_FORMAT(date, "%m-%Y"))


问:
Displaying nested data from network return using Parse Javascript SDK
I am obtaining the following response from my Parse Server using the Parse Javascript SDK:

Using the code below, I am successfully outputting the inventoryQTY into the stock variable, but cannot work out how to output GTIN_13 which is nested in Product_Temp?

```<code>for (i in results) {
    var stock = results[i].get("inventoryQty")
    var Barcode = results[i].get("GTIN_13");
    console.log("Stock is " + stock);
    console.log("Barcode is " + Barcode);
}
</code>```

I have also tried:

```<code>    var Barcode = results[i].get("Product_Temp.GTIN_13");
</code>```

答:
Use this code to get the value of GTIN_13:</p>

```<code>for (var i=0; i < results.length; i++) {
    var product = results[i].get('Product_Temp');

    for (var productIndex = 0; productIndex < product.length; productIndex++) {
       var barcode = product[productIndex].get('GTIN_13');
       // your code to process the barcode ...
    }
}
</code>```

Body:
I am obtaining the following response from my Parse Server using the Parse Javascript SDK:

Using the code below, I am successfully outputting the inventoryQTY into the stock variable, but cannot work out how to output GTIN_13 which is nested in Product_Temp?

for (i in results) {
    var stock = results[i].get("inventoryQty")
    var Barcode = results[i].get("GTIN_13");
    console.log("Stock is " + stock);
    console.log("Barcode is " + Barcode);
}

I have also tried:

    var Barcode = results[i].get("Product_Temp.GTIN_13");

Body:
Use this code to get the value of GTIN_13:

for (var i=0; i < results.length; i++) {
    var product = results[i].get('Product_Temp');

    for (var productIndex = 0; productIndex < product.length; productIndex++) {
       var barcode = product[productIndex].get('GTIN_13');
       // your code to process the barcode ...
    }
}


问:
Tabpanels within a form
I'm new to Bootstrap and I have a doubt. It is possible to put tabpanels within a form so I could divide the fields of the form in multiple tabpanels, use dynamic tabs and submit the form as just one form? As an example I have the code below.

Dados Pessoais

Dados Médicos

            <form role="form">

Dados Pessoais

                          Nome do Paciente
                          <input type="text" class="form-control" placeholder="Nome" required="true">

                          CPF
                          <input type="number" class="form-control" placeholder="CPF">

                          RG
                          <input type="number" class="form-control" placeholder="RG">

                          Data de Nascimento
                          <input type="date" class="form-control" placeholder="Data de Nascimento">

                          Sexo
                          <select class="form-control">
                            <option>Masculino</option>
                            <option>Feminino</option>
                          </select>

                          Estado Civil
                          <select class="form-control">
                            <option>Solteiro(a)</option>
                            <option>Casado(a)</option>
                            <option>Divorciado(a)</option>
                            <option>Viúvo(a)</option>
                          </select>

                          Nome do Cônjuge
                          <input type="text" class="form-control" placeholder="Nome do Cônjuge">

                          Endereço
                          <input type="text" class="form-control" placeholder="Endereço">

                          Bairro
                          <input type="text" class="form-control" placeholder="Bairro">

                          Cidade
                          <input type="text" class="form-control" placeholder="Cidade">

                          CEP
                          <input type="text" class="form-control" placeholder="CEP">

Dados Médicos

                          Nome do Paciente
                          <input type="text" class="form-control" placeholder="Nome">

                          CPF
                          <input type="number" class="form-control" placeholder="CPF">

                          RG
                          <input type="number" class="form-control" placeholder="RG">

                                  <button type="button" class="btn btn-primary">Anterior</button>
                                  <button type="button" class="btn btn-primary">Próximo</button>

                                  <button type="button" class="btn btn-danger">Cancelar</button>
                                  <button type="submit" class="btn btn-success">Cadastrar</button>
                                  <input type="button"  class="btn btn-success" value="Cadastrar">

            </form>

```

I want to have two tabpanels, so I can use the dynamic tabs, but I need to submit all fields as one form. It is possible? I've searched around about this subject and i've read a few guys saying that different forms can be send as just one if you serialize them with jQuery. It is a valid alternative in this case?

PS: I'm also new here in Stackoverflow, so if there's any mistake in the way I have made my question, please tell me so I can correct it. And the names of the fields are in Portuguese, because I'm Brazillian and I'm trying to make an application that will serve as a test. If the names difficult the comprehension, let me know, so I can translate it.

答:
You should be able to do this with JavaScript:

```<code> <input type="button" value="Click Me!" onclick="submitForms()" />
</code>```

If your forms have IDs:

```<code>submitForms = function(){
    document.getElementById("form1").submit();
    document.getElementById("form2").submit();
</code>```

}

Title: Tabpanels within a form

Body:
I'm new to Bootstrap and I have a doubt. It is possible to put tabpanels within a form so I could divide the fields of the form in multiple tabpanels, use dynamic tabs and submit the form as just one form? As an example I have the code below.

Dados Pessoais

Dados Médicos

            <form role="form">

Dados Pessoais

                          Nome do Paciente
                          <input type="text" class="form-control" placeholder="Nome" required="true">

                          CPF
                          <input type="number" class="form-control" placeholder="CPF">

                          RG
                          <input type="number" class="form-control" placeholder="RG">

                          Data de Nascimento
                          <input type="date" class="form-control" placeholder="Data de Nascimento">

                          Sexo
                          <select class="form-control">
                            <option>Masculino</option>
                            <option>Feminino</option>
                          </select>

                          Estado Civil
                          <select class="form-control">
                            <option>Solteiro(a)</option>
                            <option>Casado(a)</option>
                            <option>Divorciado(a)</option>
                            <option>Viúvo(a)</option>
                          </select>

                          Nome do Cônjuge
                          <input type="text" class="form-control" placeholder="Nome do Cônjuge">

                          Endereço
                          <input type="text" class="form-control" placeholder="Endereço">

                          Bairro
                          <input type="text" class="form-control" placeholder="Bairro">

                          Cidade
                          <input type="text" class="form-control" placeholder="Cidade">

                          CEP
                          <input type="text" class="form-control" placeholder="CEP">

Dados Médicos

                          Nome do Paciente
                          <input type="text" class="form-control" placeholder="Nome">

                          CPF
                          <input type="number" class="form-control" placeholder="CPF">

                          RG
                          <input type="number" class="form-control" placeholder="RG">

                                  <button type="button" class="btn btn-primary">Anterior</button>
                                  <button type="button" class="btn btn-primary">Próximo</button>

                                  <button type="button" class="btn btn-danger">Cancelar</button>
                                  <button type="submit" class="btn btn-success">Cadastrar</button>
                                  <input type="button"  class="btn btn-success" value="Cadastrar">

            </form>

I want to have two tabpanels, so I can use the dynamic tabs, but I need to submit all fields as one form. It is possible? I've searched around about this subject and i've read a few guys saying that different forms can be send as just one if you serialize them with jQuery. It is a valid alternative in this case?

PS: I'm also new here in Stackoverflow, so if there's any mistake in the way I have made my question, please tell me so I can correct it. And the names of the fields are in Portuguese, because I'm Brazillian and I'm trying to make an application that will serve as a test. If the names difficult the comprehension, let me know, so I can translate it.

Body:
You should be able to do this with JavaScript:

 <input type="button" value="Click Me!" onclick="submitForms()" />

If your forms have IDs:

submitForms = function(){
    document.getElementById("form1").submit();
    document.getElementById("form2").submit();

}


问:
json object from javascript nested array
I'm using a nested array with the following structure:

```<code>arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
</code>```

now I'm trying to get a nested Json Object from this array

```<code>arr{
 {
 id: example0,
 name: name00,
 },
{
 id: example1,
 name: name01,
 },
{
 id: example2,
 name: name02,
 }
}
</code>```

I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.

Thank you!

答:
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:

```<code>const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
</code>```

You first need to map it to an array of Objects.

```<code>const arrayOfObjects = array.map((el) => ({
  id: el[0],
  name: el[1]
}))
</code>```

Then you can call JSON.stringify(arrayOfObjects) to get the JSON.

Body:
I'm using a nested array with the following structure:

arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";

now I'm trying to get a nested Json Object from this array

arr{
 {
 id: example0,
 name: name00,
 },
{
 id: example1,
 name: name01,
 },
{
 id: example2,
 name: name02,
 }
}

I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.

Thank you!

Body:
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:

const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]

You first need to map it to an array of Objects.

const arrayOfObjects = array.map((el) => ({
  id: el[0],
  name: el[1]
}))

Then you can call JSON.stringify(arrayOfObjects) to get the JSON.


问:
Freemarker ignore missing variables
I'm using freemarker to generate files and I'm struggling with the templateExeptionHandler part. I have variables in my template that don't have to be replaced (if they are not present in the data-model). I don't like to put these variables inside my data-model with the same value (can't get it to work either) and I know I can 'escape' variables in the template itself but I don't really like that solution.

MyTemplateExceptionHandler looks as follows:

```<code>class MyTemplateExceptionHandler implements TemplateExceptionHandler {
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
  try {
    out.write("${" + te.getBlamedExpressionString() + "}");
  } catch (IOException e) {
    throw new TemplateException("Failed to print error message. Cause: " + e, env);
  }
}
</code>```

}

The problem is that once I'm parsing variables in the form of:

${workflow.input.myVariable}

the result in my new generated file is showing only the first part of this variable:

${workflow}

Any thoughts on how I can get the full variable back and returned in my generated file?

答: That use case is not supported, as of 2.3.27 at least. It's not even clear how it should work, like, what if the missing variable is a parameter to a directive? Certainly it could be solved for the case of ${} only (even then, only when it appears outside a string literal), but I'm not sure if that addresses the need, or it just lures uses into using it and then they hit a wall later on with a directive parameter... (Or, another tricky case, what's with ${thisIsMissing + thisExists}? I guess it should become to something like ${thisIsMissing + 123}... so doing this right can complicate the core quite much.)

Title: Freemarker ignore missing variables

Body:
I'm using freemarker to generate files and I'm struggling with the templateExeptionHandler part. I have variables in my template that don't have to be replaced (if they are not present in the data-model). I don't like to put these variables inside my data-model with the same value (can't get it to work either) and I know I can 'escape' variables in the template itself but I don't really like that solution.

MyTemplateExceptionHandler looks as follows:

class MyTemplateExceptionHandler implements TemplateExceptionHandler {
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
  try {
    out.write("${" + te.getBlamedExpressionString() + "}");
  } catch (IOException e) {
    throw new TemplateException("Failed to print error message. Cause: " + e, env);
  }
}

}

The problem is that once I'm parsing variables in the form of:

${workflow.input.myVariable}

the result in my new generated file is showing only the first part of this variable:

${workflow}

Any thoughts on how I can get the full variable back and returned in my generated file?


问:
PySpark application creates many pyspark-shell sessions
I have started working on Spark using Python. I'm working on an application that uses SparkML Linear Regression APIs. When I submit my job in YARN cluster mode, during the execution phase, many pyspark-shell apps get created with YARN as the user. I could see them in the YARN UI. They eventually get finished with succeeded status and my main application which I actually submitted then gets finished with succeeded status. Is this an expected behavior? This is kinda interesting to me since I create the singleton sparkSession instance and use it throughout my application so I don't know why pyspark-shell sessions/apps get created.</p>

答:
The immediate solution would be to use sparkContext instead of sparkSession. But it would be interesting to see your configuration lines to see how you're creating your sessions to be able to tell why multiple apps are being created.

We just updated to Spark 2.2 from Spark 1.6, so we have yet to delve seriously into sparkSessions (which are new in 2+).


问:
Awkward spacing between 2 column list items
I have a list of ingredients in a two-column layout, using flex-box. When an ingredient is long enough to cause the text to break to a second line, it causes awkward vertical spacing between the list items in the adjacent column. Before using flex-box, I tried using making the list items inline-blocks and floated them.

Here's what it looks like on my website:

Here's what my code looks like:

.field-items {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.field-item {
  width: 50%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="field-items">
  <div class="field-item even">
    8 ounces sugar snap peas, stringed </div>
  <div class="field-item odd">
    12 grape tomatoes, halved </div>
  <div class="field-item even">2 tablespoons sliced almonds</div>
  <div class="field-item odd">2 tablespoons extra-virgin olive, walnut, or almond oil</div>
  <div class="field-item even">
    2 tablespoons fruity vinegar, such as raspberry or pomegranate </div>
  <div class="field-item odd">
    ¼ teaspoon salt </div>
  <div class="field-item even">
    1/8 teaspoon freshly ground pepper </div>
  <div class="field-item odd">
    4 cups packed mixed baby lettuce </div>
  <div class="field-item even">
    ¼ cup snipped fresh chives (½-inch pieces) </div>
  <div class="field-item odd">
    ¼ cup chopped fresh tarragon </div>
</div></code>```

See it in action: https://jsfiddle.net/4t4pd3tt/2/

My goal is to have even spacing between all of the list elements. I'm sure this question has already been answered before, but I wasn't able to find what I was looking for in my initial search.

答:
To make that work using Flexbox, you need amongst other, to use flex-direction: column and give the flex container a fixed height.

Instead, for column layouts, CSS Columns is the proper way.

Stack snippet

.field-items {
  -moz-column-count: 2;
  -webkit-column-count: 2;
  column-count: 2;
}

.field-item {
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="field-items">
  <div class="field-item">
    8 ounces sugar snap peas, stringed </div>
  <div class="field-item">
    12 grape tomatoes, halved </div>
  <div class="field-item">2 tablespoons sliced almonds</div>
  <div class="field-item">2 tablespoons extra-virgin olive, walnut, or almond oil</div>
  <div class="field-item">
    2 tablespoons fruity vinegar, such as raspberry or pomegranate </div>
  <div class="field-item">
    ¼ teaspoon salt </div>
  <div class="field-item">
    1/8 teaspoon freshly ground pepper </div>
  <div class="field-item">
    4 cups packed mixed baby lettuce </div>
  <div class="field-item">
    ¼ cup snipped fresh chives (½-inch pieces) </div>
  <div class="field-item">
    ¼ cup chopped fresh tarragon </div>
</div></code>```

Body:
I have a list of ingredients in a two-column layout, using flex-box. When an ingredient is long enough to cause the text to break to a second line, it causes awkward vertical spacing between the list items in the adjacent column. Before using flex-box, I tried using making the list items inline-blocks and floated them.

Here's what it looks like on my website:

Here's what my code looks like:

.field-items {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.field-item {
  width: 50%;
  float: left;
}

    8 ounces sugar snap peas, stringed

    12 grape tomatoes, halved

2 tablespoons sliced almonds

2 tablespoons extra-virgin olive, walnut, or almond oil

    2 tablespoons fruity vinegar, such as raspberry or pomegranate

    ¼ teaspoon salt

    1/8 teaspoon freshly ground pepper

    4 cups packed mixed baby lettuce

    ¼ cup snipped fresh chives (½-inch pieces)

    ¼ cup chopped fresh tarragon

See it in action: https://jsfiddle.net/4t4pd3tt/2/

My goal is to have even spacing between all of the list elements. I'm sure this question has already been answered before, but I wasn't able to find what I was looking for in my initial search.

Body:
To make that work using Flexbox, you need amongst other, to use flex-direction: column and give the flex container a fixed height.

Instead, for column layouts, CSS Columns is the proper way.

Stack snippet

.field-items {
  -moz-column-count: 2;
  -webkit-column-count: 2;
  column-count: 2;
}

.field-item {
}

<div class="field-items">
  <div class="field-item">
    8 ounces sugar snap peas, stringed </div>
  <div class="field-item">
    12 grape tomatoes, halved </div>
  <div class="field-item">2 tablespoons sliced almonds</div>
  <div class="field-item">2 tablespoons extra-virgin olive, walnut, or almond oil</div>
  <div class="field-item">
    2 tablespoons fruity vinegar, such as raspberry or pomegranate </div>
  <div class="field-item">
    ¼ teaspoon salt </div>
  <div class="field-item">
    1/8 teaspoon freshly ground pepper </div>
  <div class="field-item">
    4 cups packed mixed baby lettuce </div>
  <div class="field-item">
    ¼ cup snipped fresh chives (½-inch pieces) </div>
  <div class="field-item">
    ¼ cup chopped fresh tarragon </div>
</div>


问:
Visual Studio displaying errors even if projects build
I have a problem with Visual Studio on a C# solution. It displays totally random errors, but the projects build. Right now, I have 33 files with errors, and I can see red squiggly lines in all of them.

I tried cleaning / rebuilding the solution, closing Visual Studio and even restarting my computer. I can modify .cs files and I see the changes in the solution.

Does anyone have an idea about why it does that?

答:
Ran into this issue with a single type not being recognized by Visual Studio which showed the red squiggle even though the solution built successfully. I noticed in the Solution Explorer the file did not have the expand arrow on the left which shows classes and properties on expansion.

The fix was to Exclude the file from the project and save/build which produced an expected error and then Include the file in the project and save and build.

After performing these steps Visual Studio started to recognize my type again. Looking at the diff in git it appears the issue was due to line endings not matching on the <Compile Include="..." /> line of my .csproj file.


问:
GLassfish error in log port 1527
Hi i have this error message :

Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused

when im doing a deploy, my EAR reaches 50% and it goes back to 0, and I get this error, does anyone know why it happens? im missing some configuration?

Help me please!!!

答: You need to start the JavaDB that is default DB on glassfish. Navigate to glassfish4/javadb/bin and run startNetworkServer script to start the db on port 1527</p>

Title: GLassfish error in log port 1527


问:
returning a pointer that points to char array. How do i print out the entire contents of the array?
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

```<code>#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //
</code>```

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

答:
For starters it does not make sense to declare an object of the type std::string and then to try to reverse it as a character array.

And moreover the header that contains declarations of standard C functions is named like <cstring>.

Also you need to include the header that contains the definition of the class std::string.

So the headers should be

```<code>#include <iostream>
#include <string>
#include <cstring>
</code>```

However a question arises: why not to use the same object of the type std::string instead of interpreting it as a character array?

Your approach even if to make it to compile has in any case bugs. Due to this statement

```<code>str = ReverseString(&str[0]);
</code>```

there is a memory leak. And moreover the returned string is not zero-terminated.

Thus the program has undefined behavior.

In fact what you are trying to do is to copy one string in another string in the reversed order.

Using objects of the type std::string the task can be done in one line.

For example

```<code>#include <iostream>
#include <string>

int main()
{
    std::string s("Hello, World!");
    std::string t( s.rbegin(), s.rend() );

    std::cout << s << std::endl;
    std::cout << t << std::endl;

    return 0;
}
</code>```

The program output is

```<code>Hello, World!
!dlroW ,olleH
</code>```

if you want to reverse the original string then you could write

```<code>#include <iostream>
#include <string>

int main()
{
    std::string s("Hello, World!");

    std::cout << s << std::endl;

    s.assign( s.rbegin(), s.rend() );

    std::cout << s << std::endl;

    return 0;
}
</code>```

You can write a separate function the following way

```<code>#include <iostream>
#include <string>

std::string ReverseCopyString( const std::string &s )
{
    return { s.rbegin(), s.rend() };
}

int main()
{
    std::string s("Hello, World!");
    std::string t = ReverseCopyString( s );

    std::cout << s << std::endl;
    std::cout << t << std::endl;

    return 0;
}
</code>```

Take into account that there is standard algorithm std::reverse_copy that does the same task. Or if you want to reverse the original string then you can use the algorithm std::reverse.

For example

```<code>#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>

int main()
{
    std::string s("Hello, World!");
    std::string t;
    t.reserve(s.size());

    std::reverse_copy(s.begin(), s.end(), std::back_inserter(t));

    std::cout << s << std::endl;
    std::cout << t << std::endl;

    return 0;
}
</code>```

If you want to deal with character arrays then the original string should also be stored in a character array.

```<code>#include <iostream>
#include <string>
#include <cstring>

char * ReverseCopyString(const char *s)
{
    size_t n = std::strlen(s);

    char *t = new char[n + 1];

    size_t i = 0;

    for (; i != n; i++) t[i] = s[n - 1 - i];

    t[i] = '\0';

    return t;
}

int main()
{
    const size_t N = 100;
    char s[N];

    std::cout << "Please Enter a String: ";
    std::cin.getline(s, sizeof( s ) );

    std::cout << "The string you entered is: " << s << std::endl;

    char *t = ReverseCopyString( s );

    std::cout << t << std::endl;

    delete []t;

    return 0;
}
</code>```

The program output might look like

```<code>Please Enter a String: Hello, World!
The string you entered is: Hello, World!
!dlroW ,olleH
</code>```

Body:
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

Body:
For starters it does not make sense to declare an object of the type std::string and then to try to reverse it as a character array.

And moreover the header that contains declarations of standard C functions is named like <cstring>.

Also you need to include the header that contains the definition of the class std::string.

So the headers should be

#include <iostream>
#include <string>
#include <cstring>

However a question arises: why not to use the same object of the type std::string instead of interpreting it as a character array?

Your approach even if to make it to compile has in any case bugs. Due to this statement

str = ReverseString(&str[0]);

there is a memory leak. And moreover the returned string is not zero-terminated.

Thus the program has undefined behavior.

In fact what you are trying to do is to copy one string in another string in the reversed order.

Using objects of the type std::string the task can be done in one line.

For example

#include <iostream>
#include <string>

int main()
{
    std::string s("Hello, World!");
    std::string t( s.rbegin(), s.rend() );

    std::cout << s << std::endl;
    std::cout << t << std::endl;

    return 0;
}

The program output is

Hello, World!
!dlroW ,olleH

if you want to reverse the original string then you could write

#include <iostream>
#include <string>

int main()
{
    std::string s("Hello, World!");

    std::cout << s << std::endl;

    s.assign( s.rbegin(), s.rend() );

    std::cout << s << std::endl;

    return 0;
}

You can write a separate function the following way

#include <iostream>
#include <string>

std::string ReverseCopyString( const std::string &s )
{
    return { s.rbegin(), s.rend() };
}

int main()
{
    std::string s("Hello, World!");
    std::string t = ReverseCopyString( s );

    std::cout << s << std::endl;
    std::cout << t << std::endl;

    return 0;
}

Take into account that there is standard algorithm std::reverse_copy that does the same task. Or if you want to reverse the original string then you can use the algorithm std::reverse.

For example

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>

int main()
{
    std::string s("Hello, World!");
    std::string t;
    t.reserve(s.size());

    std::reverse_copy(s.begin(), s.end(), std::back_inserter(t));

    std::cout << s << std::endl;
    std::cout << t << std::endl;

    return 0;
}

If you want to deal with character arrays then the original string should also be stored in a character array.

#include <iostream>
#include <string>
#include <cstring>

char * ReverseCopyString(const char *s)
{
    size_t n = std::strlen(s);

    char *t = new char[n + 1];

    size_t i = 0;

    for (; i != n; i++) t[i] = s[n - 1 - i];

    t[i] = '\0';

    return t;
}

int main()
{
    const size_t N = 100;
    char s[N];

    std::cout << "Please Enter a String: ";
    std::cin.getline(s, sizeof( s ) );

    std::cout << "The string you entered is: " << s << std::endl;

    char *t = ReverseCopyString( s );

    std::cout << t << std::endl;

    delete []t;

    return 0;
}

The program output might look like

Please Enter a String: Hello, World!
The string you entered is: Hello, World!
!dlroW ,olleH


问:
C++ weirdness with array initialization from brace-enclosed lists
I can't get the code below to compile with either GCC or Clang. Tried both C++11 and C++14.

My question:

Is there any logical reason for this not to be implemented? Myself, I can't think of any... See below for my workaround.

```<code>enum class fruit {
    APPLES,
    ORANGES,
    STRAWBERRIES
};
struct Area {float x, y, width, height;};
const Area test[] = {
    [fruit::APPLES] = {1,2,3,4},
    [fruit::ORANGES] = {2,2,3,4},
    [fruit::STRAWBERRIES] = {3,2,3,4}
};
</code>```

This though will compile just fine:

```<code>namespace fruit { // instead of enum class, this works
    enum {
            APPLES,
            ORANGES,
            STRAWBERRIES
    };
}
struct Area {float x, y, width, height;};
const Area test[] = {
    [fruit::APPLES] = {1,2,3,4},
    [fruit::ORANGES] = {2,2,3,4},
    [fruit::STRAWBERRIES] = {3,2,3,4}
};
</code>```

答:
Okay, so I will answer this myself from what I learned in the comments.

This is apparently called using "designated initializer" and it's a C99 feature, not a part of the C++ standard (even if it compiles in some cases):

```<code>int array[] = {
    [1] = 11,
    [0] = 22
};
</code>```

The code in my question compiles for me if I make these changes though:

```<code>[fruit::APPLES] = {1,2,3,4}
</code>```

Change into:

```<code>[(int)fruit::APPLES] = {1,2,3,4}
</code>```

Or into (the more correct way):

```<code>[static_cast<int>(fruit::APPLES)] = {1,2,3,4}
</code>```

But if you want to be standard compatible it's best not to use designated initializers and instead rewrite the code...

Body:
I can't get the code below to compile with either GCC or Clang. Tried both C++11 and C++14.

My question:

Is there any logical reason for this not to be implemented? Myself, I can't think of any... See below for my workaround.

enum class fruit {
    APPLES,
    ORANGES,
    STRAWBERRIES
};
struct Area {float x, y, width, height;};
const Area test[] = {
    [fruit::APPLES] = {1,2,3,4},
    [fruit::ORANGES] = {2,2,3,4},
    [fruit::STRAWBERRIES] = {3,2,3,4}
};

This though will compile just fine:

namespace fruit { // instead of enum class, this works
    enum {
            APPLES,
            ORANGES,
            STRAWBERRIES
    };
}
struct Area {float x, y, width, height;};
const Area test[] = {
    [fruit::APPLES] = {1,2,3,4},
    [fruit::ORANGES] = {2,2,3,4},
    [fruit::STRAWBERRIES] = {3,2,3,4}
};

Body:
Okay, so I will answer this myself from what I learned in the comments.

This is apparently called using "designated initializer" and it's a C99 feature, not a part of the C++ standard (even if it compiles in some cases):

int array[] = {
    [1] = 11,
    [0] = 22
};

The code in my question compiles for me if I make these changes though:

[fruit::APPLES] = {1,2,3,4}

Change into:

[(int)fruit::APPLES] = {1,2,3,4}

Or into (the more correct way):

[static_cast<int>(fruit::APPLES)] = {1,2,3,4}

But if you want to be standard compatible it's best not to use designated initializers and instead rewrite the code...