问:
How to write into a CSV file with Python
Background:

I have a CSV (csv_dump) file with data from a MySQL table. I want copy some of the lines that meet certain conditions (row[1] == condition_1 and row[2] == condition_2) into a temporary CSV file (csv_temp).

Code Snippet:

```<code>f_reader = open(csv_dump, 'r')
f_writer = open(csv_temp, 'w')
temp_file = csv.writer(f_writer)

lines_in_csv = csv.reader(f_reader, delimiter=',', skipinitialspace=False)

for row in lines_in_csv:

    if row[1] == condition_1 and row[2] == condition_2:
        temp_file.writerow(row)

f_reader.close()
f_writer.close()
</code>```

Question:

How can I copy the line that is being read copy it "as is" into the temp file with Python3?

答:
The following Python script seems to do the job... However, having said that, you should probably be using a MySQL query to do this work directly, instead of re-processing from an intermediate CSV file. But I guess there must be some good reason for wanting to do that?

mycsv.csv:

```<code>aa,1,2,5
bb,2,3,5
cc,ddd,3,3
hh,,3,1
as,hfd,3,3
</code>```

readwrite.py:

```<code>import csv

with open('mycsv.csv', 'rb') as infile:
    with open('out.csv', 'wb') as outfile:
        inreader = csv.reader(infile, delimiter=',', quotechar='"')
        outwriter = csv.writer(outfile)
        for row in inreader:
            if row[2]==row[3]:
                outwriter.writerow(row)
</code>```

out.csv:

```<code>cc,ddd,3,3
as,hfd,3,3
</code>```

With a little more work, you could change the 'csv.writer' to make use of the same delimiters and escape/quote characters as the 'csv.reader'. It's not exactly the same as writing out the raw line from the file, but I think it will be practically as fast since the lines in question have already clearly been parsed without error if we have been able to check the value of specific fields.

Body:
Background:

I have a CSV (csv_dump) file with data from a MySQL table. I want copy some of the lines that meet certain conditions (row[1] == condition_1 and row[2] == condition_2) into a temporary CSV file (csv_temp).

Code Snippet:

f_reader = open(csv_dump, 'r')
f_writer = open(csv_temp, 'w')
temp_file = csv.writer(f_writer)

lines_in_csv = csv.reader(f_reader, delimiter=',', skipinitialspace=False)

for row in lines_in_csv:

    if row[1] == condition_1 and row[2] == condition_2:
        temp_file.writerow(row)

f_reader.close()
f_writer.close()

Question:

How can I copy the line that is being read copy it "as is" into the temp file with Python3?

Body:
The following Python script seems to do the job... However, having said that, you should probably be using a MySQL query to do this work directly, instead of re-processing from an intermediate CSV file. But I guess there must be some good reason for wanting to do that?

mycsv.csv:

aa,1,2,5
bb,2,3,5
cc,ddd,3,3
hh,,3,1
as,hfd,3,3

readwrite.py:

import csv

with open('mycsv.csv', 'rb') as infile:
    with open('out.csv', 'wb') as outfile:
        inreader = csv.reader(infile, delimiter=',', quotechar='"')
        outwriter = csv.writer(outfile)
        for row in inreader:
            if row[2]==row[3]:
                outwriter.writerow(row)

out.csv:

cc,ddd,3,3
as,hfd,3,3

With a little more work, you could change the 'csv.writer' to make use of the same delimiters and escape/quote characters as the 'csv.reader'. It's not exactly the same as writing out the raw line from the file, but I think it will be practically as fast since the lines in question have already clearly been parsed without error if we have been able to check the value of specific fields.


来源: stackexchange

问:
Why I get error when I upload zip file to phonegap service?
I try to create apk file using phonegap service.

Here is my config.xml file in my project:

```<code><?xml version='1.1' encoding='utf-8'?>
<widget id="il.co.geomind.gilgalplay" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>sites</name>
    <description>
        app for sites mapping
    </description>
    <author email="jacklondon@ddd.com" href="">

    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="Orientation" value="portrait" />
    <preference name="permissions" value="none"/>

    <feature name="http://api.phonegap.com/1.0/camera"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>

    <icon src="images/icons/ldpi.png" gap:platform="android" gap:qualifier="ldpi" />
    <icon src="images/icons/mdpi.png" gap:platform="android" gap:qualifier="mdpi" />
    <icon src="images/icons/hdpi.png" gap:platform="android" gap:qualifier="hdpi" />
    <icon src="images/icons/xhdpi.png" gap:platform="android" gap:qualifier="xhdpi" />
    <icon src="images/icons/xxhdpi.png" gap:platform="android" gap:qualifier="xxhdpi" />
    <icon src="images/icons/xxxhdpi.png" gap:platform="android" gap:qualifier="xxxhdpi" />

    <!-- iPhone / iPod Touch  -->
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="60" height="60" />
    <icon src="images/icons/xhdpi.png" gap:platform="ios" width="120" height="120" />

    <!-- Settings Icon -->
    <icon src="images/icons/ldpi.png" gap:platform="ios" width="29" height="29" />
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="58" height="58" />

    <!-- Spotlight Icon -->
    <icon src="images/icons/ldpi.png" gap:platform="ios" width="40" height="40" />
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="80" height="80" />

  <gap:platform name="android" />

  <gap:splash src="images/icons/screen-xhdpi.png"/>

  <gap:plugin name="cordova-plugin-whitelist" source="npm" />
  <gap:plugin name="org.apache.cordova.camera" version="0.3.6" source="npm" />
  <gap:plugin name="org.apache.cordova.device" version="0.3.0" source="npm"/>
  <gap:plugin name="com.phonegap.plugins.pushplugin" version="2.5.0" source="npm"/>
  <gap:plugin name="org.apache.cordova.geolocation" version="0.3.12" source="npm"/>

</widget>
</code>```

I make zip file from the project and make upload to the phonegap service I get this error:

```<code>Error - The following plugin, plugin version or a dependancy of this plugin is not on npm: com.phonegap.plugins.pushplugin@2.5.0
</code>```

Any idea why I get error above and how to fix it?

答:
By setting the source to Node Package Manager (source="npm"), you're telling PhoneGap Build to retrieve the plugin from that location, but "com.phonegap.plugins.pushplugin, version 2.5.0" isn't actually there.

If we look on npmjs.com for the push plugin, there are two plugin search results but as mentioned in the other Answer, it hasn't been updated for over 2 years and is even labeled "-deprecated".

Assuming you want a push notification plugin, I recommend trying to find an official one.  To do so, search for them by beginning with “cordova-plugin” coupled with whatever you’re looking for: "cordova-plugin-push". This led me to this one, which would probably work.

In your config.xml file, add a reference to it like so:

```<code><plugin name="cordova-plugin-push-notification" version="2.5.2" source="npm" />
</code>```

I used version 2.5.2 since that's the latest version:

For further reference, see my guide on using NPM with PhoneGap Build.

ContentLicense: CC BY-SA 3.0

Body:
I try to create apk file using phonegap service.

Here is my config.xml file in my project:

<?xml version='1.1' encoding='utf-8'?>
<widget id="il.co.geomind.gilgalplay" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>sites</name>
    <description>
        app for sites mapping
    </description>
    <author email="jacklondon@ddd.com" href="">

    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="Orientation" value="portrait" />
    <preference name="permissions" value="none"/>

    <feature name="http://api.phonegap.com/1.0/camera"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>

    <icon src="images/icons/ldpi.png" gap:platform="android" gap:qualifier="ldpi" />
    <icon src="images/icons/mdpi.png" gap:platform="android" gap:qualifier="mdpi" />
    <icon src="images/icons/hdpi.png" gap:platform="android" gap:qualifier="hdpi" />
    <icon src="images/icons/xhdpi.png" gap:platform="android" gap:qualifier="xhdpi" />
    <icon src="images/icons/xxhdpi.png" gap:platform="android" gap:qualifier="xxhdpi" />
    <icon src="images/icons/xxxhdpi.png" gap:platform="android" gap:qualifier="xxxhdpi" />

    <icon src="images/icons/mdpi.png" gap:platform="ios" width="60" height="60" />
    <icon src="images/icons/xhdpi.png" gap:platform="ios" width="120" height="120" />

    <icon src="images/icons/ldpi.png" gap:platform="ios" width="29" height="29" />
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="58" height="58" />

    <icon src="images/icons/ldpi.png" gap:platform="ios" width="40" height="40" />
    <icon src="images/icons/mdpi.png" gap:platform="ios" width="80" height="80" />

  <gap:platform name="android" />

  <gap:splash src="images/icons/screen-xhdpi.png"/>

  <gap:plugin name="cordova-plugin-whitelist" source="npm" />
  <gap:plugin name="org.apache.cordova.camera" version="0.3.6" source="npm" />
  <gap:plugin name="org.apache.cordova.device" version="0.3.0" source="npm"/>
  <gap:plugin name="com.phonegap.plugins.pushplugin" version="2.5.0" source="npm"/>
  <gap:plugin name="org.apache.cordova.geolocation" version="0.3.12" source="npm"/>

</widget>

I make zip file from the project and make upload to the phonegap service I get this error:

Error - The following plugin, plugin version or a dependancy of this plugin is not on npm: com.phonegap.plugins.pushplugin@2.5.0

Any idea why I get error above and how to fix it?

Body:
By setting the source to Node Package Manager (source="npm"), you're telling PhoneGap Build to retrieve the plugin from that location, but "com.phonegap.plugins.pushplugin, version 2.5.0" isn't actually there.

If we look on npmjs.com for the push plugin, there are two plugin search results but as mentioned in the other Answer, it hasn't been updated for over 2 years and is even labeled "-deprecated".

Assuming you want a push notification plugin, I recommend trying to find an official one.  To do so, search for them by beginning with “cordova-plugin” coupled with whatever you’re looking for: "cordova-plugin-push". This led me to this one, which would probably work.

In your config.xml file, add a reference to it like so:

<plugin name="cordova-plugin-push-notification" version="2.5.2" source="npm" />

I used version 2.5.2 since that's the latest version:

For further reference, see my guide on using NPM with PhoneGap Build.


问:
How to create an offset formula to use the reference in a cell (the cell the formula points to), not the cell address the formula is in?
I thought this would be easy, but haven't figured it out on my own or found an existing answer online.

I have a worksheet set up to create charts from the contents of certain cells in a table.  I'd like to be able to point one cell to a value in another worksheet and have all the related cell populate with the values using the formula in the one cell as an address reference.

For example, if I put the formula ='Source Data'!G19 in cell E3, I would like cell E4 below it to act like it has the formula ='Source Data'!G20 (one row below in the Source Data worksheet) and populate that value while cell F3 to the right would act like it had the formula ='Source Data'!H20 in it.  So the new worksheet would just mirror the table of data from the Source Data worksheet for as many columns or rows as I need.

I'd tried to figure this out with offset, indirect, match and address functions, but have failed.

It is important to note that the formula needs to be able to identify the actual cell address, not just match the value from the formula because the same values show up multiple times in the Source Data worksheet.

Any help or direction is greatly appreciated.

答:
Here's my approach:
I have a workbook with 2 spreadsheets Source Data and Results, on Source Data, I have the "Static" table that contains all my values from A1 to D12(This can be any number of cells, as long as you use an equal range in the Results sheet).

On Results, Cell A1 is reserved for the "guide" cell from Source Data, written in the following format: ''Source Data'!A1 (note the two single quotes at the begging). I chose to start at Cell B2 on the Results sheet, you can switch the formula however you like.

The desired result is achieved by using the following formula on B2:

=IF(CELL("contents",OFFSET(INDIRECT($A$1),ROW(B2)-2,COLUMN(B2)-2))<>0,CELL("contents",OFFSET(INDIRECT($A$1),ROW(B2)-2,COLUMN(B2)-2)),"")

then drag down and to the right the same number of maximum cells that exist on Source Data and the result will adjust accordingly.

I prepared a Google Sheets document with all of the information.


问:
link_to helper doesn't work for me
the controller file drummer.rb

and I use both old controller/action way and new resource way, either work
the view file index.html.erb:

```<code><ul>
<% @drummer_list.each do |d| %>
  <li>
    <%= link_to :controller => 'drummers',:action => 'show', :id => '@drummer'  do %>
      <%=  d.first_name + ' ' + d.last_name %>
    <% end %>
  </li>
<% end %>
</ul>
</code>```

the resource way:

```<code><ul>
<% @drummer_list.each do |d| %>
  <li>
    <%= link_to drummers_path(@drummer)  do %>
      <%=  d.first_name + ' ' + d.last_name %>
    <% end %>
  </li>
<% end %>
</ul>
</code>```

when I click each link, in the browser url bar give me this

```<code>http://localhost:3000/drummers/@drummer
</code>```

it should give me

```<code>http://localhost:3000/drummers/1
</code>```

I think the problem is about the @drummer, I'm not sure about the it.

答:
```<code><ul>
<% @drummer_list.each do |d| %>
  <li>
    <%= link_to "#{d.first_name} #{d.last_name}", d %>
  </li>
<% end %>
</ul>
</code>```

I would move this into a collection partial if it gets more complicated.

ContentLicense: CC BY-SA 2.5

Title: link_to helper doesn't work for me

Body:
the controller file drummer.rb

and I use both old controller/action way and new resource way, either work
the view file index.html.erb:

<% @drummer_list.each do |d| %>

    <%= link_to :controller => 'drummers',:action => 'show', :id => '@drummer'  do %>
      <%=  d.first_name + ' ' + d.last_name %>
    <% end %>

<% end %>

the resource way:

<% @drummer_list.each do |d| %>

    <%= link_to drummers_path(@drummer)  do %>
      <%=  d.first_name + ' ' + d.last_name %>
    <% end %>

<% end %>

when I click each link, in the browser url bar give me this

http://localhost:3000/drummers/@drummer

it should give me

http://localhost:3000/drummers/1

I think the problem is about the @drummer, I'm not sure about the it.

Body:
<ul>
<% @drummer_list.each do |d| %>
  <li>
    <%= link_to "#{d.first_name} #{d.last_name}", d %>
  </li>
<% end %>
</ul>

I would move this into a collection partial if it gets more complicated.


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

Suppose I have the file contents as a string:

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

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

Here is a simple example which shows my dilemma:

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

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

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

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

What I've Tried So Far

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

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

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

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

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

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

Any help is appreciated! :-)

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

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

```<code>from pathlib import PurePath

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

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

答:
StringIO returns an StringIO object, it's almost equivalent to the file object returned by the open statement. So basically, you can use the StringIO in place of the open statement.

```<code># from StringIO import StringIO  # for Python 2, old
from io import StringIO
with StringIO('there is a lot of blah blah in this so-called file') as f:
    print(f.read())
</code>```

Output:

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

Title: Treat a string as a file in python

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

Suppose I have the file contents as a string:

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

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

Here is a simple example which shows my dilemma:

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

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

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

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

What I've Tried So Far

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

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

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

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

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

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

Any help is appreciated! :-)

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

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

from pathlib import PurePath

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

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

Body:
StringIO returns an StringIO object, it's almost equivalent to the file object returned by the open statement. So basically, you can use the StringIO in place of the open statement.

# from StringIO import StringIO  # for Python 2, old
from io import StringIO
with StringIO('there is a lot of blah blah in this so-called file') as f:
    print(f.read())

Output:

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

ContentLicense: CC BY-SA 4.0


问:
How identifiers are stored in memory?
any value assigned to a variable (e.g. int i=5) is stored in memory in hexadecimal form at some address.
So will the variable name(i) associated with the value is converted to ASCII code in memory while storing?</p>

答:
Yes, Java stores that stuff.

Answer:

The runtime knows what type everything is because almost everything is an object, and every object has a method called “getClass()”, which will return the type of object.

That means when an object is passed to a method in Java, the parameter type is known,and also the type of object is known too. That means it’s pretty easy to work out if it’s a valid type to pass.

int in Java isn’t an object, but the type information is still there in both int parameters in methods, and easy enough to check if they match up.

The example of a 4 byte string vs. 32 bit integer would be a valid enough point in C, but not in Java, where strings are abstracted away from being simply character arrays of a given length. Strings are objects in Java, and not just a plain allocation of memory like in C.

Title: How identifiers are stored in memory?


问:
How do I sum two matrices or data frames that share only some elements in common using R?
I have two large data frames that I would like to perform element-wise operations on. In my case, I'd like to essentially do a matrix addition on two matrices that have partially-overlapping column and row names.

For example:

```<code>A <- matrix(rep(1,4),nrow=2)
colnames(A) <- c("a","b")
rownames(A) <- paste("r", seq(1,2,1), sep="")
B <- matrix(rep(10,4),nrow=2)
colnames(A) <- c("b","c")
rownames(B) <- paste("r", seq(2,3,1), sep="")

A
   a b
r1 1 1
r2 1 1

B
    b  c
r2 10 10
r3 10 10
</code>```

I would like to sum A+B by column-and-row names to get:

```<code>>S
   a  b  c
r1 1  1  0
r2 1 11 10
r3 0 10 10
</code>```

The row and column names in the matrices (or data frames) only partially overlap, so the final matrix will have different dimensions than the individual ones. In this toy example, the only overlapping cell is row:b/col:r2. I take empty cells to equal 0.

I can do it in a very clumsy way by subsetting matrices by overlapping rows and columns, then sorting and adding the submatrices, and finally by concatenating the non-overlapping bits. My real data are gene expression matrices with ~20,000 rows (genes) and ~10,000 columns (cells).

答:
We can do this with data.table and this should be efficient.  Place the matrixes in a list, convert the matrix to data.table, create row names as a column ('rn'), rbind the data.tables (rbindlist(...)), grouped by 'rn' get the sum of other columns

```<code>library(data.table)
rbindlist(lapply(list(A, B), function(x) setDT(as.data.frame(x),
 keep.rownames = TRUE)), fill = TRUE)[, lapply(.SD, sum, na.rm = TRUE), by = rn]
#   rn a  b  c
#1: r1 1  1  0
#2: r2 1 11 10
#3: r3 0 10 10
</code>```

data

```<code>A <- structure(c(1L, 1L, 1L, 1L), .Dim = c(2L, 2L), .Dimnames = list(
c("r1", "r2"), c("a", "b")))

B <- structure(c(10L, 10L, 10L, 10L), .Dim = c(2L, 2L), .Dimnames = list(
c("r2", "r3"), c("b", "c")))
</code>```

Body:
I have two large data frames that I would like to perform element-wise operations on. In my case, I'd like to essentially do a matrix addition on two matrices that have partially-overlapping column and row names.

For example:

A <- matrix(rep(1,4),nrow=2)
colnames(A) <- c("a","b")
rownames(A) <- paste("r", seq(1,2,1), sep="")
B <- matrix(rep(10,4),nrow=2)
colnames(A) <- c("b","c")
rownames(B) <- paste("r", seq(2,3,1), sep="")

A
   a b
r1 1 1
r2 1 1

B
    b  c
r2 10 10
r3 10 10

I would like to sum A+B by column-and-row names to get:

>S
   a  b  c
r1 1  1  0
r2 1 11 10
r3 0 10 10

The row and column names in the matrices (or data frames) only partially overlap, so the final matrix will have different dimensions than the individual ones. In this toy example, the only overlapping cell is row:b/col:r2. I take empty cells to equal 0.

I can do it in a very clumsy way by subsetting matrices by overlapping rows and columns, then sorting and adding the submatrices, and finally by concatenating the non-overlapping bits. My real data are gene expression matrices with ~20,000 rows (genes) and ~10,000 columns (cells).

Body:
We can do this with data.table and this should be efficient.  Place the matrixes in a list, convert the matrix to data.table, create row names as a column ('rn'), rbind the data.tables (rbindlist(...)), grouped by 'rn' get the sum of other columns

library(data.table)
rbindlist(lapply(list(A, B), function(x) setDT(as.data.frame(x),
 keep.rownames = TRUE)), fill = TRUE)[, lapply(.SD, sum, na.rm = TRUE), by = rn]
#   rn a  b  c
#1: r1 1  1  0
#2: r2 1 11 10
#3: r3 0 10 10

data

A <- structure(c(1L, 1L, 1L, 1L), .Dim = c(2L, 2L), .Dimnames = list(
c("r1", "r2"), c("a", "b")))

B <- structure(c(10L, 10L, 10L, 10L), .Dim = c(2L, 2L), .Dimnames = list(
c("r2", "r3"), c("b", "c")))


问:
Wrong injection of $modalProvider dependency angujarjs
I'm trying to open a dialog box in angularjs using bootstrap but whenever i try i get this error while injecting the right dependencies.

```<code>.controller('login_ctrl', ['$scope','$http','$window','$modal','$log', function($scope,$http,$window,$modal,$log) {

    var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',

            //size: size,
            resolve: {
                user: function() {
                    return userData;
                },
                selectedProducts: function() {
                    return userData.selectedProducts;
                },
                products: function () {
                    //console.log($scope.selectedProducts);
                    return $scope.products; // get all available products
                }
            }
        });

}])
</code>```

all the files js and css files are in the head section of my document

```<code><link href="/spree/web/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/spree.css">
<script src="/spree/web/lib//angularjs/angular.min.js"></script>
<script src="/spree/web/lib/angularjs/angular-route.min.js"></script>
<script src="/spree/web/js/app.js"></script>
<script src="/spree/web/js/controller.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.js"></script>
</code>```

and this is how the start of the js looks like

```<code>angular.module('controller', ['ui.bootstrap'])
</code>```

when i preview i get this error in the console

Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=%24modalProvider%20%3C-%20%24modal%20%3C-%20login_ctrl

答:
In new version of ui-bootstrap all params and injections changes to $uib* for example for your question you have to use $uibModal instead $modal in your controller.

```<code>.controller('login_ctrl', ['$scope','$http','$window','$uibModal','$log', function($scope,$http,$window,$uibModal,$log) {

var modalInstance = $uibModal.open({
        templateUrl: 'myModalContent.html',
        controller: 'ModalInstanceCtrl',

        //size: size,
        resolve: {
            user: function() {
                return userData;
            },
            selectedProducts: function() {
                return userData.selectedProducts;
            },
            products: function () {
                //console.log($scope.selectedProducts);
                return $scope.products; // get all available products
            }
        }
    });
}]);
</code>```

Body:
I'm trying to open a dialog box in angularjs using bootstrap but whenever i try i get this error while injecting the right dependencies.

.controller('login_ctrl', ['$scope','$http','$window','$modal','$log', function($scope,$http,$window,$modal,$log) {

    var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',

            //size: size,
            resolve: {
                user: function() {
                    return userData;
                },
                selectedProducts: function() {
                    return userData.selectedProducts;
                },
                products: function () {
                    //console.log($scope.selectedProducts);
                    return $scope.products; // get all available products
                }
            }
        });

}])

all the files js and css files are in the head section of my document

<link href="/spree/web/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/spree.css">

and this is how the start of the js looks like

angular.module('controller', ['ui.bootstrap'])

when i preview i get this error in the console

Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=%24modalProvider%20%3C-%20%24modal%20%3C-%20login_ctrl

Body:
In new version of ui-bootstrap all params and injections changes to $uib* for example for your question you have to use $uibModal instead $modal in your controller.

.controller('login_ctrl', ['$scope','$http','$window','$uibModal','$log', function($scope,$http,$window,$uibModal,$log) {

var modalInstance = $uibModal.open({
        templateUrl: 'myModalContent.html',
        controller: 'ModalInstanceCtrl',

        //size: size,
        resolve: {
            user: function() {
                return userData;
            },
            selectedProducts: function() {
                return userData.selectedProducts;
            },
            products: function () {
                //console.log($scope.selectedProducts);
                return $scope.products; // get all available products
            }
        }
    });
}]);


问:
SQL Query to Sum Values on One Table and Select Names from Another table
Apologies for the poorly written title.

I have two tables. Table a with Student ID and Names and table b with Student ID, course and course cost

I want to be able to query the database so I can show the student name and total dollars spent on courses

So far I have this:

```<code>SELECT Student.fname, Student.lname, SUM(m.CourseCost) FROM
  (SELECT DISTINCT StuID, CourseCost FROM Courses) AS m
     INNER JOIN Student ON m.StuID = Student.ID;
</code>```

Visual Studio throws an error when I try to run the query. I am using MS Access as the database. I think there is something wrong with my inner

答:
Your query should be

```<code>SELECT Student.fname, Student.lname, SUM(m.CourseCost) FROM
  (SELECT DISTINCT StuID, CourseCost FROM Course) AS m
     INNER JOIN Student ON m.StuID = Student.ID
     group by Student.fname, Student.lname
</code>```

Or You can do by another way

```<code>select Student.fname, Student.lname, SUM(m.CourseCost) as  CourseCost
from Student
inner join Course m on Student.ID = m.StuID
group by Student.fname, Student.lname, m.StuID
</code>```

Body:
Apologies for the poorly written title.

I have two tables. Table a with Student ID and Names and table b with Student ID, course and course cost

I want to be able to query the database so I can show the student name and total dollars spent on courses

So far I have this:

SELECT Student.fname, Student.lname, SUM(m.CourseCost) FROM
  (SELECT DISTINCT StuID, CourseCost FROM Courses) AS m
     INNER JOIN Student ON m.StuID = Student.ID;

Visual Studio throws an error when I try to run the query. I am using MS Access as the database. I think there is something wrong with my inner

Body:
Your query should be

SELECT Student.fname, Student.lname, SUM(m.CourseCost) FROM
  (SELECT DISTINCT StuID, CourseCost FROM Course) AS m
     INNER JOIN Student ON m.StuID = Student.ID
     group by Student.fname, Student.lname

Or You can do by another way

select Student.fname, Student.lname, SUM(m.CourseCost) as  CourseCost
from Student
inner join Course m on Student.ID = m.StuID
group by Student.fname, Student.lname, m.StuID


问:
Attempting two pass two objects through @PathVariable in thymeleaf/spring-boot
I'm attempting to pull two parameters with the @PathVariable annotation but have been unsuccessful due to java throwing me an error about it referencing the item id (which I currently has as an Long) as a String.

Controller:

```<code>@PostMapping("/purchaseToner/{tid}/{bid}")
    public String buyToner(Model model, @PathVariable("tid") Long tid,
                           @PathVariable("bid") Long bid){

        //Grab info
        Buyer mBuyer = buyerService.findOne(bid);
        Toner mToner = tonerService.findOneToner(tid);

        //Updating qualities
        mToner.setTonerQuantity(mToner.getTonerQuantity() - 1);
        mBuyer.setBalance(mBuyer.getBalance() - mToner.getTonerPrice());

        Buyer iBuyer = new Buyer();
        iBuyer.getToners().add(mToner);

        return "redirect:/";
    }
</code>```

View:

```<code> <form th:action="@{/purchaseToner/{tid}(tid=${toner.id})/{bid}(bid=${buyer.buyerId})}" th:object="${buyer}" method="post">
                       <select th:object="${toner}">
                            <option>Select a Toner</option>
                            <option th:each="toner : ${toners}"
                                    th:text="${toner.tonerName}"
                                    th:value="${toner.id}">
                            </option>
                       </select>
                        <input type="hidden" name="buyerId"/>
                        <input type="submit" value="Purchase" onclick="return confirm('Are you sure you want to make this purchase?')"/>
                    </form>
</code>```

Print Trace:

```<code>2017-06-05 21:10:59.418  INFO 788 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-06-05 21:10:59.517  INFO 788 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-05 21:10:59.527  INFO 788 --- [           main] com.ronone.Application                   : Started Application in 18.596 seconds (JVM running for 19.548)
2017-06-05 21:11:06.438  INFO 788 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-06-05 21:11:06.439  INFO 788 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-06-05 21:11:06.470  INFO 788 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 31 ms
2017-06-05 21:11:09.673  INFO 788 --- [nio-8080-exec-2] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2017-06-05 21:11:15.837  WARN 788 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "{tid}(tid=${toner.id})"
</code>```

答:
Your api buyToner has not been receiving inputs in path variable as number. There is nothing wrong with your api service; check your client side code, is it sending request in proper format OR have you tested your api with any restclient ?

Check out the java exception

```<code>java.lang.NumberFormatException: For input string: "{tid}(tid=${toner.id})"
</code>```

input is not a number here. AND WHY ?

Body:
I'm attempting to pull two parameters with the @PathVariable annotation but have been unsuccessful due to java throwing me an error about it referencing the item id (which I currently has as an Long) as a String.

Controller:

@PostMapping("/purchaseToner/{tid}/{bid}")
    public String buyToner(Model model, @PathVariable("tid") Long tid,
                           @PathVariable("bid") Long bid){

        //Grab info
        Buyer mBuyer = buyerService.findOne(bid);
        Toner mToner = tonerService.findOneToner(tid);

        //Updating qualities
        mToner.setTonerQuantity(mToner.getTonerQuantity() - 1);
        mBuyer.setBalance(mBuyer.getBalance() - mToner.getTonerPrice());

        Buyer iBuyer = new Buyer();
        iBuyer.getToners().add(mToner);

        return "redirect:/";
    }

View:

 <form th:action="@{/purchaseToner/{tid}(tid=${toner.id})/{bid}(bid=${buyer.buyerId})}" th:object="${buyer}" method="post">
                       <select th:object="${toner}">
                            <option>Select a Toner</option>
                            <option th:each="toner : ${toners}"
                                    th:text="${toner.tonerName}"
                                    th:value="${toner.id}">
                            </option>
                       </select>
                        <input type="hidden" name="buyerId"/>
                        <input type="submit" value="Purchase" onclick="return confirm('Are you sure you want to make this purchase?')"/>
                    </form>

Print Trace:

2017-06-05 21:10:59.418  INFO 788 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-06-05 21:10:59.517  INFO 788 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-05 21:10:59.527  INFO 788 --- [           main] com.ronone.Application                   : Started Application in 18.596 seconds (JVM running for 19.548)
2017-06-05 21:11:06.438  INFO 788 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-06-05 21:11:06.439  INFO 788 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-06-05 21:11:06.470  INFO 788 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 31 ms
2017-06-05 21:11:09.673  INFO 788 --- [nio-8080-exec-2] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2017-06-05 21:11:15.837  WARN 788 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "{tid}(tid=${toner.id})"

Body:
Your api buyToner has not been receiving inputs in path variable as number. There is nothing wrong with your api service; check your client side code, is it sending request in proper format OR have you tested your api with any restclient ?

Check out the java exception

java.lang.NumberFormatException: For input string: "{tid}(tid=${toner.id})"

input is not a number here. AND WHY ?


问:
Unity Connection to web by jsp
```<code>using UnityEngine;
using System.Collections;
using System.Text;

public class Network : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        Debug.Log("[waitforComm] Hello, World!");

        string postData = "{\"waitforCommData\":1}";
        Hashtable headers = new Hashtable();
        headers.Add("Content-Type", "application/json");

        byte[] pData = Encoding.ASCII.GetBytes(postData.ToCharArray());

        WWW www = new WWW("http://localhost:8080/jspsample/process.jsp", pData, headers);

        Debug.Log("[waitforComm] post message requested.");

        StartCoroutine(waitforRequest(www));
    }

    // Update is called once per frame
    void Update()
    { }

    private IEnumerator waitforRequest(WWW www)
    {
        yield return www;
        Debug.Log("[waitforComm] response : " + www.text);
    }
}
</code>```

this is our code, i can't figure out this part

WWW www = new WWW("http://localhost:8080/jspsample/process.jsp", pData, headers);

we have error in headers that
Argument 3: cannot convert from 'System.Collections.Hashtable' to 'System.Collections.Generic.Dictionary'

答:
The Unity documentation for the WWW object constructor this code is using is pretty clear, but not crystal.

The third parameter is declared as Dictionary<string, string>, even though the text says "hashtable".

So instead of:

```<code>Hashtable headers = new Hashtable();
headers.Add("Content-Type", "application/json");
</code>```

Do:

```<code>var headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
</code>```

And you should be good to go.

Title: Unity Connection to web by jsp

Body:
using UnityEngine;
using System.Collections;
using System.Text;

public class Network : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        Debug.Log("[waitforComm] Hello, World!");

        string postData = "{\"waitforCommData\":1}";
        Hashtable headers = new Hashtable();
        headers.Add("Content-Type", "application/json");

        byte[] pData = Encoding.ASCII.GetBytes(postData.ToCharArray());

        WWW www = new WWW("http://localhost:8080/jspsample/process.jsp", pData, headers);

        Debug.Log("[waitforComm] post message requested.");

        StartCoroutine(waitforRequest(www));
    }

    // Update is called once per frame
    void Update()
    { }

    private IEnumerator waitforRequest(WWW www)
    {
        yield return www;
        Debug.Log("[waitforComm] response : " + www.text);
    }
}

this is our code, i can't figure out this part

WWW www = new WWW("http://localhost:8080/jspsample/process.jsp", pData, headers);

we have error in headers that
Argument 3: cannot convert from 'System.Collections.Hashtable' to 'System.Collections.Generic.Dictionary'

Body:
The Unity documentation for the WWW object constructor this code is using is pretty clear, but not crystal.

The third parameter is declared as Dictionary<string, string>, even though the text says "hashtable".

So instead of:

Hashtable headers = new Hashtable();
headers.Add("Content-Type", "application/json");

Do:

var headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");

And you should be good to go.


答:
test.csv

```<code>data1,data2,data3
120,80,200
140,50,210
170,100,250
150,70,300
180,120,280
</code>```

The code goes here

```<code>import csv
with open("test.csv", 'r') as incsvfile:
  input_csv = csv.reader(incsvfile, delimiter=',', skipinitialspace=False)
  with open('tempfile.csv', 'w', newline='') as outcsvfile:
    spamwriter = csv.writer(outcsvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    first_row = next(input_csv)
    spamwriter.writerow(first_row)
    for row in input_csv:
        if int(row[1]) != 80 and int(row[2]) != 300:
          spamwriter.writerow(row)
</code>```

output tempfile.csv

```<code>data1,data2,data3
140,50,210
170,100,250
180,120,280
</code>```

if you don't have title remove these two lines

```<code>    first_row = next(input_csv)
    spamwriter.writerow(first_row)
</code>```

Title: How to write into a CSV file with Python

Body:
Background:

I have a CSV (csv_dump) file with data from a MySQL table. I want copy some of the lines that meet certain conditions (row[1] == condition_1 and row[2] == condition_2) into a temporary CSV file (csv_temp).

Code Snippet:

f_reader = open(csv_dump, 'r')
f_writer = open(csv_temp, 'w')
temp_file = csv.writer(f_writer)

lines_in_csv = csv.reader(f_reader, delimiter=',', skipinitialspace=False)

for row in lines_in_csv:

    if row[1] == condition_1 and row[2] == condition_2:
        temp_file.writerow(row)

f_reader.close()
f_writer.close()

Question:

How can I copy the line that is being read copy it "as is" into the temp file with Python3?

Body:
test.csv

data1,data2,data3
120,80,200
140,50,210
170,100,250
150,70,300
180,120,280

The code goes here

import csv
with open("test.csv", 'r') as incsvfile:
  input_csv = csv.reader(incsvfile, delimiter=',', skipinitialspace=False)
  with open('tempfile.csv', 'w', newline='') as outcsvfile:
    spamwriter = csv.writer(outcsvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    first_row = next(input_csv)
    spamwriter.writerow(first_row)
    for row in input_csv:
        if int(row[1]) != 80 and int(row[2]) != 300:
          spamwriter.writerow(row)

output tempfile.csv

data1,data2,data3
140,50,210
170,100,250
180,120,280

if you don't have title remove these two lines

    first_row = next(input_csv)
    spamwriter.writerow(first_row)


问:
Returning Reference from function of pointer type
Was told today that this was a "clever way of making something like a constructor" but it "sews the seeds of destruction" even though it works. I've been searching and I can't seem to figure out why. Thanks.</p>

```<code>Person* makePerson(std::string name, std::int num) {
    Person p(name, num);
    return &p;
}
</code>```

答:
You are returning a pointer to a variable whose lifetime is over when the function returns.  This is useless and will lead to undefined behavior.

You want something like this:

```<code>std::unique_ptr<Person> makePerson(std::string name, std::int num) {
    std::unique_ptr<Person> p(new Person(name, num));
    return std::move(p);
}
</code>```

P.S.: Use int not std::int.

Body:
Was told today that this was a "clever way of making something like a constructor" but it "sews the seeds of destruction" even though it works. I've been searching and I can't seem to figure out why. Thanks.

Person* makePerson(std::string name, std::int num) {
    Person p(name, num);
    return &p;
}

Body:
You are returning a pointer to a variable whose lifetime is over when the function returns.  This is useless and will lead to undefined behavior.

You want something like this:

std::unique_ptr<Person> makePerson(std::string name, std::int num) {
    std::unique_ptr<Person> p(new Person(name, num));
    return std::move(p);
}

P.S.: Use int not std::int.


问:
manipulating DOM elements inside or outside the eventListener
I am trying to add an clickevent when I click on the button, and the page will show what I have typed into the input field:

```<code>var input = document.querySelector("input").value;
document.querySelector(".myButton").addEventListener("click",function()
{
var container = document.querySelector(".contanier");
   container.innerHTML = input;
});
</code>```

this is just work fine, but i want make this code looks strunctre a bit, so i rewite as :

```<code>var input = document.querySelector("input").value;
var button = document.querySelector(".myButton");
var container = document.querySelector(".contanier");
button.addEventListener("click",function(){container.innerHTML = input;});
</code>```

but when I click the button the page just refresh to be blanked, do i have to make DOM inside the eventso this can work? Could anyone tell me what's the difference after I rewrite this?

sorry i fogort the html code:

```<code><body>
<div class="main-container">
   <input type="text" class="js-userInput">
   <button class="myButton">Go!</button>
</div>

 <div class="container"></div>
</body>
</code>```

答:
If you are trying this into the form then button should have the attribute type="button".
Their another method in
function ($event) {
$event.preventDefault();}.
Example
https://plnkr.co/edit/1F5Z7CZOS4P89nEzU7dP?p=preview

Body:
I am trying to add an clickevent when I click on the button, and the page will show what I have typed into the input field:

var input = document.querySelector("input").value;
document.querySelector(".myButton").addEventListener("click",function()
{
var container = document.querySelector(".contanier");
   container.innerHTML = input;
});

this is just work fine, but i want make this code looks strunctre a bit, so i rewite as :

var input = document.querySelector("input").value;
var button = document.querySelector(".myButton");
var container = document.querySelector(".contanier");
button.addEventListener("click",function(){container.innerHTML = input;});

but when I click the button the page just refresh to be blanked, do i have to make DOM inside the eventso this can work? Could anyone tell me what's the difference after I rewrite this?

sorry i fogort the html code:

   <input type="text" class="js-userInput">
   <button class="myButton">Go!</button>


问:
Indexing a subset of an adjacency matrix
I have a 200 x 200 adjacency matrix called M. This is the connection strength for 200 nodes (the nodes are numbered 1 to 200 and organized in ascending order in M - i.e., M(23,45) is the connection strength of node 23 and 45). Out of these 200 nodes, I'm interested in three subsets of nodes.

```<code>subset1 = [2,34,36,42,69,102,187];
subset2 = [5,11,28,89,107,199];
subset3 = [7,55,60,188];
</code>```

Using M, I would like to conduct the following operations:

Average of the connection strength within subset1, subset2, and subset3, separately. For instance, for subset1, that would be the mean connection of all possible pairs of nodes 2, 34, 26,..., 187.

Find the connection strength between subset1, subset2, and subset3. This would be the average of connection strength between all pairs of node spanning all possible pairs of the three subsets (average of connection between subset1 & subset2, subset2 & subset3, and subset1 & subset3). Do note that this between connection does not equate putting all the nodes from three subsets into a single matrix (e.g., connection between two subsets is the mean connection of each node in one subset with every node in the other subset).

What I've tried so far was indexing M using a for loop. It was bulky, especially when I have a large number of nodes in each subset. Can someone help?

答:
```<code>M1 = M(subset1, subset1);
ind = triu(true(size(M1)), 1); % upper triangle
M1_avg = mean(M1(ind));
</code>```

I will leave M2_avg and M1_M2_avg to you.

Body:
I have a 200 x 200 adjacency matrix called M. This is the connection strength for 200 nodes (the nodes are numbered 1 to 200 and organized in ascending order in M - i.e., M(23,45) is the connection strength of node 23 and 45). Out of these 200 nodes, I'm interested in three subsets of nodes.

subset1 = [2,34,36,42,69,102,187];
subset2 = [5,11,28,89,107,199];
subset3 = [7,55,60,188];

Using M, I would like to conduct the following operations:

Average of the connection strength within subset1, subset2, and subset3, separately. For instance, for subset1, that would be the mean connection of all possible pairs of nodes 2, 34, 26,..., 187.

Find the connection strength between subset1, subset2, and subset3. This would be the average of connection strength between all pairs of node spanning all possible pairs of the three subsets (average of connection between subset1 & subset2, subset2 & subset3, and subset1 & subset3). Do note that this between connection does not equate putting all the nodes from three subsets into a single matrix (e.g., connection between two subsets is the mean connection of each node in one subset with every node in the other subset).

What I've tried so far was indexing M using a for loop. It was bulky, especially when I have a large number of nodes in each subset. Can someone help?

Body:
M1 = M(subset1, subset1);
ind = triu(true(size(M1)), 1); % upper triangle
M1_avg = mean(M1(ind));

I will leave M2_avg and M1_M2_avg to you.


问:
PHP Laravel Blade @include pass data into WordPress query
I'm using Sage 9 WordPress starter theme.https://github.com/roots/sage

After include the template in Laravel Blade and pass some data.

```<code>@include ('partials.filter-archive', ['taxonomy' => 'project-type'])
</code>```

How could I use it in my template partials.filter-archive ??
{{ $taxonomy }} doesn't seem to work :(

```<code>@php
  $terms = get_terms(array(
    'taxonomy' => {{ $taxonomy }},
    'orderby' => 'menu_order',
  ));
  print_r($terms);
@endphp
</code>```

答:
I solved it

I can actually simply just do this in partials.filter-archive, that worked for me.

```<code>$terms = get_terms(array(
    'taxonomy' => $taxonomy,
    'orderby' => 'menu_order',
  ));

print_r($terms);
</code>```

Body:
I'm using Sage 9 WordPress starter theme.https://github.com/roots/sage

After include the template in Laravel Blade and pass some data.

@include ('partials.filter-archive', ['taxonomy' => 'project-type'])

How could I use it in my template partials.filter-archive ??
{{ $taxonomy }} doesn't seem to work :(

@php
  $terms = get_terms(array(
    'taxonomy' => {{ $taxonomy }},
    'orderby' => 'menu_order',
  ));
  print_r($terms);
@endphp

Body:
I solved it

I can actually simply just do this in partials.filter-archive, that worked for me.

$terms = get_terms(array(
    'taxonomy' => $taxonomy,
    'orderby' => 'menu_order',
  ));

print_r($terms);


问:
how to find time using python?
i want to run my function and then I want to find now's time using python.

then lets say after 2 hours my function should run again.

what should i do?

答:
```<code>import datetime
import time

def func():
    # your function
    pass

while True:
    func() # call you function
    print datetime.datetime.now() # print current datetime
    time.sleep(2*60*60) # sleep for 2 hours
</code>```

However, a better way for a scheduled operation would be to use cron, as @Silver Light suggested.

Title: how to find time using python?

Body:
import datetime
import time

def func():
    # your function
    pass

while True:
    func() # call you function
    print datetime.datetime.now() # print current datetime
    time.sleep(2*60*60) # sleep for 2 hours

However, a better way for a scheduled operation would be to use cron, as @Silver Light suggested.


问:
Optimization of getRange / Copy methods
I'm looking for a way to speed up my script, below is a snippet (it's actually a lot longer, but essentially the same thing: getrange -> copy to another sheet.

The issue is I run into execution time issues, I believe I need to minimize the function calls and get the entire range/values in one hit, then copy in another.

Only thing is I'm a script noob and can't work this part out, any assistance would be greatly appreciated.

function testEV1() {
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test');
  var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Datastore');
  var lastRow = sheet2.getLastRow()+1;

  if (sheet1.getRange('B3') != " ")
    var confirm = Browser.msgBox('Confirmation required','Are you sure you want to submit this evaluation?', Browser.Buttons.OK_CANCEL);
  if (confirm == 'ok') {
    var wait = Browser.msgBox('Submission In Progress', 'Submission will take approximately 15 seconds, please wait for notification.', Browser.Buttons.OK);
    /*** Evaluation Details ***/
    sheet1.getRange('B2').copyTo(sheet2.getRange(lastRow, 1), {contentsOnly: true});                /*** Agent ***/
    sheet1.getRange('B3').copyTo(sheet2.getRange(lastRow, 2), {contentsOnly: true});               /*** Date of Review ***/
    sheet1.getRange('B4').copyTo(sheet2.getRange(lastRow, 3), {contentsOnly: true});               /*** Date of Call or Chat ***/
    sheet1.getRange('D3').copyTo(sheet2.getRange(lastRow, 4), {contentsOnly: true});               /*** Reviewer ***/
    sheet1.getRange('D4').copyTo(sheet2.getRange(lastRow, 5), {contentsOnly:true});               /*** Method of Enquiry ***/
    sheet1.getRange('B5').copyTo(sheet2.getRange(lastRow, 6), {contentsOnly: true});               /*** Type(Issue vs Query) ***/
    sheet1.getRange('B7').copyTo(sheet2.getRange(lastRow, 7), {contentsOnly: true});               /*** Chat & Call Link ***/
    sheet1.getRange('D5').copyTo(sheet2.getRange(lastRow, 8), {contentsOnly: true});               /*** Category ***/
    sheet1.getRange('B6').copyTo(sheet2.getRange(lastRow, 9), {contentsOnly: true});               /*** FOFC ***/
    sheet1.getRange('D6').copyTo(sheet2.getRange(lastRow, 10), {contentsOnly: true});               /*** If FOFC NO ***/

    var complete = Browser.msgBox('Submission Completed', 'Evaluation has been submitted, you may now clear the form or exit the application.', Browser.Buttons.OK);
  }
};  ```

答:
Try getting your 2 source values all at once & the put those values into a single array to then paste into the sheet. e.g.

```<code>function testEV1() {
   var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test');
   var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Datastore');
   var lastRow = sheet2.getLastRow()+1;

   if (sheet1.getRange('B3') != " "){
     var confirm = Browser.msgBox('Confirmation required','Are you sure you want to submit this evaluation?', Browser.Buttons.OK_CANCEL);
   }
   if(confirm=='ok') {
       var wait = Browser.msgBox('Submission In Progress','Submission will take approximately 15 seconds, please wait for notification.', Browser.Buttons.OK);

       /*** Evaluation Details ***/
       // Get all of the values in one query & then order them at the output stage. This gives more data than we actually consume, but it saves in expensive calls to getRange() & getValues()
       var vals = sheet1.getRange('B2:D7').getValues(); // gets a 2D array of the values in the range.
       var dest_range = sheet2.getRange(lastRow, 1, 1, 10); // the destination range: start at last_row:col_1 & make a range 1 row deep, 10 cols wide.
       dest_range.setValues([
                             [vals[0][0], vals[0][1], vals[0][2], vals[2][1], vals[2][2], vals[0][3], vals[0][5], vals[2][3], vals[0][4], vals[2][4]]
                            ]); // this is your 1 x 10 array of values

       Browser.msgBox('Submission Completed','Evaluation has been submitted, you may now clear the form or exit the application.', Browser.Buttons.OK);
  }
};
</code>```

This should give you a starting point for a much better implementation.

Title: Optimization of getRange / Copy methods

Body:
Try getting your 2 source values all at once & the put those values into a single array to then paste into the sheet. e.g.

function testEV1() {
   var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test');
   var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Datastore');
   var lastRow = sheet2.getLastRow()+1;

   if (sheet1.getRange('B3') != " "){
     var confirm = Browser.msgBox('Confirmation required','Are you sure you want to submit this evaluation?', Browser.Buttons.OK_CANCEL);
   }
   if(confirm=='ok') {
       var wait = Browser.msgBox('Submission In Progress','Submission will take approximately 15 seconds, please wait for notification.', Browser.Buttons.OK);

       /*** Evaluation Details ***/
       // Get all of the values in one query & then order them at the output stage. This gives more data than we actually consume, but it saves in expensive calls to getRange() & getValues()
       var vals = sheet1.getRange('B2:D7').getValues(); // gets a 2D array of the values in the range.
       var dest_range = sheet2.getRange(lastRow, 1, 1, 10); // the destination range: start at last_row:col_1 & make a range 1 row deep, 10 cols wide.
       dest_range.setValues([
                             [vals[0][0], vals[0][1], vals[0][2], vals[2][1], vals[2][2], vals[0][3], vals[0][5], vals[2][3], vals[0][4], vals[2][4]]
                            ]); // this is your 1 x 10 array of values

       Browser.msgBox('Submission Completed','Evaluation has been submitted, you may now clear the form or exit the application.', Browser.Buttons.OK);
  }
};

This should give you a starting point for a much better implementation.


问:
Place some nodes of the same network on GPU and others on CPU?
When defining a network in Caffe/Caffe2, can you place some of the nodes on the CPU and others on GPU? If so, how? </p>

<p>(If your answer pertains a specific version of Caffe, please specify which)</p>

答:
This might be actually possible in Caffe2 but I have never tested it.
In Caffe2, every blob and operator has a device assigned to it. An operator runs on the device assigned to it. But you would then need to manually take care of initialization and communication because data_parallel_model in Caffe2 is only equipped for multi-GPU setup.</p>

Body:
When defining a network in Caffe/Caffe2, can you place some of the nodes on the CPU and others on GPU? If so, how?

(If your answer pertains a specific version of Caffe, please specify which)


问:
Creating base in mem sql
When I create data base in MEMSQL with the name "evento" for example, it create two others bases automatically, "evento_0" and "evento_1", and if I exclude, the querys in data base "evento" throws error.</p>

答: It sounds like your connecting to a leaf node in your cluster instead of to an aggregator node.   Those partition database (_XXX databases)  appear on leaves only.  Check the connection string your using for workbench.  You should point it at the host/port of an aggregator node.  Check memsql-ops list output to see which nodes are aggregators.</p>

Title: Creating base in mem sql


问:
Python : Comparing file name with folder name in same directory
I have a folder with lot of zip files and the extracted folders for the same.
The folder has become so much clustered .

Is there any way to compare the zipped files name with the EXTRACTED folders name in the same directory ?

i want to delete the EXTRACTED folders if they have a .zip file in the same directory.

答:
You can try something like this:

```<code>import shutil
from os import listdir
from os.path import isfile, join, isdir

directories = [d for d in listdir('./') if isdir(join('./', d))]

files = [f for f in listdir('./') if isfile(join('./', f)) and '.zip' in f]

# print(directories)
# print(files)

for d in directories:
    for f in files:
        if f == d + '.zip':
            shutil.rmtree(d)
</code>```

Note that you need to use something like shutil.rmtree(d) if you directories contain subdirectories and/or files.

Body:
You can try something like this:

import shutil
from os import listdir
from os.path import isfile, join, isdir

directories = [d for d in listdir('./') if isdir(join('./', d))]

files = [f for f in listdir('./') if isfile(join('./', f)) and '.zip' in f]

# print(directories)
# print(files)

for d in directories:
    for f in files:
        if f == d + '.zip':
            shutil.rmtree(d)

Note that you need to use something like shutil.rmtree(d) if you directories contain subdirectories and/or files.


问:
How do I run an external javascript function in a web page?
I can run Javascript in-page, thus:

Javascript.html:

```<code><html>
    <body>
        Hello <span id="mySpan"> World! </span>
    </body>
    <script>
        function worldInSpanish() {
            return "Mundo!";
        }
        document.getElementById('mySpan').innerHTML = worldInSpanish();
    </script>
</html>
</code>```

Hello Mundo!

But when I try to run it from an external file, it doesn't work.

javascript.js:

```<code>function worldInSpanish() {
    return "Mundo!";
}
</code>```

External_javascript.html:

```<code><html>
    <body>
        Hello <span id="mySpan"> World! </span>
    </body>
    <script src="javascript.js">
        document.getElementById('mySpan').innerHTML = worldInSpanish();
    </script>
</html>
</code>```

Doesn't change the text:

Hello World!

What am I doing wrong? I'm guessing that I need to do something more to "import" the function into the HTML page or "export" it from the Javascript file.

答:
Note: If the "src" attribute is present, the  element must be empty.

The
```

or You can import such function on that script tag and remove src attribute that you have done firstly. Thanks.

Body:
I can run Javascript in-page, thus:

Javascript.html:

        Hello  World!

Hello Mundo!

But when I try to run it from an external file, it doesn't work.

javascript.js:

function worldInSpanish() {
    return "Mundo!";
}

External_javascript.html:

        Hello  World!

Doesn't change the text:

Hello World!

What am I doing wrong? I'm guessing that I need to do something more to "import" the function into the HTML page or "export" it from the Javascript file.

Body:
Note: If the "src" attribute is present, the  element must be empty.

The <script> tag is used to define a client-side script (JavaScript).

The <script> element either contains scripting statements, or it points to an external script file through the src attribute.

The src attribute specifies the URL of an external script file.

If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again. Save the script file with a .js extension, and then refer to it using the src attribute in the <script> tag.

Note: The external script file cannot contain the <script> tag.

Note: Point to the external script file exactly where you would have written the script.

So either you have to import js file another script tag like

<script src="javascript.js"></script>

or You can import such function on that script tag and remove src attribute that you have done firstly. Thanks.


答:
```<code>select students.name , (select sum(cost) from course_details where student_id = students.id) as cost from students;
</code>```

please note, this is a postgresql query. I believe the concept of subquery is the same.

Title: SQL Query to Sum Values on One Table and Select Names from Another table

Body:
Apologies for the poorly written title.

I have two tables. Table a with Student ID and Names and table b with Student ID, course and course cost

I want to be able to query the database so I can show the student name and total dollars spent on courses

So far I have this:

SELECT Student.fname, Student.lname, SUM(m.CourseCost) FROM
  (SELECT DISTINCT StuID, CourseCost FROM Courses) AS m
     INNER JOIN Student ON m.StuID = Student.ID;

Visual Studio throws an error when I try to run the query. I am using MS Access as the database. I think there is something wrong with my inner

Body:
select students.name , (select sum(cost) from course_details where student_id = students.id) as cost from students;

please note, this is a postgresql query. I believe the concept of subquery is the same.


问:
How to know if a date is in an interval using lubridate?
If I have a lubridate interval: "2010-02-20" %--% "2012-03-15"
How may I know if a date, say "2011-01-12", is in that range?

I am using lubridate and the tidyverse packages.

Body:
ymd("2011-01-12") %within% ("2010-02-20" %--% "2012-03-15")

# [1] TRUE


问:
Having Issues with JSF Backing Managed Bean Not Updating in the View
This question relates to a question I asked earlier and in order not to include the same code snippets, I would be glad if you would view it here.

I deploy the application on Tomcat 8.5. and now I see the return value of getMessage() from the HelloWorld managed bean displayed in the browser.

Now when I edit the value in the getMessage() function for instance instead of "Hello World!" I use "Hello World!................" and save and redeploy, the old value keeps displaying in the browser. Even if I restart Tomcat, it is the same old value. I just don't understand why.

I don't know if the problem is a cache problem or what. What I don't understand it is even after shutting down the server and restart it, I get the same old value.

答:
I agree with Asela Senanayake steps but sometimes for me even after the Cleaning up the Tomcat Directory the code was not deployed properly. What you can do is manually delete your project from the tomcat working directory and do the build and publish again for your project. You can find the project deployment location for tomcat below:

your_project_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0


问:
Redirect to another action in an interceptor in struts 2
I am currently in the process of learning Struts 2 and I am currently building a simple application where unverified users are redirected to a login form.

I have a login form and action functional which takes the users credentials, verifies them and stores a User object in the session however I am now trying to prevent access to pages before the login has taken place and I am trying to do this with an interceptor.

My problem is that I have written an interceptor that checks whether the User object has been saved in the session but if it has not I want to redirect to the login page and can't find any way of doing this without bypassing struts and using the HttpServletResponse.sendRedirect method

Configuration:

```<code><package name="mypackage" extends="struts-default" namespace="/admin">

    <interceptors>
        <interceptor name="login" class="my.LoginInterceptor" />
    </interceptors>

    <default-interceptor-ref name="login"/>

    <action name="login" class="my.LoginAction">
        <result name="input">/admin/login.jsp</result>
        <result name="success" type="redirect">/admin</result>
    </action>

    <action name="private" class="my.PrivateAction">
        <result>/admin/private.jsp</result>
    </action>

</package>
</code>```

The interceptor code:

```<code>@Override
public String intercept(ActionInvocation inv) throws Exception {

    Map<String, Object> session = inv.getInvocationContext().getSession();

    Object user = session.get("user");
    if(user == null) {

                      // redirect to the 'login' action here

    }
    else {
        return inv.invoke();
    }

}
</code>```

答:
You can find the complete example of struts2 with a custom Login Interceptor here

http://sandeepbhardwaj.github.io/2010/12/01/struts2-with-login-interceptor.html

great tutorial.

Body:
I am currently in the process of learning Struts 2 and I am currently building a simple application where unverified users are redirected to a login form.

I have a login form and action functional which takes the users credentials, verifies them and stores a User object in the session however I am now trying to prevent access to pages before the login has taken place and I am trying to do this with an interceptor.

My problem is that I have written an interceptor that checks whether the User object has been saved in the session but if it has not I want to redirect to the login page and can't find any way of doing this without bypassing struts and using the HttpServletResponse.sendRedirect method

Configuration:

<package name="mypackage" extends="struts-default" namespace="/admin">

    <interceptors>
        <interceptor name="login" class="my.LoginInterceptor" />
    </interceptors>

    <default-interceptor-ref name="login"/>

    <action name="login" class="my.LoginAction">
        <result name="input">/admin/login.jsp</result>
        <result name="success" type="redirect">/admin</result>
    </action>

    <action name="private" class="my.PrivateAction">
        <result>/admin/private.jsp</result>
    </action>

</package>

The interceptor code:

@Override
public String intercept(ActionInvocation inv) throws Exception {

    Map<String, Object> session = inv.getInvocationContext().getSession();

    Object user = session.get("user");
    if(user == null) {

                      // redirect to the 'login' action here

    }
    else {
        return inv.invoke();
    }

}


问:
Google Sign in not working properly
I have integrated sign in with google in my android application, now issue is that in some device its not working,but in my emulator and in some device it is working fine,what is the issue?

https://developers.google.com/identity/sign-in/android/

http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/

this two tutorials to sign in, but when i run my app, and try to login it allows to select account,but when i click on that in my logcat it shows

```<code>System.out: Google logout
</code>```

CODE

```<code>private void handleSignInResult(GoogleSignInResult result) {
        Log.d("", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            Log.e("", "display name: " + acct.getDisplayName());

            personName = acct.getDisplayName();
            personPhotoUrl = String.valueOf(acct.getPhotoUrl());
            ggoleemail = acct.getEmail();
            googleid = "G" + acct.getId();
          //  String baday = String.valueOf(acct.getAccount());

            Log.e(TAG, "Name: " + personName + googleid  + ", email: " + ggoleemail
                    + ", Image: " + personPhotoUrl);
          /*  txtName.setText(personName);
            txtEmail.setText(email);
            Glide.with(getApplicationContext()).load(personPhotoUrl)
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgProfilePic);
*/
            googleslogins();
          //  updateUI(true);

        } else {
            // Signed out, show unauthenticated UI.
            //updateUI(false);
            System.out.println("Google logout");
        }
    }
</code>```

答:
Based from this thread, you're getting an error maybe because the user's account is attached to both a hosted account and a Google account, and probably it has different passwords for each The authentication servers currently do not handle this well. Follow this Connecting to Google Drive with Google APIs Client Library for Java tutorial.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   ...
   // Google Accounts using OAuth2
   m_credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(DriveScopes.DRIVE));

   m_client = new com.google.api.services.drive.Drive.Builder(
            m_transport, m_jsonFactory, m_credential).setApplicationName("AppName/1.0")
            .build();
   ...
}
</code>```

You can also check on these related issues:

Bad Authentication Error Rails connecting to google drive

Google Drive: 403 Authentication failed

Hope this helps!

Title: Google Sign in not working properly

Body:
I have integrated sign in with google in my android application, now issue is that in some device its not working,but in my emulator and in some device it is working fine,what is the issue?

https://developers.google.com/identity/sign-in/android/

http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/

this two tutorials to sign in, but when i run my app, and try to login it allows to select account,but when i click on that in my logcat it shows

System.out: Google logout

CODE

private void handleSignInResult(GoogleSignInResult result) {
        Log.d("", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            Log.e("", "display name: " + acct.getDisplayName());

            personName = acct.getDisplayName();
            personPhotoUrl = String.valueOf(acct.getPhotoUrl());
            ggoleemail = acct.getEmail();
            googleid = "G" + acct.getId();
          //  String baday = String.valueOf(acct.getAccount());

            Log.e(TAG, "Name: " + personName + googleid  + ", email: " + ggoleemail
                    + ", Image: " + personPhotoUrl);
          /*  txtName.setText(personName);
            txtEmail.setText(email);
            Glide.with(getApplicationContext()).load(personPhotoUrl)
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imgProfilePic);
*/
            googleslogins();
          //  updateUI(true);

        } else {
            // Signed out, show unauthenticated UI.
            //updateUI(false);
            System.out.println("Google logout");
        }
    }

Body:
Based from this thread, you're getting an error maybe because the user's account is attached to both a hosted account and a Google account, and probably it has different passwords for each The authentication servers currently do not handle this well. Follow this Connecting to Google Drive with Google APIs Client Library for Java tutorial.

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   ...
   // Google Accounts using OAuth2
   m_credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(DriveScopes.DRIVE));

   m_client = new com.google.api.services.drive.Drive.Builder(
            m_transport, m_jsonFactory, m_credential).setApplicationName("AppName/1.0")
            .build();
   ...
}

You can also check on these related issues:

Bad Authentication Error Rails connecting to google drive

Google Drive: 403 Authentication failed

Hope this helps!


问:
MongoDB Crashing on full-text queries
Getting a periodic crash on my mongodb server.  It's running on a 4GB ubuntu 16.04.4 droplet in DigitalOcean.  I have increased the memory and monitoring doesn't show high utilization, so I suspect this is some kind of misunderstanding on my part around how to configure mongo.

I am using full-text search, and have indexes in place, but I have a feeling it's not quite right.

This is the latest mongo (fresh install of community edition, 3.4).
Mongo warns me at startup that I really should use XFS instead of ext4, but that's the only warning.  I doubt if that's an issue.

Any ideas?

The pertinent log entry is:

```<code>2017-06-05T21:35:13.545+0000 I COMMAND  [conn5] command eagle.devices command: find { find: "devices", filter: { $text: { $search: "*55" } }, projection: { score: { $meta: "textScore" }, _id: 1, name: 1, descriptions: 1 }, limit: 10 } planSummary: IXSCAN { _fts: "text", _ftsx: 1 } keysExamined:6834 docsExamined:6834 cursorExhausted:1 numYields:161 nreturned:10 reslen:11410 locks:{ Global: { acquireCount: { r: 326 } }, Database: { acquireCount: { r: 163 } }, Collection: { acquireCount: { r: 163 } } } protocol:op_query 3163ms
2017-06-05T21:35:17.011+0000 F -        [conn5] out of memory.
</code>```

And backtrace:

```<code>----- BEGIN BACKTRACE -----
{"backtrace":[{"b":"55A9B8BBD000","o":"1576BE1","s":"_ZN5mongo15printStackTraceERSo"},{"b":"55A9B8BBD000","o":"15760F4","s":"_ZN5mongo29reportOutOfMemoryErrorAndExitEv"},{"b":"55A9B8BBD000","o":"14E2401","s":"_ZN5mongo11mongoMallocEm"},{"b":"55A9B8BBD000","o":"8A8BB2","s":"_ZNK5mongo7BSONObj4copyEv"},{"b":"55A9B8BBD000","o":"8A8C69","s":"_ZNK5mongo7BSONObj8getOwnedEv"},{"b":"55A9B8BBD000","o":"BD4C54","s":"_ZN5mongo16WorkingSetMember20makeObjOwnedIfNeededEv"},{"b":"55A9B8BBD000","o":"BCD278","s":"_ZN5mongo11TextOrStage7addTermEmPm"},{"b":"55A9B8BBD000","o":"BCD46F","s":"_ZN5mongo11TextOrStage16readFromChildrenEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"BCA81F","s":"_ZN5mongo14TextMatchStage6doWorkEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"BA1F67","s":"_ZN5mongo15ProjectionStage6doWorkEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"BB018E","s":"_ZN5mongo9SkipStage6doWorkEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"B933B6","s":"_ZN5mongo10LimitStage6doWorkEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"EA505A","s":"_ZN5mongo12PlanExecutor11getNextImplEPNS_11SnapshottedINS_7BSONObjEEEPNS_8RecordIdE"},{"b":"55A9B8BBD000","o":"EA597B","s":"_ZN5mongo12PlanExecutor7getNextEPNS_7BSONObjEPNS_8RecordIdE"},{"b":"55A9B8BBD000","o":"A8B1B4","s":"_ZN5mongo7FindCmd3runEPNS_16OperationContextERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERNS_7BSONObjEiRS8_RNS_14BSONObjBuilderE"},{"b":"55A9B8BBD000","o":"A61DA7","s":"_ZN5mongo7Command3runEPNS_16OperationContextERKNS_3rpc16RequestInterfaceEPNS3_21ReplyBuilderInterfaceE"},{"b":"55A9B8BBD000","o":"A63139","s":"_ZN5mongo7Command11execCommandEPNS_16OperationContextEPS0_RKNS_3rpc16RequestInterfaceEPNS4_21ReplyBuilderInterfaceE"},{"b":"55A9B8BBD000","o":"1080D5D","s":"_ZN5mongo11runCommandsEPNS_16OperationContextERKNS_3rpc16RequestInterfaceEPNS2_21ReplyBuilderInterfaceE"},{"b":"55A9B8BBD000","o":"C7F552"},{"b":"55A9B8BBD000","o":"C814C6","s":"_ZN5mongo16assembleResponseEPNS_16OperationContextERNS_7MessageERNS_10DbResponseERKNS_11HostAndPortE"},{"b":"55A9B8BBD000","o":"88042D","s":"_ZN5mongo23ServiceEntryPointMongod12_sessionLoopERKSt10shared_ptrINS_9transport7SessionEE"},{"b":"55A9B8BBD000","o":"880D6D"},{"b":"55A9B8BBD000","o":"14DCC52"},{"b":"7FE3A24BF000","o":"76BA"},{"b":"7FE3A20F6000","o":"10682D","s":"clone"}],"processInfo":{ "mongodbVersion" : "3.4.4", "gitVersion" : "888390515874a9debd1b6c5d36559ca86b44babd", "compiledModules" : [], "uname" : { "sysname" : "Linux", "release" : "4.4.0-78-generic", "version" : "#99-Ubuntu SMP Thu Apr 27 15:29:09 UTC 2017", "machine" : "x86_64" }, "somap" : [ { "b" : "55A9B8BBD000", "elfType" : 3, "buildId" : "5754B63E6FC9683BABEC9CDF7BF6764E6939C8A2" }, { "b" : "7FFD3BDF8000", "elfType" : 3, "buildId" : "4C93E2706C4247EB8ED67A60A6D83F3D740DFD8E" }, { "b" : "7FE3A344B000", "path" : "/lib/x86_64-linux-gnu/libssl.so.1.0.0", "elfType" : 3, "buildId" : "7F514146540382F59AD705BA8C913A75204C6858" }, { "b" : "7FE3A3007000", "path" : "/lib/x86_64-linux-gnu/libcrypto.so.1.0.0", "elfType" : 3, "buildId" : "E6D4D2E4A048992CD5501E5985094E6CEC6C5D4F" }, { "b" : "7FE3A2DFF000", "path" : "/lib/x86_64-linux-gnu/librt.so.1", "elfType" : 3, "buildId" : "0DBB8C21FC5D977098CA718BA2BFD6C4C21172E9" }, { "b" : "7FE3A2BFB000", "path" : "/lib/x86_64-linux-gnu/libdl.so.2", "elfType" : 3, "buildId" : "C0C5B7F18348654040534B050B110D32A19EA38D" }, { "b" : "7FE3A28F2000", "path" : "/lib/x86_64-linux-gnu/libm.so.6", "elfType" : 3, "buildId" : "05451CB4D66C321691F64F253880B7CE5B8812A6" }, { "b" : "7FE3A26DC000", "path" : "/lib/x86_64-linux-gnu/libgcc_s.so.1", "elfType" : 3, "buildId" : "68220AE2C65D65C1B6AAA12FA6765A6EC2F5F434" }, { "b" : "7FE3A24BF000", "path" : "/lib/x86_64-linux-gnu/libpthread.so.0", "elfType" : 3, "buildId" : "84538E3C6CFCD5D4E3C0D2B6C3373F802915A498" }, { "b" : "7FE3A20F6000", "path" : "/lib/x86_64-linux-gnu/libc.so.6", "elfType" : 3, "buildId" : "CBFA941A8EB7A11E4F90E81B66FCD5A820995D7C" }, { "b" : "7FE3A36B4000", "path" : "/lib64/ld-linux-x86-64.so.2", "elfType" : 3, "buildId" : "A7D5A820B802049276B1FC26C8E845A3E194EB6B" } ] }}
 mongod(_ZN5mongo15printStackTraceERSo+0x41) [0x55a9ba133be1]
 mongod(_ZN5mongo29reportOutOfMemoryErrorAndExitEv+0x84) [0x55a9ba1330f4]
 mongod(_ZN5mongo11mongoMallocEm+0x21) [0x55a9ba09f401]
 mongod(_ZNK5mongo7BSONObj4copyEv+0x22) [0x55a9b9465bb2]
 mongod(_ZNK5mongo7BSONObj8getOwnedEv+0x59) [0x55a9b9465c69]
 mongod(_ZN5mongo16WorkingSetMember20makeObjOwnedIfNeededEv+0x54) [0x55a9b9791c54]
 mongod(_ZN5mongo11TextOrStage7addTermEmPm+0x688) [0x55a9b978a278]
 mongod(_ZN5mongo11TextOrStage16readFromChildrenEPm+0x6F) [0x55a9b978a46f]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo14TextMatchStage6doWorkEPm+0x6F) [0x55a9b978781f]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo15ProjectionStage6doWorkEPm+0x47) [0x55a9b975ef67]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo9SkipStage6doWorkEPm+0x3E) [0x55a9b976d18e]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo10LimitStage6doWorkEPm+0x76) [0x55a9b97503b6]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo12PlanExecutor11getNextImplEPNS_11SnapshottedINS_7BSONObjEEEPNS_8RecordIdE+0x19A) [0x55a9b9a6205a]
 mongod(_ZN5mongo12PlanExecutor7getNextEPNS_7BSONObjEPNS_8RecordIdE+0x4B) [0x55a9b9a6297b]
 mongod(_ZN5mongo7FindCmd3runEPNS_16OperationContextERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERNS_7BSONObjEiRS8_RNS_14BSONObjBuilderE+0x1054) [0x55a9b96481b4]
 mongod(_ZN5mongo7Command3runEPNS_16OperationContextERKNS_3rpc16RequestInterfaceEPNS3_21ReplyBuilderInterfaceE+0x527) [0x55a9b961eda7]
 mongod(_ZN5mongo7Command11execCommandEPNS_16OperationContextEPS0_RKNS_3rpc16RequestInterfaceEPNS4_21ReplyBuilderInterfaceE+0x9D9) [0x55a9b9620139]
 mongod(_ZN5mongo11runCommandsEPNS_16OperationContextERKNS_3rpc16RequestInterfaceEPNS2_21ReplyBuilderInterfaceE+0x26D) [0x55a9b9c3dd5d]
 mongod(+0xC7F552) [0x55a9b983c552]
 mongod(_ZN5mongo16assembleResponseEPNS_16OperationContextERNS_7MessageERNS_10DbResponseERKNS_11HostAndPortE+0x6D6) [0x55a9b983e4c6]
 mongod(_ZN5mongo23ServiceEntryPointMongod12_sessionLoopERKSt10shared_ptrINS_9transport7SessionEE+0x1ED) [0x55a9b943d42d]
 mongod(+0x880D6D) [0x55a9b943dd6d]
 mongod(+0x14DCC52) [0x55a9ba099c52]
 libpthread.so.0(+0x76BA) [0x7fe3a24c66ba]
 libc.so.6(clone+0x6D) [0x7fe3a21fc82d]
-----  END BACKTRACE  -----
</code>```

And, if you're still reading, here's the output form "service mongod status":

```<code>● mongod.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2017-06-05 23:53:35 UTC; 12s ago
     Docs: https://docs.mongodb.org/manual
  Process: 4959 ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (code=exited, status=14)
 Main PID: 4959 (code=exited, status=14)

Jun 05 23:53:28 sp-mongo-0 systemd[1]: Started High-performance, schema-free document-oriented database.
Jun 05 23:53:35 sp-mongo-0 mongod[4959]: src/third_party/gperftools-2.5/src/central_freelist.cc:333] tcmalloc: allocation failed 12288
Jun 05 23:53:35 sp-mongo-0 mongod[4959]: src/third_party/gperftools-2.5/src/central_freelist.cc:333] tcmalloc: allocation failed 8192
Jun 05 23:53:35 sp-mongo-0 mongod[4959]: src/third_party/gperftools-2.5/src/central_freelist.cc:333] tcmalloc: allocation failed 20480
Jun 05 23:53:35 sp-mongo-0 mongod[4959]: src/third_party/gperftools-2.5/src/central_freelist.cc:333] tcmalloc: allocation failed 20480
Jun 05 23:53:35 sp-mongo-0 systemd[1]: mongod.service: Main process exited, code=exited, status=14/n/a
Jun 05 23:53:35 sp-mongo-0 systemd[1]: mongod.service: Unit entered failed state.
Jun 05 23:53:35 sp-mongo-0 systemd[1]: mongod.service: Failed with result 'exit-code'.
</code>```

答: It may be that your search using wild card with text index <code>$text: { $search: "*55" }</code> is not supported. </p>

Title: MongoDB Crashing on full-text queries

Body:
Getting a periodic crash on my mongodb server.  It's running on a 4GB ubuntu 16.04.4 droplet in DigitalOcean.  I have increased the memory and monitoring doesn't show high utilization, so I suspect this is some kind of misunderstanding on my part around how to configure mongo.

I am using full-text search, and have indexes in place, but I have a feeling it's not quite right.

This is the latest mongo (fresh install of community edition, 3.4).
Mongo warns me at startup that I really should use XFS instead of ext4, but that's the only warning.  I doubt if that's an issue.

Any ideas?

The pertinent log entry is:

2017-06-05T21:35:13.545+0000 I COMMAND  [conn5] command eagle.devices command: find { find: "devices", filter: { $text: { $search: "*55" } }, projection: { score: { $meta: "textScore" }, _id: 1, name: 1, descriptions: 1 }, limit: 10 } planSummary: IXSCAN { _fts: "text", _ftsx: 1 } keysExamined:6834 docsExamined:6834 cursorExhausted:1 numYields:161 nreturned:10 reslen:11410 locks:{ Global: { acquireCount: { r: 326 } }, Database: { acquireCount: { r: 163 } }, Collection: { acquireCount: { r: 163 } } } protocol:op_query 3163ms
2017-06-05T21:35:17.011+0000 F -        [conn5] out of memory.

And backtrace:

----- BEGIN BACKTRACE -----
{"backtrace":[{"b":"55A9B8BBD000","o":"1576BE1","s":"_ZN5mongo15printStackTraceERSo"},{"b":"55A9B8BBD000","o":"15760F4","s":"_ZN5mongo29reportOutOfMemoryErrorAndExitEv"},{"b":"55A9B8BBD000","o":"14E2401","s":"_ZN5mongo11mongoMallocEm"},{"b":"55A9B8BBD000","o":"8A8BB2","s":"_ZNK5mongo7BSONObj4copyEv"},{"b":"55A9B8BBD000","o":"8A8C69","s":"_ZNK5mongo7BSONObj8getOwnedEv"},{"b":"55A9B8BBD000","o":"BD4C54","s":"_ZN5mongo16WorkingSetMember20makeObjOwnedIfNeededEv"},{"b":"55A9B8BBD000","o":"BCD278","s":"_ZN5mongo11TextOrStage7addTermEmPm"},{"b":"55A9B8BBD000","o":"BCD46F","s":"_ZN5mongo11TextOrStage16readFromChildrenEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"BCA81F","s":"_ZN5mongo14TextMatchStage6doWorkEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"BA1F67","s":"_ZN5mongo15ProjectionStage6doWorkEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"BB018E","s":"_ZN5mongo9SkipStage6doWorkEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"B933B6","s":"_ZN5mongo10LimitStage6doWorkEPm"},{"b":"55A9B8BBD000","o":"B9F343","s":"_ZN5mongo9PlanStage4workEPm"},{"b":"55A9B8BBD000","o":"EA505A","s":"_ZN5mongo12PlanExecutor11getNextImplEPNS_11SnapshottedINS_7BSONObjEEEPNS_8RecordIdE"},{"b":"55A9B8BBD000","o":"EA597B","s":"_ZN5mongo12PlanExecutor7getNextEPNS_7BSONObjEPNS_8RecordIdE"},{"b":"55A9B8BBD000","o":"A8B1B4","s":"_ZN5mongo7FindCmd3runEPNS_16OperationContextERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERNS_7BSONObjEiRS8_RNS_14BSONObjBuilderE"},{"b":"55A9B8BBD000","o":"A61DA7","s":"_ZN5mongo7Command3runEPNS_16OperationContextERKNS_3rpc16RequestInterfaceEPNS3_21ReplyBuilderInterfaceE"},{"b":"55A9B8BBD000","o":"A63139","s":"_ZN5mongo7Command11execCommandEPNS_16OperationContextEPS0_RKNS_3rpc16RequestInterfaceEPNS4_21ReplyBuilderInterfaceE"},{"b":"55A9B8BBD000","o":"1080D5D","s":"_ZN5mongo11runCommandsEPNS_16OperationContextERKNS_3rpc16RequestInterfaceEPNS2_21ReplyBuilderInterfaceE"},{"b":"55A9B8BBD000","o":"C7F552"},{"b":"55A9B8BBD000","o":"C814C6","s":"_ZN5mongo16assembleResponseEPNS_16OperationContextERNS_7MessageERNS_10DbResponseERKNS_11HostAndPortE"},{"b":"55A9B8BBD000","o":"88042D","s":"_ZN5mongo23ServiceEntryPointMongod12_sessionLoopERKSt10shared_ptrINS_9transport7SessionEE"},{"b":"55A9B8BBD000","o":"880D6D"},{"b":"55A9B8BBD000","o":"14DCC52"},{"b":"7FE3A24BF000","o":"76BA"},{"b":"7FE3A20F6000","o":"10682D","s":"clone"}],"processInfo":{ "mongodbVersion" : "3.4.4", "gitVersion" : "888390515874a9debd1b6c5d36559ca86b44babd", "compiledModules" : [], "uname" : { "sysname" : "Linux", "release" : "4.4.0-78-generic", "version" : "#99-Ubuntu SMP Thu Apr 27 15:29:09 UTC 2017", "machine" : "x86_64" }, "somap" : [ { "b" : "55A9B8BBD000", "elfType" : 3, "buildId" : "5754B63E6FC9683BABEC9CDF7BF6764E6939C8A2" }, { "b" : "7FFD3BDF8000", "elfType" : 3, "buildId" : "4C93E2706C4247EB8ED67A60A6D83F3D740DFD8E" }, { "b" : "7FE3A344B000", "path" : "/lib/x86_64-linux-gnu/libssl.so.1.0.0", "elfType" : 3, "buildId" : "7F514146540382F59AD705BA8C913A75204C6858" }, { "b" : "7FE3A3007000", "path" : "/lib/x86_64-linux-gnu/libcrypto.so.1.0.0", "elfType" : 3, "buildId" : "E6D4D2E4A048992CD5501E5985094E6CEC6C5D4F" }, { "b" : "7FE3A2DFF000", "path" : "/lib/x86_64-linux-gnu/librt.so.1", "elfType" : 3, "buildId" : "0DBB8C21FC5D977098CA718BA2BFD6C4C21172E9" }, { "b" : "7FE3A2BFB000", "path" : "/lib/x86_64-linux-gnu/libdl.so.2", "elfType" : 3, "buildId" : "C0C5B7F18348654040534B050B110D32A19EA38D" }, { "b" : "7FE3A28F2000", "path" : "/lib/x86_64-linux-gnu/libm.so.6", "elfType" : 3, "buildId" : "05451CB4D66C321691F64F253880B7CE5B8812A6" }, { "b" : "7FE3A26DC000", "path" : "/lib/x86_64-linux-gnu/libgcc_s.so.1", "elfType" : 3, "buildId" : "68220AE2C65D65C1B6AAA12FA6765A6EC2F5F434" }, { "b" : "7FE3A24BF000", "path" : "/lib/x86_64-linux-gnu/libpthread.so.0", "elfType" : 3, "buildId" : "84538E3C6CFCD5D4E3C0D2B6C3373F802915A498" }, { "b" : "7FE3A20F6000", "path" : "/lib/x86_64-linux-gnu/libc.so.6", "elfType" : 3, "buildId" : "CBFA941A8EB7A11E4F90E81B66FCD5A820995D7C" }, { "b" : "7FE3A36B4000", "path" : "/lib64/ld-linux-x86-64.so.2", "elfType" : 3, "buildId" : "A7D5A820B802049276B1FC26C8E845A3E194EB6B" } ] }}
 mongod(_ZN5mongo15printStackTraceERSo+0x41) [0x55a9ba133be1]
 mongod(_ZN5mongo29reportOutOfMemoryErrorAndExitEv+0x84) [0x55a9ba1330f4]
 mongod(_ZN5mongo11mongoMallocEm+0x21) [0x55a9ba09f401]
 mongod(_ZNK5mongo7BSONObj4copyEv+0x22) [0x55a9b9465bb2]
 mongod(_ZNK5mongo7BSONObj8getOwnedEv+0x59) [0x55a9b9465c69]
 mongod(_ZN5mongo16WorkingSetMember20makeObjOwnedIfNeededEv+0x54) [0x55a9b9791c54]
 mongod(_ZN5mongo11TextOrStage7addTermEmPm+0x688) [0x55a9b978a278]
 mongod(_ZN5mongo11TextOrStage16readFromChildrenEPm+0x6F) [0x55a9b978a46f]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo14TextMatchStage6doWorkEPm+0x6F) [0x55a9b978781f]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo15ProjectionStage6doWorkEPm+0x47) [0x55a9b975ef67]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo9SkipStage6doWorkEPm+0x3E) [0x55a9b976d18e]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo10LimitStage6doWorkEPm+0x76) [0x55a9b97503b6]
 mongod(_ZN5mongo9PlanStage4workEPm+0x63) [0x55a9b975c343]
 mongod(_ZN5mongo12PlanExecutor11getNextImplEPNS_11SnapshottedINS_7BSONObjEEEPNS_8RecordIdE+0x19A) [0x55a9b9a6205a]
 mongod(_ZN5mongo12PlanExecutor7getNextEPNS_7BSONObjEPNS_8RecordIdE+0x4B) [0x55a9b9a6297b]
 mongod(_ZN5mongo7FindCmd3runEPNS_16OperationContextERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERNS_7BSONObjEiRS8_RNS_14BSONObjBuilderE+0x1054) [0x55a9b96481b4]
 mongod(_ZN5mongo7Command3runEPNS_16OperationContextERKNS_3rpc16RequestInterfaceEPNS3_21ReplyBuilderInterfaceE+0x527) [0x55a9b961eda7]
 mongod(_ZN5mongo7Command11execCommandEPNS_16OperationContextEPS0_RKNS_3rpc16RequestInterfaceEPNS4_21ReplyBuilderInterfaceE+0x9D9) [0x55a9b9620139]
 mongod(_ZN5mongo11runCommandsEPNS_16OperationContextERKNS_3rpc16RequestInterfaceEPNS2_21ReplyBuilderInterfaceE+0x26D) [0x55a9b9c3dd5d]
 mongod(+0xC7F552) [0x55a9b983c552]
 mongod(_ZN5mongo16assembleResponseEPNS_16OperationContextERNS_7MessageERNS_10DbResponseERKNS_11HostAndPortE+0x6D6) [0x55a9b983e4c6]
 mongod(_ZN5mongo23ServiceEntryPointMongod12_sessionLoopERKSt10shared_ptrINS_9transport7SessionEE+0x1ED) [0x55a9b943d42d]
 mongod(+0x880D6D) [0x55a9b943dd6d]
 mongod(+0x14DCC52) [0x55a9ba099c52]
 libpthread.so.0(+0x76BA) [0x7fe3a24c66ba]
 libc.so.6(clone+0x6D) [0x7fe3a21fc82d]
-----  END BACKTRACE  -----

And, if you're still reading, here's the output form "service mongod status":

● mongod.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2017-06-05 23:53:35 UTC; 12s ago
     Docs: https://docs.mongodb.org/manual
  Process: 4959 ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (code=exited, status=14)
 Main PID: 4959 (code=exited, status=14)

Jun 05 23:53:28 sp-mongo-0 systemd[1]: Started High-performance, schema-free document-oriented database.
Jun 05 23:53:35 sp-mongo-0 mongod[4959]: src/third_party/gperftools-2.5/src/central_freelist.cc:333] tcmalloc: allocation failed 12288
Jun 05 23:53:35 sp-mongo-0 mongod[4959]: src/third_party/gperftools-2.5/src/central_freelist.cc:333] tcmalloc: allocation failed 8192
Jun 05 23:53:35 sp-mongo-0 mongod[4959]: src/third_party/gperftools-2.5/src/central_freelist.cc:333] tcmalloc: allocation failed 20480
Jun 05 23:53:35 sp-mongo-0 mongod[4959]: src/third_party/gperftools-2.5/src/central_freelist.cc:333] tcmalloc: allocation failed 20480
Jun 05 23:53:35 sp-mongo-0 systemd[1]: mongod.service: Main process exited, code=exited, status=14/n/a
Jun 05 23:53:35 sp-mongo-0 systemd[1]: mongod.service: Unit entered failed state.
Jun 05 23:53:35 sp-mongo-0 systemd[1]: mongod.service: Failed with result 'exit-code'.

Body: It may be that your search using wild card with text index $text: { $search: "*55" } is not supported.