问:
python multiprocessing in Jupyter on Windows: AttributeError: Can't get attribute "abc"
I am trying to run a simple command that guesses gender by name using multiprocessing. This code worked on a previous machine so perhaps my setup had something to do with it.

Below is my multiprocessing code:

```<code>import sys
import gender_guesser.detector as gender
import multiprocessing
import time

d = gender.Detector()

def guess_gender (name):
    n = name.title() # make first letter upper case and the rest lower case
    g = d.get_gender(n) # guess gender
    return g

ls = ['john','joe','amamda','derick','peter','ashley','john','joe','amamda','derick','peter','ashley']

t=time.time()

results=[]
def callBack(x):
    results.append(x)

pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()-1, maxtasksperchild=1)

for n in ls:
    print (n)
    pool.apply_async(guess_gender,args=[n],callback=callBack)

pool.close()
pool.join()

results = pd.concat(results)

print(time.time()-t)
</code>```

It simply runs and doesn't do anything. In my cmd window, I see the following at the end of an error message:

```<code>AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
</code>```

Am running python version 3.6.1 on Anaconda:

```<code>import sys
print(sys.version)
3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]
</code>```

Update: Still cannot get it to work. Below is the entire cmd log when I ran the code provided. I appreciate any thoughts you may have!

```<code>C:\Users\ywu\Google Drive>jupyter notebook
[I 10:13:43.954 NotebookApp] Serving notebooks from local directory: C:\Users\ywu\Google Drive
[I 10:13:43.954 NotebookApp] 0 active kernels
[I 10:13:43.955 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=255a5c0c9af337a1c2187feb63f1c426fb903e5929a0b2f0
[I 10:13:43.956 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 10:13:43.959 NotebookApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://localhost:8888/?token=255a5c0c9af337a1c2187feb63f1c426fb903e5929a0b2f0
[I 10:13:44.264 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[W 10:13:44.319 NotebookApp] 404 GET /api/kernels/aceb78ee-73e4-4481-9993-63e5ee8f72cb/channels?session_id=AEA3C6B2B0A440FC84FF3BAF5F5CB615 (127.0.0.1): Kernel does not exist: aceb78ee-73e4-4481-9993-63e5ee8f72cb
[W 10:13:44.328 NotebookApp] 404 GET /api/kernels/aceb78ee-73e4-4481-9993-63e5ee8f72cb/channels?session_id=AEA3C6B2B0A440FC84FF3BAF5F5CB615 (127.0.0.1) 20.07ms referer=None
[I 10:13:54.740 NotebookApp] Creating new notebook in /code/python
[I 10:13:55.241 NotebookApp] Kernel started: 45ab2da6-7466-408c-aa5a-98f7db54e711
[W 10:14:00.341 NotebookApp] Replacing stale connection: aceb78ee-73e4-4481-9993-63e5ee8f72cb:AEA3C6B2B0A440FC84FF3BAF5F5CB615
Process SpawnPoolWorker-2:
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
Process SpawnPoolWorker-1:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
Process SpawnPoolWorker-4:
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
Process SpawnPoolWorker-3:
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
Process SpawnPoolWorker-5:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
Process SpawnPoolWorker-6:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
Traceback (most recent call last):
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Process SpawnPoolWorker-7:
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Process SpawnPoolWorker-8:
Process SpawnPoolWorker-9:
Process SpawnPoolWorker-10:
Traceback (most recent call last):
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
Process SpawnPoolWorker-11:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Process SpawnPoolWorker-14:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
Traceback (most recent call last):
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
Traceback (most recent call last):
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
[W 10:14:15.043 NotebookApp] 404 GET /api/kernels/c1224db6-69c6-470e-b74c-4c7b94fb48fe/channels?session_id=D8DC8A440B044EED8EBCA374EBEAF7C6 (127.0.0.1): Kernel does not exist: c1224db6-69c6-470e-b74c-4c7b94fb48fe
[W 10:14:15.046 NotebookApp] 404 GET /api/kernels/c1224db6-69c6-470e-b74c-4c7b94fb48fe/channels?session_id=D8DC8A440B044EED8EBCA374EBEAF7C6 (127.0.0.1) 7.48ms referer=None
</code>```

答:
I got multiprocessing to work from within a Jupyter notebook on Windows by saving my function in a separate .py file and including that file in my notebook.

Example:

f.py:

```<code>def f(name, output):
  output.put('hello {0}'.format(name))
  return
</code>```

Code in Jupyter notebook:

```<code>from multiprocessing import Process, Queue

#Having the function definition here results in
#AttributeError: Can't get attribute 'f' on <module '__main__' (built-in)>

#The solution seems to be importing the function from a separate file.

import f

#Also, the original version of f only had a print statement in it.
#That doesn't work with Process - in the sense that it prints to the console
#instead of the notebook.
#The trick is to let f write the string to print into an output-queue.
#When Process is done, the result is retrieved from the queue and printed.

if __name__ == '__main__':

   # Define an output queue
   output=Queue()

   # Setup a list of processes that we want to run
   p = Process(target=f.f, args=('Bob',output))

   # Run process
   p.start()

   # Exit the completed process
   p.join()

   # Get process results from the output queue
   result = output.get(p)

   print(result)
</code>```

I'm a Python newby and I may have missed all sorts of details, but this works for me.

Body:
I am trying to run a simple command that guesses gender by name using multiprocessing. This code worked on a previous machine so perhaps my setup had something to do with it.

Below is my multiprocessing code:

import sys
import gender_guesser.detector as gender
import multiprocessing
import time

d = gender.Detector()

def guess_gender (name):
    n = name.title() # make first letter upper case and the rest lower case
    g = d.get_gender(n) # guess gender
    return g

ls = ['john','joe','amamda','derick','peter','ashley','john','joe','amamda','derick','peter','ashley']

t=time.time()

results=[]
def callBack(x):
    results.append(x)

pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()-1, maxtasksperchild=1)

for n in ls:
    print (n)
    pool.apply_async(guess_gender,args=[n],callback=callBack)

pool.close()
pool.join()

results = pd.concat(results)

print(time.time()-t)

It simply runs and doesn't do anything. In my cmd window, I see the following at the end of an error message:

AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>

Am running python version 3.6.1 on Anaconda:

import sys
print(sys.version)
3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]

Update: Still cannot get it to work. Below is the entire cmd log when I ran the code provided. I appreciate any thoughts you may have!

C:\Users\ywu\Google Drive>jupyter notebook
[I 10:13:43.954 NotebookApp] Serving notebooks from local directory: C:\Users\ywu\Google Drive
[I 10:13:43.954 NotebookApp] 0 active kernels
[I 10:13:43.955 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=255a5c0c9af337a1c2187feb63f1c426fb903e5929a0b2f0
[I 10:13:43.956 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 10:13:43.959 NotebookApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://localhost:8888/?token=255a5c0c9af337a1c2187feb63f1c426fb903e5929a0b2f0
[I 10:13:44.264 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[W 10:13:44.319 NotebookApp] 404 GET /api/kernels/aceb78ee-73e4-4481-9993-63e5ee8f72cb/channels?session_id=AEA3C6B2B0A440FC84FF3BAF5F5CB615 (127.0.0.1): Kernel does not exist: aceb78ee-73e4-4481-9993-63e5ee8f72cb
[W 10:13:44.328 NotebookApp] 404 GET /api/kernels/aceb78ee-73e4-4481-9993-63e5ee8f72cb/channels?session_id=AEA3C6B2B0A440FC84FF3BAF5F5CB615 (127.0.0.1) 20.07ms referer=None
[I 10:13:54.740 NotebookApp] Creating new notebook in /code/python
[I 10:13:55.241 NotebookApp] Kernel started: 45ab2da6-7466-408c-aa5a-98f7db54e711
[W 10:14:00.341 NotebookApp] Replacing stale connection: aceb78ee-73e4-4481-9993-63e5ee8f72cb:AEA3C6B2B0A440FC84FF3BAF5F5CB615
Process SpawnPoolWorker-2:
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
Process SpawnPoolWorker-1:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
Process SpawnPoolWorker-4:
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
Process SpawnPoolWorker-3:
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
Process SpawnPoolWorker-5:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
Process SpawnPoolWorker-6:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
Traceback (most recent call last):
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Process SpawnPoolWorker-7:
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Process SpawnPoolWorker-8:
Process SpawnPoolWorker-9:
Process SpawnPoolWorker-10:
Traceback (most recent call last):
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
Traceback (most recent call last):
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
Process SpawnPoolWorker-11:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
Process SpawnPoolWorker-14:
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
Traceback (most recent call last):
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
Traceback (most recent call last):
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 249, in _bootstrap
    self.run()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker
    task = get()
  File "C:\Users\ywu\AppData\Local\Continuum\Anaconda3\lib\multiprocessing\queues.py", line 345, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'guess_gender' on <module '__main__' (built-in)>
[W 10:14:15.043 NotebookApp] 404 GET /api/kernels/c1224db6-69c6-470e-b74c-4c7b94fb48fe/channels?session_id=D8DC8A440B044EED8EBCA374EBEAF7C6 (127.0.0.1): Kernel does not exist: c1224db6-69c6-470e-b74c-4c7b94fb48fe
[W 10:14:15.046 NotebookApp] 404 GET /api/kernels/c1224db6-69c6-470e-b74c-4c7b94fb48fe/channels?session_id=D8DC8A440B044EED8EBCA374EBEAF7C6 (127.0.0.1) 7.48ms referer=None

Body:
I got multiprocessing to work from within a Jupyter notebook on Windows by saving my function in a separate .py file and including that file in my notebook.

Example:

f.py:

def f(name, output):
  output.put('hello {0}'.format(name))
  return

Code in Jupyter notebook:

from multiprocessing import Process, Queue

#Having the function definition here results in
#AttributeError: Can't get attribute 'f' on <module '__main__' (built-in)>

#The solution seems to be importing the function from a separate file.

import f

#Also, the original version of f only had a print statement in it.
#That doesn't work with Process - in the sense that it prints to the console
#instead of the notebook.
#The trick is to let f write the string to print into an output-queue.
#When Process is done, the result is retrieved from the queue and printed.

if __name__ == '__main__':

   # Define an output queue
   output=Queue()

   # Setup a list of processes that we want to run
   p = Process(target=f.f, args=('Bob',output))

   # Run process
   p.start()

   # Exit the completed process
   p.join()

   # Get process results from the output queue
   result = output.get(p)

   print(result)

I'm a Python newby and I may have missed all sorts of details, but this works for me.


来源: stackexchange

问:
C# Regex does not match strings with a dot in
I am trying to do a find replace in a string of text. I am using Regex like this:

```<code>Regex regexText = new Regex("Test.Value");

strText = regexText.Replace(strText, value);
</code>```

In this example I am trying to find the string "Test.Value" in a text string. However if this value appears in the string the replace does not happen.

If I remove the dots eg:

```<code>Regex regexText = new Regex("TEST");

strText = regexText.Replace(strText, value);
</code>```

If I put the word "TEST" in the string, it replaces it just fine.

Is there a way to get this to work with strings with "."'s in?

答:
You have to escape the dot:

```<code>Regex regexText = new Regex(@"Test\.Value");
</code>```

As you wrote it, the regex is just looking for "Test", followed by any character except a line feed, followed by "Value".

On the top of that, if the text you are looking for is a little bit different, a case insensitive matching could help you out:

```<code>Regex regexText = new Regex(@"Test\.Value", RegexOptions.IgnoreCase);
</code>```

Anyway, in this case I don't think a Regex is necessary. A simple string replace should do the job:

```<code>strText.Replace("Test.Value", value);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to do a find replace in a string of text. I am using Regex like this:

Regex regexText = new Regex("Test.Value");

strText = regexText.Replace(strText, value);

In this example I am trying to find the string "Test.Value" in a text string. However if this value appears in the string the replace does not happen.

If I remove the dots eg:

Regex regexText = new Regex("TEST");

strText = regexText.Replace(strText, value);

If I put the word "TEST" in the string, it replaces it just fine.

Is there a way to get this to work with strings with "."'s in?

Body:
You have to escape the dot:

Regex regexText = new Regex(@"Test\.Value");

As you wrote it, the regex is just looking for "Test", followed by any character except a line feed, followed by "Value".

On the top of that, if the text you are looking for is a little bit different, a case insensitive matching could help you out:

Regex regexText = new Regex(@"Test\.Value", RegexOptions.IgnoreCase);

Anyway, in this case I don't think a Regex is necessary. A simple string replace should do the job:

strText.Replace("Test.Value", value);


问:
numpy.partition in JavaScript
Is there a readily available equivalent to numpy.partition in JavaScript, via a library or built in?

It does not seem like any of the popular relevant libraries such as underscore.js provide such a function. I am asking because I would like to be able to find the n highest (or lowest) elements in an array for the general case, without having to implement quickselect or introselect myself.

Partitioning an array at index n rearranges the array so that the element at n is in sorted order, and all the elements with index greater than n are larger than that element at n. Alternatively, the elements at indices less than n can all be less than the element at n. Either way, it is a partial sort that guarantees the position of a particular element and the distribution of the elements above and below it.

A full sort satisfies the same conditions of course, but runs in O(n log n) time, while partitioning generally runs in O(n) time (average case for quickselect, worst case for introselect).

The jQuery plugin QuickSelect does something completely different, despite the promising name.

Part of the motivation for this question: Possible to use Math.min to get second smallest number from array?

答:
Package to do quickselect.

Github

NPM

(I've never used this package, but from the README, it seems to be what OP is looking for)

Title: numpy.partition in JavaScript


问:
c++ char display only ascii value?
I want to build int array from string. However my issue is that it takes string or char as ascii, not its value.

```<code>#include <cstdio>
#include <string>

using namespace std;

int *arr = new int[10];
int j = 0;
string answer;
cout << "Enter the value: ";
// (4,3,1,2) is typed
cin >> answer;

void buildArr(string s){
    for(int i = 0; i<10; i++){
        if(s[i] != '(' || s[i] != ',' || s[i] != ')'){
            arr[j] = (int)s[i];
            j++;
        }
   }
}
</code>```

It supposed to make arr holds 4 3 1 2. but it contains 40 52 44 51 44 49 44 50 41 which is same as (4,3,1,2).

It takes ( as 40 which is ascii number, it does not recognize it as '('. So my if statement does not filter out (  , ) this three characters. How can I properly compare char?

I searched through other questions, and tried s[i]-=0 but did not have any luck. Thanks in advance!

答:
You should use and (&&) instead of or (||)

You need to convert ASCII values into integers, instead of (int)s[i] you can use s[i] - '0'

Title: c++ char display only ascii value?

Body:
I want to build int array from string. However my issue is that it takes string or char as ascii, not its value.

#include <cstdio>
#include <string>

using namespace std;

int *arr = new int[10];
int j = 0;
string answer;
cout << "Enter the value: ";
// (4,3,1,2) is typed
cin >> answer;

void buildArr(string s){
    for(int i = 0; i<10; i++){
        if(s[i] != '(' || s[i] != ',' || s[i] != ')'){
            arr[j] = (int)s[i];
            j++;
        }
   }
}

It supposed to make arr holds 4 3 1 2. but it contains 40 52 44 51 44 49 44 50 41 which is same as (4,3,1,2).

It takes ( as 40 which is ascii number, it does not recognize it as '('. So my if statement does not filter out (  , ) this three characters. How can I properly compare char?

I searched through other questions, and tried s[i]-=0 but did not have any luck. Thanks in advance!


问:
Writing to Excel
I'm testing out how to fill in info to my excel sheet and wrote a simple test program

```<code>use Win32::OLE qw(in);
use Win32::OLE::Const "Microsoft Excel";

$Win32::OLE::Warn = 3;

my $excel = Win32::OLE->new("Excel.Application", "Quit");
my $book = $excel->Workbooks->Add();
my $sheet = $book->Worksheets(1);
my $range = $sheet->Range($sheet->Cells(1,1), $sheet->Cells(5,5));

my $mat = $range->{Value};
$mat[1][1] = "x";
#for my $row (@$mat){
#   print "$i\n";
#   for my $cel (@{$row}){
#       $cel = "x";
#   }
#}

$range->{Value} = $mat;

my $fso = Win32::OLE->new("Scripting.FileSystemObject");
my $map = $fso->GetAbsolutePathName(".");
my $padnaam = $map . "\\test.xlsx";
$book->SaveAs($padnaam);
</code>```

When I use the commented out code, there is a nice square of "x"s but when I just try to assign an x by index nothing appears.
I'm guessing I'm not referencing the array correctly but after looking trough the perlreftut and all questions I could find about 2D arrays I can't really figure out the correct sequence that should be used instead.

So, how can I add values to the range by index?

答:
$mat is an array reference. You need to dereference it:</p>

```<code>$$mat[1][1] = "x";
</code>```

Title: Writing to Excel

Body:
I'm testing out how to fill in info to my excel sheet and wrote a simple test program

use Win32::OLE qw(in);
use Win32::OLE::Const "Microsoft Excel";

$Win32::OLE::Warn = 3;

my $excel = Win32::OLE->new("Excel.Application", "Quit");
my $book = $excel->Workbooks->Add();
my $sheet = $book->Worksheets(1);
my $range = $sheet->Range($sheet->Cells(1,1), $sheet->Cells(5,5));

my $mat = $range->{Value};
$mat[1][1] = "x";
#for my $row (@$mat){
#   print "$i\n";
#   for my $cel (@{$row}){
#       $cel = "x";
#   }
#}

$range->{Value} = $mat;

my $fso = Win32::OLE->new("Scripting.FileSystemObject");
my $map = $fso->GetAbsolutePathName(".");
my $padnaam = $map . "\\test.xlsx";
$book->SaveAs($padnaam);

When I use the commented out code, there is a nice square of "x"s but when I just try to assign an x by index nothing appears.
I'm guessing I'm not referencing the array correctly but after looking trough the perlreftut and all questions I could find about 2D arrays I can't really figure out the correct sequence that should be used instead.

So, how can I add values to the range by index?

Body:
$mat is an array reference. You need to dereference it:

$$mat[1][1] = "x";


问:
How can I do multi-parameter queries using Google Chrome custom search engines?
I am migrating from Firefox to Chrome and I haven't been able to copy or emulate my multiple criteria queries. In Firefox it works as a breeze using a javascript script that I have found here but after a lot of testing I think is not possible to implement in Chrome. Take a look at my modified version for converting currency:</p>

```<code>javascript:var s='%s'; url='http://www.google.com/finance/converter?a=%s&from=%s&to=%s'; t=''; qc=0; chunks=url.split('%s'); for(i=0; i<s.length; i++){if(s.charAt(i)=='"')qc=qc^1; t+=((s.charAt(i)==' '&&qc)?'^':s.charAt(i)); }args=t.split(/\s/); nurl=''; for(i=0; i<chunks.length; i++){nurl+=chunks[i]; if(args[i]!=undefined) {args[i]=args[i].replace(/\^/g,' '); nurl+=args[i]; }}location.replace(nurl,'< BR>');
</code>```

答:
Chrome has supported this since at least the date of your question. Here is how I do it:

```<code>javascript: (function(){
var s='%s';
url='https://www.google.com/search?hl=en&q=%s&tbo=1&tbs=qdr:%s';
query='';
urlchunks=url.split('%s');
schunks=s.split(';');
for(i=0; i<schunks.length; i++)query+=urlchunks[i]+schunks[i];
location.replace(query);
})();
</code>```

You can use any URL that has more than one paramenter, which takes more than one argument.

To use from omnibox: search word(s);search word(s)

Body:
I am migrating from Firefox to Chrome and I haven't been able to copy or emulate my multiple criteria queries. In Firefox it works as a breeze using a javascript script that I have found here but after a lot of testing I think is not possible to implement in Chrome. Take a look at my modified version for converting currency:

javascript:var s='%s'; url='http://www.google.com/finance/converter?a=%s&from=%s&to=%s'; t=''; qc=0; chunks=url.split('%s'); for(i=0; i<s.length; i++){if(s.charAt(i)=='"')qc=qc^1; t+=((s.charAt(i)==' '&&qc)?'^':s.charAt(i)); }args=t.split(/\s/); nurl=''; for(i=0; i<chunks.length; i++){nurl+=chunks[i]; if(args[i]!=undefined) {args[i]=args[i].replace(/\^/g,' '); nurl+=args[i]; }}location.replace(nurl,'
');

Body:
Chrome has supported this since at least the date of your question. Here is how I do it:

javascript: (function(){
var s='%s';
url='https://www.google.com/search?hl=en&q=%s&tbo=1&tbs=qdr:%s';
query='';
urlchunks=url.split('%s');
schunks=s.split(';');
for(i=0; i<schunks.length; i++)query+=urlchunks[i]+schunks[i];
location.replace(query);
})();

You can use any URL that has more than one paramenter, which takes more than one argument.

To use from omnibox: search word(s);search word(s)


问:
Execute button's command after the animation
In my application i have added a frame-by-frame animation to my button's selector. So, when I press the button the application is started and another activity is launched. The problem is that if I press the button very quickly the application reaches only to the second frame. I would like to launch the next activity after the animation is ended. Is that possible?</p>

答: You should set an AnimationListener to your animation and start another activity on animation end.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


答:
First of all, this:

```<code>if(s[i] != '(' || s[i] != ',' || s[i] != ')')
</code>```

should be

```<code>if(s[i] != '(' && s[i] != ',' && s[i] != ')')
</code>```

The way you had it, as s[i] can't ever be both '(' and ',', it will always evaluate to true.

Secondly,

```<code>arr[j] = (int)s[i];
</code>```

should be

```<code> arr[j] = s[i] - '0'
</code>```

If you just cast it to an int, then you'll get the ascii value. To convert it to the actual number, subtract the ascii value of zero. In ascii, the numbers are all sequential, so if you subtract the ascii value for zero you get the offset in that list. There's a table here.

Title: c++ char display only ascii value?

Body:
First of all, this:

if(s[i] != '(' || s[i] != ',' || s[i] != ')')

should be

if(s[i] != '(' && s[i] != ',' && s[i] != ')')

The way you had it, as s[i] can't ever be both '(' and ',', it will always evaluate to true.

Secondly,

arr[j] = (int)s[i];

should be

 arr[j] = s[i] - '0'

If you just cast it to an int, then you'll get the ascii value. To convert it to the actual number, subtract the ascii value of zero. In ascii, the numbers are all sequential, so if you subtract the ascii value for zero you get the offset in that list. There's a table here.


问:
phpinfo() outputs nothing
I've tried phpinfo() but it output nothing. It is interesting that php-r "phpinfo();" works correctly while using phpinfo() in web outputs nothing.
Again, nothing is written to error.log too. php.ini is empty.

I don't know what to do now.

Edit:

Thanks to lanzz, I got that phpinfo() requires no output before it.

答:
Just wanted to add, that I was using short tags '<?'

```<code><? phpinfo();
</code>```

which was failing, becuase I was using short tags when they were disabled so it should have been

```<code><?php phpinfo();
</code>```

Title: phpinfo() outputs nothing

Body:
Just wanted to add, that I was using short tags '<?'

<? phpinfo();

which was failing, becuase I was using short tags when they were disabled so it should have been

<?php phpinfo();


问:
FreeRTOS Static for safety application
Hy,

I'm interested to a safe sw architecture based on FreeRTOS on a TMS570 for a safety application,

by my point of view for a safety application it is better to use the static version of task, queue, ..

xQueueCreateStatic
xTaskCreateStatic
xTimerCreateStatic
.. and so on

do you agree on this or you think I could use also the non static version?
Thanks
Antonio

答:
As you imply, FreeRTOS gives you both options.  Some of the pros and cons of both are listed on the following page, so I won't repeat them here: http://www.freertos.org/Static_Vs_Dynamic_Memory_Allocation.html

Only you can answer your question though, as it depends on what your application is doing.  The answer would be very different between whether your application is creating all its resources at boot time and then never deleting them, or if it is continuously creating and deleting lots of different sized memory blocks at run time.  As this is a safety application I would be surprised if it was doing lots of memory allocation and deallocation at run time - but if it were you would have to concern yourself with memory fragmentation, dealing with heap exhaustion, and non deterministic behaviour of the memory allocater (not ever allocation takes the same time).  Using heap_4.c in FreeRTOS should prevent fragmentation in most cases, but 'should' is probably not good enough for a safety application.

If all the resources are allocated dynamically, but only at boot time (which is actually the case for most application), then none of these potential pitfalls apply, and there is really no reason not to use dynamic memory.

Title: FreeRTOS Static for safety application


问:
JavaScript Add function called as many times as you wanted
The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that? </p>

```<code>function add () {

}
add(1)(2)(3)();  //6
add(5)(6)(7)(8)(9)()  //35
</code>```

答:
I think this is exactly what you need:

function add(value) {
   return (val) => val !== undefined ? add(value + val) : value;
}

console.log(add(2)(2)()); //4
console.log(add(2)(2)(5)(5)()); //14
console.log(add(1)(1)(1)(1)(1)()); //5
console.log(add(1)(1)(0)(1)(1)()); //4```

How it works

For every call it declares a function inside, in result it creates a closure(persistent scope) in every call. Function created in that way has access to its parameter + previous call parameter due to existing closure.

So if I call add(2)(3)():

add(2) - returns function with visible 2 value

add(2)(3) - calls second function with input 2 + 3 and return third function with visible value equal 5

add(2)(3)() - ends computation due to empty param and returns the value

To finish the computation pipe the last call needs to be without a value.

Body:
The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that?

function add () {

}
add(1)(2)(3)();  //6
add(5)(6)(7)(8)(9)()  //35

Body:
I think this is exactly what you need:

function add(value) {
   return (val) => val !== undefined ? add(value + val) : value;
}

console.log(add(2)(2)()); //4
console.log(add(2)(2)(5)(5)()); //14
console.log(add(1)(1)(1)(1)(1)()); //5
console.log(add(1)(1)(0)(1)(1)()); //4

How it works

For every call it declares a function inside, in result it creates a closure(persistent scope) in every call. Function created in that way has access to its parameter + previous call parameter due to existing closure.

So if I call add(2)(3)():

add(2) - returns function with visible 2 value

add(2)(3) - calls second function with input 2 + 3 and return third function with visible value equal 5

add(2)(3)() - ends computation due to empty param and returns the value

To finish the computation pipe the last call needs to be without a value.


问:
Select TailNumber with MaxAirTime by UniqueCarrier
I have a similar problem with my own dataset and decided to practice on an example dataset. I'm trying to select the TailNumbers associated with the Max Air Time by Carrier.

Here's my solution thus far:

```<code>library(hflights)

hflights %>%
  group_by(UniqueCarrier, TailNum) %>%
  summarise(maxAT = max(AirTime)) %>%
  arrange(desc(maxAT))
</code>```

This provides three columns to which I can eyeball the max Air Time values and then filter them down using filter() statements. However, I feel like there's a more elegant way to do so.

答:
You can use which.max to find out the row with the maximum AirTime and then slice the rows:

```<code>hflights %>%
    select(UniqueCarrier, TailNum, AirTime) %>%
    group_by(UniqueCarrier) %>%
    slice(which.max(AirTime))

# A tibble: 15 x 3
# Groups:   UniqueCarrier [15]
#   UniqueCarrier TailNum AirTime
#           <chr>   <chr>   <int>
# 1            AA  N3FNAA     161
# 2            AS  N626AS     315
# 3            B6  N283JB     258
# 4            CO  N77066     549
# 5            DL  N358NB     188
# 6            EV  N716EV     173
# 7            F9  N905FR     190
# 8            FL  N176AT     186
# 9            MQ  N526MQ     220
#10            OO  N744SK     225
#11            UA  N457UA     276
#12            US  N950UW     212
#13            WN  N256WN     288
#14            XE  N11199     204
#15            YV  N907FJ     150
</code>```

Body:
I have a similar problem with my own dataset and decided to practice on an example dataset. I'm trying to select the TailNumbers associated with the Max Air Time by Carrier.

Here's my solution thus far:

library(hflights)

hflights %>%
  group_by(UniqueCarrier, TailNum) %>%
  summarise(maxAT = max(AirTime)) %>%
  arrange(desc(maxAT))

This provides three columns to which I can eyeball the max Air Time values and then filter them down using filter() statements. However, I feel like there's a more elegant way to do so.

Body:
You can use which.max to find out the row with the maximum AirTime and then slice the rows:

hflights %>%
    select(UniqueCarrier, TailNum, AirTime) %>%
    group_by(UniqueCarrier) %>%
    slice(which.max(AirTime))

# A tibble: 15 x 3
# Groups:   UniqueCarrier [15]
#   UniqueCarrier TailNum AirTime
#           <chr>   <chr>   <int>
# 1            AA  N3FNAA     161
# 2            AS  N626AS     315
# 3            B6  N283JB     258
# 4            CO  N77066     549
# 5            DL  N358NB     188
# 6            EV  N716EV     173
# 7            F9  N905FR     190
# 8            FL  N176AT     186
# 9            MQ  N526MQ     220
#10            OO  N744SK     225
#11            UA  N457UA     276
#12            US  N950UW     212
#13            WN  N256WN     288
#14            XE  N11199     204
#15            YV  N907FJ     150


问:
CMake: Getting a list of directories (non-recursive)
In CMake, how can I get a non-recursive list of directories that exist in a certain directory?
I can see that using GLOB isn't recommended.</p>

答:
Why wouldn't GLOB be recommended? That's what the GLOB is for. I love GLOB, especially in cases like this where it's extremely helpful to grab multiple items.

The macro from this question may be what you're looking for.

```<code>MACRO(SUBDIRLIST result curdir)
  FILE(GLOB children RELATIVE ${curdir} ${curdir}/*)
  SET(dirlist "")
  FOREACH(child ${children})
    IF(IS_DIRECTORY ${curdir}/${child})
      LIST(APPEND dirlist ${child})
    ENDIF()
  ENDFOREACH()
  SET(${result} ${dirlist})
ENDMACRO()
</code>```

You basically grab the items from the current source directory, check to see if it's a directory, and if so, append it to a list.

Credit to refaim in the link for that macro.

Body:
Why wouldn't GLOB be recommended? That's what the GLOB is for. I love GLOB, especially in cases like this where it's extremely helpful to grab multiple items.

The macro from this question may be what you're looking for.

MACRO(SUBDIRLIST result curdir)
  FILE(GLOB children RELATIVE ${curdir} ${curdir}/*)
  SET(dirlist "")
  FOREACH(child ${children})
    IF(IS_DIRECTORY ${curdir}/${child})
      LIST(APPEND dirlist ${child})
    ENDIF()
  ENDFOREACH()
  SET(${result} ${dirlist})
ENDMACRO()

You basically grab the items from the current source directory, check to see if it's a directory, and if so, append it to a list.

Credit to refaim in the link for that macro.


问:
Loading Page for Shiny Dashboard
I am trying to create a loading page for my dashboard but I can't seem to get it to work. I followed the example here; Shiny Dashboard - display a dedicated "loading.." page until initial loading of the data is done but it is for fluid page and not shiny dashboard and I can't figure out how to adapt it.

Any help would be appreciated!

I would preferably like the loading page just to be a fluid page (no header or sidebar) and then have my main dashboard have the shiny dashboard aspects.

Extra: If I could add a gif to the loading screen, that would be amazing. Something like:

```<code><iframe src="https://giphy.com/embed/BlmF3MhGfa4SY" width="480" height="360" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/plane-BlmF3MhGfa4SY">via GIPHY</a></p>
</code>```

[break]

```<code>library (shiny)
library (shinydashboard)
library(shinyjs)

rm(list=ls())

appCSS <- "
#loading_page {
  position: absolute;
  background: #000000;
  opacity: 0.9;
  z-index: 100;
  left: 0;
  right: 0;
  height: 100%;
  text-align: center;
  color: #FFFFFF;
}
"
header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody("It worked!")

ui <- dashboardPage(
  useShinyjs(),
  inlineCSS(appCSS),
  div(
    id = "loading_page",
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody("Loading...")
  ),
  hidden(
    div(
      id = "main_content",
      header, sidebar, body
    )
  )
)

server = function(input, output, session) {
    # Simulate work being done for 4 second
    Sys.sleep(4)

    hide("loading_page")
    show("main_content")
  }

shinyApp(ui, server)
</code>```

答:
Try this library shinycssloaders

```<code>library(shiny)
library(shinycssloaders)
library(highcharter)

ui <- fluidPage(
        mainPanel(
                plotOutput("my_plot")  %>% withSpinner(color="#0dc5c1")
        )
)

server <- function(input, output){

        output$my_plot <- renderPlot({
                Sys.sleep(1)
                plot(mtcars)})
}

shinyApp(ui, server)
</code>```

Title: Loading Page for Shiny Dashboard

Body:
I am trying to create a loading page for my dashboard but I can't seem to get it to work. I followed the example here; Shiny Dashboard - display a dedicated "loading.." page until initial loading of the data is done but it is for fluid page and not shiny dashboard and I can't figure out how to adapt it.

Any help would be appreciated!

I would preferably like the loading page just to be a fluid page (no header or sidebar) and then have my main dashboard have the shiny dashboard aspects.

Extra: If I could add a gif to the loading screen, that would be amazing. Something like:

via GIPHY

[break]

library (shiny)
library (shinydashboard)
library(shinyjs)

rm(list=ls())

appCSS <- "
#loading_page {
  position: absolute;
  background: #000000;
  opacity: 0.9;
  z-index: 100;
  left: 0;
  right: 0;
  height: 100%;
  text-align: center;
  color: #FFFFFF;
}
"
header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody("It worked!")

ui <- dashboardPage(
  useShinyjs(),
  inlineCSS(appCSS),
  div(
    id = "loading_page",
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody("Loading...")
  ),
  hidden(
    div(
      id = "main_content",
      header, sidebar, body
    )
  )
)

server = function(input, output, session) {
    # Simulate work being done for 4 second
    Sys.sleep(4)

    hide("loading_page")
    show("main_content")
  }

shinyApp(ui, server)

Body:
Try this library shinycssloaders

library(shiny)
library(shinycssloaders)
library(highcharter)

ui <- fluidPage(
        mainPanel(
                plotOutput("my_plot")  %>% withSpinner(color="#0dc5c1")
        )
)

server <- function(input, output){

        output$my_plot <- renderPlot({
                Sys.sleep(1)
                plot(mtcars)})
}

shinyApp(ui, server)


问:
omniauth-facebook gem: request.env["omniauth.auth"] is nil
I'm using the omniauth-facebook gem with devise. It was working until recently. I also recently upgrated to Rails 5.0.1 from Rails 4, but I'm not sure that's the cause.

I currently have 0 users, and I'm logged into Facebook. But when I try to sign up for my app with Facebook on localhost, I get this error:

```<code>NoMethodError in RegistrationsController#facebook
undefined method `provider' for nil:NilClass
</code>```

Here is my User model. I marked the line that the error highlights.

User.rb

```<code>  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :omniauthable, :omniauth_providers => [:facebook]

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user| #ERROR
      @data = auth.info
      user.name = @data.name
      # ...
    end
  end
</code>```

RegistrationsController

```<code>  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
</code>```

Also, here's my link:

```<code><%= link_to "fb", user_facebook_omniauth_callback_path(:facebook, thing: @thing.id, degree: @degree, :format => :js) %>
</code>```

The HTML Output:

```<code><a href=\"/auth/facebook/callback.js?thing=2\">fb<\/a>
</code>```

And the path:

```<code>localhost:3000/auth/facebook/callback.js?thing=2
</code>```

So the problem is that request.env["omniauth.auth"] is nil for some reason. I can't find any traces of similar errors in any documentation.

Anyone encounter this before or have any thoughts?

答: I had the same issue and solved it by removing :omniauthable from User model

Body:
I'm using the omniauth-facebook gem with devise. It was working until recently. I also recently upgrated to Rails 5.0.1 from Rails 4, but I'm not sure that's the cause.

I currently have 0 users, and I'm logged into Facebook. But when I try to sign up for my app with Facebook on localhost, I get this error:

NoMethodError in RegistrationsController#facebook
undefined method `provider' for nil:NilClass

Here is my User model. I marked the line that the error highlights.

User.rb

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :omniauthable, :omniauth_providers => [:facebook]

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user| #ERROR
      @data = auth.info
      user.name = @data.name
      # ...
    end
  end

RegistrationsController

  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

Also, here's my link:

<%= link_to "fb", user_facebook_omniauth_callback_path(:facebook, thing: @thing.id, degree: @degree, :format => :js) %>

The HTML Output:

fb<\/a>

And the path:

localhost:3000/auth/facebook/callback.js?thing=2

So the problem is that request.env["omniauth.auth"] is nil for some reason. I can't find any traces of similar errors in any documentation.

Anyone encounter this before or have any thoughts?


问:
Image on UIBarButtonItem
In my iPhone application, I'm adding a toolbar on UINavigation controller as navigation bar do not take more then two bar buttons on it.
So far .. I have successfully added the UIToolBar with three BarButtonItems on it. However I am not able to display an image on BarButtonItems.

Can any one tell me .. how to add image on UIToolBar BarButtonItems? Where ToolBar is already added on nav controller.

答:
Set a custom view for the UIBarButtonItem, something like this </p>

```<code>    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    UIImage *yourImage = [UIImage imageNamed:@"yourImage.png"];
    [button setImage:yourImage forState:UIControlStateNormal];
    [button addTarget:self action:@selector(yourButtonAction) forControlEvents:UIControlEventTouchUpInside];

    [barButton setCustomView:button];
    self.navigationItem.rightBarButtonItem = barButton;
    [barButton release];
</code>```

Title: Image on UIBarButtonItem

Body:
Set a custom view for the UIBarButtonItem, something like this

    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    UIImage *yourImage = [UIImage imageNamed:@"yourImage.png"];
    [button setImage:yourImage forState:UIControlStateNormal];
    [button addTarget:self action:@selector(yourButtonAction) forControlEvents:UIControlEventTouchUpInside];

    [barButton setCustomView:button];
    self.navigationItem.rightBarButtonItem = barButton;
    [barButton release];


问:
Use 100% div width, if 50% width is too small
How could one go about creating a div, that would have a default size of XX%, however, if the screen gets too small it would switch into 100% size? I have tried using min-width property but the problem with this is that it will not be responsive after the min-width is reached and will overflow if the screen is even smaller.

答:
You can do it with @media queries, e.g.:

div {
  width: 50%;
  height: 100px;
  border: 1px solid;
}

@media (max-width: 568px) { /* adjust to your needs */
  div {width: 100%}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Body:
You can do it with @media queries, e.g.:

div {
  width: 50%;
  height: 100px;
  border: 1px solid;
}

@media (max-width: 568px) { /* adjust to your needs */
  div {width: 100%}
}

<div></div>


答:
You need to do

```<code>(int)str[i] - '0';
</code>```

This will give you 4 instead of 40, etc.

Title: c++ char display only ascii value?

Body:
I want to build int array from string. However my issue is that it takes string or char as ascii, not its value.

#include <cstdio>
#include <string>

using namespace std;

int *arr = new int[10];
int j = 0;
string answer;
cout << "Enter the value: ";
// (4,3,1,2) is typed
cin >> answer;

void buildArr(string s){
    for(int i = 0; i<10; i++){
        if(s[i] != '(' || s[i] != ',' || s[i] != ')'){
            arr[j] = (int)s[i];
            j++;
        }
   }
}

It supposed to make arr holds 4 3 1 2. but it contains 40 52 44 51 44 49 44 50 41 which is same as (4,3,1,2).

It takes ( as 40 which is ascii number, it does not recognize it as '('. So my if statement does not filter out (  , ) this three characters. How can I properly compare char?

I searched through other questions, and tried s[i]-=0 but did not have any luck. Thanks in advance!

Body:
You need to do

(int)str[i] - '0';

This will give you 4 instead of 40, etc.


问:
Mongodb: Finding items that are not present in the collection
Given a collection called "inventory" that has 2 items

```<code>{
    "_id" : ObjectId("5a0de48bce523d1df7546e9c"),
    "name" : "tshirt",
    "qty" : 5
},

{
    "_id" : ObjectId("5a0de4acce523d1df7546ea8"),
    "name" : "pant",
    "qty" : 15
}
</code>```

if I do a query like this

```<code>db.inventory.find( { qty: { $in: [ 5, 10 ] } } )
</code>```

It will give the first object.

I want to construct a result like this in json form later to be returned through an API.

```<code>{
 "5" : "true"
 "10" : "false"
}
</code>```

I have thought of the following options

Creating a temporary collection of [10 ,15) and then using aggregrate function $lookup

Looping through the list of items and doing a comparison check with [10,15] and constructing the desired output.

What other options can be done? The example is a small one but in the real application, the number of items is going to be in hundreds and thousands.

答:
The biggest challenge here is actually converting the int values in the input array into string keys. I think I've once seen code on Stack Overflow that would allow doing that but I also seem to remember it being terribly hacky.

The following code gets you pretty close to your goal, though.

```<code>db.collection.aggregate({
    $group: {
        "_id": null,
        "qties": {
            $addToSet: "$qty" // create an array of all unique "qty" values
        }
    }
}, {
    $project: {
        "_id": 0,
        "results": {
            $map: {
                input: values, // go through all values that we want to test, e.g. [ 5, 10 ]
                in: { // and map them into the following new structure
                    $arrayToObject: // transform our generated array of key-value pairs into an object
                    [[
                        {
                            "v": "$$this", // this will be just each value we look at - one by one
                            "k": { $cond: [ { $in: [ "$$this", "$qties" ] }, "true", "false" ] } // and this will tell us if the looked at value exists in our documents (or rather: in our array of unique values that we've generated in the $group stage)
                        }
                    ]]

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

This will spit out the following structure:

```<code>{
    "results" : [
        {
            "true" : 5.0
        },
        {
            "false" : 10.0
        }
    ]
}
</code>```

Alternatively, you can write the following:

```<code>var values = [ 5, 10 ]

db.getCollection('test').aggregate({
    $group: {
        "_id": null,
        "qties": {
            $addToSet: "$qty" // create an array of all unique "qty" values
        }
    }
}, {
    $project: {
        "results": {
            $map: {
                input: values, // go through all values that we want to test, e.g. [ 5, 10 ]
                in: { // and map them into the following new structure
                    "value": "$$this", // this will be just the value we look at
                    "found": { $cond: [ { $in: [ "$$this", "$qties" ] }, "true", "false" ] } // and this will tell us if the looked at value exists in our documents (in the array of unique values rather)
                }
            }
        }
    }
}, {
    $unwind: "$results" // flatten the results array
}, {
    $replaceRoot: {
        newRoot: "$results" // move the contents of the "results" field all the way up
    }
})
</code>```

...which will yield these two documents:

```<code>{
    "value" : 5.0,
    "found" : "true"
}
{
    "value" : 10.0,
    "found" : "false"
}
</code>```

Body:
Given a collection called "inventory" that has 2 items

{
    "_id" : ObjectId("5a0de48bce523d1df7546e9c"),
    "name" : "tshirt",
    "qty" : 5
},

{
    "_id" : ObjectId("5a0de4acce523d1df7546ea8"),
    "name" : "pant",
    "qty" : 15
}

if I do a query like this

db.inventory.find( { qty: { $in: [ 5, 10 ] } } )

It will give the first object.

I want to construct a result like this in json form later to be returned through an API.

{
 "5" : "true"
 "10" : "false"
}

I have thought of the following options

Creating a temporary collection of [10 ,15) and then using aggregrate function $lookup

Looping through the list of items and doing a comparison check with [10,15] and constructing the desired output.

What other options can be done? The example is a small one but in the real application, the number of items is going to be in hundreds and thousands.

Body:
The biggest challenge here is actually converting the int values in the input array into string keys. I think I've once seen code on Stack Overflow that would allow doing that but I also seem to remember it being terribly hacky.

The following code gets you pretty close to your goal, though.

db.collection.aggregate({
    $group: {
        "_id": null,
        "qties": {
            $addToSet: "$qty" // create an array of all unique "qty" values
        }
    }
}, {
    $project: {
        "_id": 0,
        "results": {
            $map: {
                input: values, // go through all values that we want to test, e.g. [ 5, 10 ]
                in: { // and map them into the following new structure
                    $arrayToObject: // transform our generated array of key-value pairs into an object
                    [[
                        {
                            "v": "$$this", // this will be just each value we look at - one by one
                            "k": { $cond: [ { $in: [ "$$this", "$qties" ] }, "true", "false" ] } // and this will tell us if the looked at value exists in our documents (or rather: in our array of unique values that we've generated in the $group stage)
                        }
                    ]]

                }
            }
        }
    }
})

This will spit out the following structure:

{
    "results" : [
        {
            "true" : 5.0
        },
        {
            "false" : 10.0
        }
    ]
}

Alternatively, you can write the following:

var values = [ 5, 10 ]

db.getCollection('test').aggregate({
    $group: {
        "_id": null,
        "qties": {
            $addToSet: "$qty" // create an array of all unique "qty" values
        }
    }
}, {
    $project: {
        "results": {
            $map: {
                input: values, // go through all values that we want to test, e.g. [ 5, 10 ]
                in: { // and map them into the following new structure
                    "value": "$$this", // this will be just the value we look at
                    "found": { $cond: [ { $in: [ "$$this", "$qties" ] }, "true", "false" ] } // and this will tell us if the looked at value exists in our documents (in the array of unique values rather)
                }
            }
        }
    }
}, {
    $unwind: "$results" // flatten the results array
}, {
    $replaceRoot: {
        newRoot: "$results" // move the contents of the "results" field all the way up
    }
})

...which will yield these two documents:

{
    "value" : 5.0,
    "found" : "true"
}
{
    "value" : 10.0,
    "found" : "false"
}


问:
How to hide my HTML drop-down menu correctly?
I made a drop-down menu consisting of a HTML input/button and some more buttons as drop-down menu items. The menu is shown as soon as hovered over the main button

```<code><div class="dropdown">
    <button id="dropdown-wifi" class="extended-button" onclick="showDropDown()">Available WiFi Hot Spots</button>
    <div id="ssid-dropdown" class="dropdown-content">
        <!-- drop-down menu items dynamically created by JavaScript -->
    </div>
</div>
</code>```

This is the hover event in CSS:

```<code>.dropdown:hover .dropdown-content {
    display: block;
}
</code>```

The JavaScript code that hides and later 'should' show again:

```<code>function showDropDown() {
    document.getElementById("ssid-dropdown").style.display = 'block';
}

function hideDropDown() {
    document.getElementById("ssid-dropdown").style.display = 'none';
}
</code>```

Now, the drop-down menu is properly shown as soon as I hover over the main button. But when selecting an item, I call hideDropDown() to hide the menu even if not hovered outside of the items.

I notified that as soon as the hideDropDown() function is called, the following is added in the CSS window of Chrome's debug windows:

```<code>element.style {
    display: none;
}
</code>```

I guess, that is a kind of CSS generated because my JavaScript function call of hideDropDown(). However, as soon as this element.stlye is occuring, the hovering/show of the drop-down menu doesn't work anymore.

Any ideas how to solve this issue?

答:
You can create class  with name hide and add next css:

```<code>.hide {
  display:none;
}
</code>```

Add or remove this class. This way is very simple

Body:
I made a drop-down menu consisting of a HTML input/button and some more buttons as drop-down menu items. The menu is shown as soon as hovered over the main button

    <button id="dropdown-wifi" class="extended-button" onclick="showDropDown()">Available WiFi Hot Spots</button>

This is the hover event in CSS:

.dropdown:hover .dropdown-content {
    display: block;
}

The JavaScript code that hides and later 'should' show again:

function showDropDown() {
    document.getElementById("ssid-dropdown").style.display = 'block';
}

function hideDropDown() {
    document.getElementById("ssid-dropdown").style.display = 'none';
}

Now, the drop-down menu is properly shown as soon as I hover over the main button. But when selecting an item, I call hideDropDown() to hide the menu even if not hovered outside of the items.

I notified that as soon as the hideDropDown() function is called, the following is added in the CSS window of Chrome's debug windows:

element.style {
    display: none;
}

I guess, that is a kind of CSS generated because my JavaScript function call of hideDropDown(). However, as soon as this element.stlye is occuring, the hovering/show of the drop-down menu doesn't work anymore.

Any ideas how to solve this issue?

Body:
You can create class  with name hide and add next css:

.hide {
  display:none;
}

Add or remove this class. This way is very simple


问:
Trying to merge into a dataframe but it keeps creating new columns
I am trying to open files and derive 2 columns(1 row for each) from multiple spreadsheets and then merging them to a base spreadsheet.So, the base dataframe (derived from a spreadsheet, from which I only needed 3 columns)  is like this :

```<code>Model |  Roadmap | Family
a       08/12/17  ROW
b       08/14/17  MACRO
c       08/15/17  CONN
d       08/27/17  MACRO
</code>```

The dataframes from the multiple spreadsheets(the model names are the spreadsheet names and they have multiple dates for each gate which i am deriving in multiple dataframes) and have this format :

```<code>    df1 (part1 -  the dataframe derived from the spreadsheet with model a for gate 0 ):
    Model   |  Gate 0
    a         02/01/18

df1 (Dataframe derived from the spreadsheet with model a for gate1):
        Model   |  Gate 1
        a         03/01/18

   df2 (part1):
    Model  |  Gate 0
    b       04/23/18

df2 (part1):
        Model  |  Gate 1
        b       05/23/18
</code>```

The output it produces is :

```<code>Model |  Roadmap | Family | Gate 0_x  | Gate 1_x   | gate 0_y | Gate 1_y
a       08/12/17  ROW      02/01/18   03/01/18
b       08/14/17  MACRO                              04/23/18  05/23/18
c       08/15/17  CONN
d       08/27/17  MACRO
</code>```

the output i want :

```<code>  Model |  Roadmap | Family | Gate 0   | Gate 1
   a       08/12/17  ROW     02/01/18   03/01/18
   b       08/14/17  MACRO    04/23/18  05/23/18
   ..
</code>```

The following is the code i am using:

```<code>import glob
import pandas as pd
import re
import ntpath

extension = 'xlsx'
d='Final.xlsx'
c = 'Roadmap.xlsx'
dflist = []
z=[]
result = [i for i in glob.glob('*.{}'.format(extension))]

for b in result:
    if b==c:
        base_file = pd.read_excel(b, sheet_name='Antennas', header=7)
        ind1 = base_file.set_index('Model')
        ind1 = base_file[['Model', 'Roadmap', 'Family']]
        #print(ind1)
        ind1.to_excel('Final.xlsx')
        file3 = pd.read_excel('Final.xlsx')
        file3= file3.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)

for a in result:

        if a == c:
            base_file = pd.read_excel(a, sheet_name='Antennas', header=7)
            ind1 = base_file.set_index('Model')
            ind1 = base_file[['Model', 'Roadmap', 'Family']]
            ind1.to_excel('Final.xlsx')
        elif a != d:
            gates = ['Gate 0 Complete','Gate 1 Complete']
            file1 = pd.read_excel('Final.xlsx')
            file1= file1.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)
            #print(file1)
            file = pd.read_excel(a, sheet_name='Timeline')
            #print(file)
            models = pd.DataFrame([['','']], columns=['Model', gates])
            for g in gates:
                z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
                v=ntpath.basename(a)
                v = v[5:-5]
                models = pd.DataFrame([[v,z]], columns =['Model',g])
                file1 = pd.merge(file1, models, how='left', on='Model')
            file3 = pd.merge(file3, file1, how='left' ,['Model','Roadmap','Family'])
            file3.to_excel('new.xlsx')
</code>```

file3 is the file i have opened as the dataframe for the base file before the for loop. Let me know if anything is not clear.

答:
Got how to do it. Let me know if you find any issues. </p>

```<code>import glob
import pandas as pd
import re
import ntpath

extension = 'xlsx'
d='Final.xlsx'
c = 'Roadmap.xlsx'
dflist = []
z=[]
result = [i for i in glob.glob('*.{}'.format(extension))]

for a in result:

    if a == c:
        base_file = pd.read_excel(a, sheet_name='Antennas', header=7)
        ind1 = base_file.set_index('Model')
        ind1 = base_file[['Model', 'Roadmap', 'Family']]
        #print(ind1)
        ind1.to_excel('Final.xlsx')
    elif a != d:
        v=ntpath.basename(a)
        v = v[5:-5]
        gates = ['Gate 0 Complete','Gate 1 Complete', 'Gate 2 Complete']
        file1 = pd.read_excel('Final.xlsx')
        file1= file1.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)
        #print(file1)
        file = pd.read_excel(a, sheet_name='Timeline')
        #print(file)
        models = pd.DataFrame([[v]], columns=['Model'])
        #print(models)
        for g in gates:
            z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
            #print(z)
            #v = re.findall(r'Scrum(\w+)', a)
            #print(v)
            #df1=pd.DataFrame([[v,z]], columns = ['Model',g])
            mod = pd.DataFrame([[v,z]], columns =['Model',g])
            models=pd.merge(models, mod, how='left', on='Model')
            #print(models)
        dflist.append(models)
        #print(dflist)
file1 = pd.merge(file1,pd.concat(dflist), how='left',on='Model')
file1.to_excel('new.xlsx')
</code>```

Body:
I am trying to open files and derive 2 columns(1 row for each) from multiple spreadsheets and then merging them to a base spreadsheet.So, the base dataframe (derived from a spreadsheet, from which I only needed 3 columns)  is like this :

Model |  Roadmap | Family
a       08/12/17  ROW
b       08/14/17  MACRO
c       08/15/17  CONN
d       08/27/17  MACRO

The dataframes from the multiple spreadsheets(the model names are the spreadsheet names and they have multiple dates for each gate which i am deriving in multiple dataframes) and have this format :

    df1 (part1 -  the dataframe derived from the spreadsheet with model a for gate 0 ):
    Model   |  Gate 0
    a         02/01/18

df1 (Dataframe derived from the spreadsheet with model a for gate1):
        Model   |  Gate 1
        a         03/01/18

   df2 (part1):
    Model  |  Gate 0
    b       04/23/18

df2 (part1):
        Model  |  Gate 1
        b       05/23/18

The output it produces is :

Model |  Roadmap | Family | Gate 0_x  | Gate 1_x   | gate 0_y | Gate 1_y
a       08/12/17  ROW      02/01/18   03/01/18
b       08/14/17  MACRO                              04/23/18  05/23/18
c       08/15/17  CONN
d       08/27/17  MACRO

the output i want :

  Model |  Roadmap | Family | Gate 0   | Gate 1
   a       08/12/17  ROW     02/01/18   03/01/18
   b       08/14/17  MACRO    04/23/18  05/23/18
   ..

The following is the code i am using:

import glob
import pandas as pd
import re
import ntpath

extension = 'xlsx'
d='Final.xlsx'
c = 'Roadmap.xlsx'
dflist = []
z=[]
result = [i for i in glob.glob('*.{}'.format(extension))]

for b in result:
    if b==c:
        base_file = pd.read_excel(b, sheet_name='Antennas', header=7)
        ind1 = base_file.set_index('Model')
        ind1 = base_file[['Model', 'Roadmap', 'Family']]
        #print(ind1)
        ind1.to_excel('Final.xlsx')
        file3 = pd.read_excel('Final.xlsx')
        file3= file3.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)

for a in result:

        if a == c:
            base_file = pd.read_excel(a, sheet_name='Antennas', header=7)
            ind1 = base_file.set_index('Model')
            ind1 = base_file[['Model', 'Roadmap', 'Family']]
            ind1.to_excel('Final.xlsx')
        elif a != d:
            gates = ['Gate 0 Complete','Gate 1 Complete']
            file1 = pd.read_excel('Final.xlsx')
            file1= file1.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)
            #print(file1)
            file = pd.read_excel(a, sheet_name='Timeline')
            #print(file)
            models = pd.DataFrame([['','']], columns=['Model', gates])
            for g in gates:
                z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
                v=ntpath.basename(a)
                v = v[5:-5]
                models = pd.DataFrame([[v,z]], columns =['Model',g])
                file1 = pd.merge(file1, models, how='left', on='Model')
            file3 = pd.merge(file3, file1, how='left' ,['Model','Roadmap','Family'])
            file3.to_excel('new.xlsx')

file3 is the file i have opened as the dataframe for the base file before the for loop. Let me know if anything is not clear.

Body:
Got how to do it. Let me know if you find any issues.

import glob
import pandas as pd
import re
import ntpath

extension = 'xlsx'
d='Final.xlsx'
c = 'Roadmap.xlsx'
dflist = []
z=[]
result = [i for i in glob.glob('*.{}'.format(extension))]

for a in result:

    if a == c:
        base_file = pd.read_excel(a, sheet_name='Antennas', header=7)
        ind1 = base_file.set_index('Model')
        ind1 = base_file[['Model', 'Roadmap', 'Family']]
        #print(ind1)
        ind1.to_excel('Final.xlsx')
    elif a != d:
        v=ntpath.basename(a)
        v = v[5:-5]
        gates = ['Gate 0 Complete','Gate 1 Complete', 'Gate 2 Complete']
        file1 = pd.read_excel('Final.xlsx')
        file1= file1.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)
        #print(file1)
        file = pd.read_excel(a, sheet_name='Timeline')
        #print(file)
        models = pd.DataFrame([[v]], columns=['Model'])
        #print(models)
        for g in gates:
            z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
            #print(z)
            #v = re.findall(r'Scrum(\w+)', a)
            #print(v)
            #df1=pd.DataFrame([[v,z]], columns = ['Model',g])
            mod = pd.DataFrame([[v,z]], columns =['Model',g])
            models=pd.merge(models, mod, how='left', on='Model')
            #print(models)
        dflist.append(models)
        #print(dflist)
file1 = pd.merge(file1,pd.concat(dflist), how='left',on='Model')
file1.to_excel('new.xlsx')


问:
Rails: Model associations
I have two models, one called User and another called Recruiter.  What I would like to do is to be able to create a scope that searches users and returns the results so recruiters can see them.  But I'm not sure how to go about setting up the association.  I made a through association between users and recruiters and created a new join table called recruiter_users but I'm not sure if this is the correct approach.  </p>

<p>1) What the best way to make the association between the 2 models
2) how exactly would I display the user results in the recruiters view? </p>

```<code>  class RecruiterUser < ApplicationRecord

  # this is a join model between recruiters and users
  belongs_to :recruiter
  belongs_to :user

class User < ApplicationRecord

  # creates association with recruiters model through the join table recruiter_users
  has_many :recruiter_users
  has_many :recruiters, through: :recruiter_users

class Recruiter < ApplicationRecord

  # creates association with users model through the join table recruiter_users
  has_many :recruiter_users
  has_many :users, through: :recruiter_users
</code>```

答:
It sounds like you want your average run of the mill many to many association:

```<code>class User
  has_many :recruitments
  has_many :recruiters,
    through: :recruitments
end

class Recruiter
  has_many :recruitments
  has_many :recruited_users,
    through: :recruitments,
    source: :user
end

class Recruitment
  belongs_to :user
  belongs_to :recruiter
end
</code>```

You don't have to name your join models a + b. If there is a more descriptive name of what the relation is use it.

this would let you iterate through the users recruited by a recruiter by:

```<code>@recruiter = Recruiter.includes(:recruited_users).find(params[:id])

<% @recruiter.recruited_users.each do |user| %>
  # ...
<% end %>
</code>```

Title: Rails: Model associations

Body:
I have two models, one called User and another called Recruiter.  What I would like to do is to be able to create a scope that searches users and returns the results so recruiters can see them.  But I'm not sure how to go about setting up the association.  I made a through association between users and recruiters and created a new join table called recruiter_users but I'm not sure if this is the correct approach.

1) What the best way to make the association between the 2 models
2) how exactly would I display the user results in the recruiters view?

  class RecruiterUser < ApplicationRecord

  # this is a join model between recruiters and users
  belongs_to :recruiter
  belongs_to :user

class User < ApplicationRecord

  # creates association with recruiters model through the join table recruiter_users
  has_many :recruiter_users
  has_many :recruiters, through: :recruiter_users

class Recruiter < ApplicationRecord

  # creates association with users model through the join table recruiter_users
  has_many :recruiter_users
  has_many :users, through: :recruiter_users

Body:
It sounds like you want your average run of the mill many to many association:

class User
  has_many :recruitments
  has_many :recruiters,
    through: :recruitments
end

class Recruiter
  has_many :recruitments
  has_many :recruited_users,
    through: :recruitments,
    source: :user
end

class Recruitment
  belongs_to :user
  belongs_to :recruiter
end

You don't have to name your join models a + b. If there is a more descriptive name of what the relation is use it.

this would let you iterate through the users recruited by a recruiter by:

@recruiter = Recruiter.includes(:recruited_users).find(params[:id])

<% @recruiter.recruited_users.each do |user| %>
  # ...
<% end %>


答:
you must use <code>@media</code> for that like this : </p>

```<code>@media screen and (min-width: 769px) {
    /* STYLES HERE */
}

@media screen and (min-device-width: 481px) and (max-device-width: 768px) {
    /* STYLES HERE */
}

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE */
}
</code>```

Title: Use 100% div width, if 50% width is too small

Body: How could one go about creating a div, that would have a default size of XX%, however, if the screen gets too small it would switch into 100% size? I have tried using min-width property but the problem with this is that it will not be responsive after the min-width is reached and will overflow if the screen is even smaller.

Body:
you must use @media for that like this :

@media screen and (min-width: 769px) {
    /* STYLES HERE */
}

@media screen and (min-device-width: 481px) and (max-device-width: 768px) {
    /* STYLES HERE */
}

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE */
}


问:
How to pass symbol as parameter of post request in ruby?
This code work well

```<code>Geokit::default_units = :miles #:kms, :nms, :meters
</code>```

But this code make errors

```<code>puts params[:unit]     # miles
Geokit::default_units = params[:unit] #:miles, :kms, :nms, :meters
</code>```

What is wrong with this?

答:
That's because all that goes through the params is an string, if you want a symbol, then consider using .to_sym:</p>

```<code>params = { unit: 'miles' }
p params[:unit].class # String
p params[:unit].to_sym.class # Symbol
</code>```

Body:
This code work well

Geokit::default_units = :miles #:kms, :nms, :meters

But this code make errors

puts params[:unit]     # miles
Geokit::default_units = params[:unit] #:miles, :kms, :nms, :meters

What is wrong with this?

Body:
That's because all that goes through the params is an string, if you want a symbol, then consider using .to_sym:

params = { unit: 'miles' }
p params[:unit].class # String
p params[:unit].to_sym.class # Symbol


问:
Find Command with multiple file extensions
I'm looking through many sub directories and finding all the files ending in .JPG .jpg and .png and copying them to a separate directory, however just now its only finding .JPG

Could someone explain what i'm doing wrong?

```<code>find /root/TEST/Images -name  '*.png' -o  -name '*.jpg' -o -name '*.JPG' -exec cp -t /root/TEST/CopiedImages {} +
</code>```

答:
You have to group the -o conditions because -a, the implied AND between the last -name '*.JPG' and -exec has higher precedence:

```<code>find /root/TEST/Images \( -name  '*.png' -o  -name '*.jpg' -o -name '*.JPG' \) -exec cp -t /root/TEST/CopiedImages {} +
</code>```

Grouping is done with parentheses, but they have to be escaped (or quoted) due to their special meaning is shell.

Unrelated to this, you can shorten the overall expression by combining filters for jpg and JPG with the case-insensitive -iname (as noted in comments):

```<code>find /root/TEST/Images \( -name  '*.png' -o  -iname '*.jpg' \) -exec cp -t /root/TEST/CopiedImages {} +
</code>```

Body:
I'm looking through many sub directories and finding all the files ending in .JPG .jpg and .png and copying them to a separate directory, however just now its only finding .JPG

Could someone explain what i'm doing wrong?

find /root/TEST/Images -name  '*.png' -o  -name '*.jpg' -o -name '*.JPG' -exec cp -t /root/TEST/CopiedImages {} +

Body:
You have to group the -o conditions because -a, the implied AND between the last -name '*.JPG' and -exec has higher precedence:

find /root/TEST/Images \( -name  '*.png' -o  -name '*.jpg' -o -name '*.JPG' \) -exec cp -t /root/TEST/CopiedImages {} +

Grouping is done with parentheses, but they have to be escaped (or quoted) due to their special meaning is shell.

Unrelated to this, you can shorten the overall expression by combining filters for jpg and JPG with the case-insensitive -iname (as noted in comments):

find /root/TEST/Images \( -name  '*.png' -o  -iname '*.jpg' \) -exec cp -t /root/TEST/CopiedImages {} +


问:
Plotting timestamps (hour/minute/seconds) with Matplotlib
I want to plot some timestamps (Year-month-day Hour-Minute-Second format). I am using the following code, however it doesn't show any hour-minute-second information, it shows them as 00-00-00. I double checked my date array, and as you can see from the snippet below, they are not zero.

Do you have any idea about why I am getting 00-00-00's?

```<code>import matplotlib.pyplot as plt
import matplotlib.dates as md
import dateutil

dates = [dateutil.parser.parse(s) for s in datestrings]
# datestrings = ['2012-02-21 11:28:17.980000', '2012-02-21 12:15:32.453000', '2012-02-21 23:26:23.734000', '2012-02-26 17:42:15.804000']
plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation= 80 )
ax=plt.gca()
xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)
plt.plot(dates[0:10],plt_data[0:10], "o-")
plt.show()
</code>```

答:
I can tell you why it shows the 00:00:00. It's because that's the start time of that particular day. For example, one tick is at 2012-02-22 00:00:00 (12 midnight of 2012-02-22) and another is at 2012-02-23 00:00:00 (12 midnight of 2012-02-23).

Ticks for the timestamps in between these two times are not shown.

I myself am trying to figure out how to show ticks for in between these times.

Body:
I want to plot some timestamps (Year-month-day Hour-Minute-Second format). I am using the following code, however it doesn't show any hour-minute-second information, it shows them as 00-00-00. I double checked my date array, and as you can see from the snippet below, they are not zero.

Do you have any idea about why I am getting 00-00-00's?

import matplotlib.pyplot as plt
import matplotlib.dates as md
import dateutil

dates = [dateutil.parser.parse(s) for s in datestrings]
# datestrings = ['2012-02-21 11:28:17.980000', '2012-02-21 12:15:32.453000', '2012-02-21 23:26:23.734000', '2012-02-26 17:42:15.804000']
plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation= 80 )
ax=plt.gca()
xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)
plt.plot(dates[0:10],plt_data[0:10], "o-")
plt.show()


问:
Running NLP on Heroku
If you use Heroku, you know Heroku imposes slugsize limit of 300MB. Our company is trying to run NLP app, which, using Stanford NLP library, is more than 300MB.

Is there anyone who has successfully hosted Stanford NLP process on Heroku? How did you achieve it? If you had to lose the weight by excluding parts of NLP library, how did you do it?

答:
I had that problem before. I talked with Heroku support and they increased my slack size to 500 Mb. So, I would suggest to talk to them. Also, heroku has recently added support for docker deployment. You can try using CodeShip or other CI with docker deployment to try out. I believe that bypasses their custom CI/CD completely.
Hope I answered your question.</p>

Title: Running NLP on Heroku


问:
How would I parse an XML file into a list
List:

```<code>List<string> list = new List<string>();
</code>```

XML File:

```<code><memberlist>
 <member>
  <name>Name</name>
  <status>Status</status>
 </member>
</memberlist>
</code>```

How would I go about parsing this file, lets say (file.xml) into the list?

I've tried many ways but none of them seem to be working.

I want to check to see if the status is 'gold', and if it is, I would like to put the name of that member into the list.

答:
You can use LINQ

```<code>XElement xml = XElement.Load("locationToYourXmlFile");

var members = xml.Elements("member");
var list  = members.Where(member => member.Element("status")?.Value == "Gold")
                   .Select(member => member.Element("name")?.Value)
                   .ToList();
</code>```

Assuming your XML has a bunch of member elements under the root memberlist element, each with a name and status element inside that.

```<code><?xml version="1.0" encoding="utf-8"?>
<memberlist>
    <member>
        <name>John</name>
        <status>Gold</status>
    </member>
    <member>
        <name>Sam</name>
        <status>Silver</status>
    </member>
    <member>
        <name>Sara</name>
        <status>Gold</status>
    </member>
</memberlist>
</code>```

Body:
List:

List<string> list = new List<string>();

XML File:

<memberlist>
 <member>
  <name>Name</name>
  <status>Status</status>
 </member>
</memberlist>

How would I go about parsing this file, lets say (file.xml) into the list?

I've tried many ways but none of them seem to be working.

I want to check to see if the status is 'gold', and if it is, I would like to put the name of that member into the list.

Body:
You can use LINQ

XElement xml = XElement.Load("locationToYourXmlFile");

var members = xml.Elements("member");
var list  = members.Where(member => member.Element("status")?.Value == "Gold")
                   .Select(member => member.Element("name")?.Value)
                   .ToList();

Assuming your XML has a bunch of member elements under the root memberlist element, each with a name and status element inside that.

<?xml version="1.0" encoding="utf-8"?>
<memberlist>
    <member>
        <name>John</name>
        <status>Gold</status>
    </member>
    <member>
        <name>Sam</name>
        <status>Silver</status>
    </member>
    <member>
        <name>Sara</name>
        <status>Gold</status>
    </member>
</memberlist>


问:
Disable selection of parent rows in a QTreeWidget
I populate nested lists in a QTreeWidget, and I need to disable the selection of parent rows.

The code is:

```<code>def fillTree(self):
    '''
    Fill UI with list of parts
    '''
    roots = ['APLE', 'ORANGE', 'MANGO']
    childs = ['body', 'seed', 'stern']
    parent = self.treeWidget.invisibleRootItem()
    for root in roots:
        widgetTrim = QTreeWidgetItem()
        widgetTrim.setText(0, root)
        parent.addChild(widgetTrim)
        for child in childs:
            widgetPart = QTreeWidgetItem()
            widgetPart.setText(0, child)
            widgetTrim.addChild(widgetPart)
</code>```

I need to avoid selection of the "fruit" items.

答:
You must remove Qt.ItemIsSelectable from the item-flags:

```<code>widgetTrim = QTreeWidgetItem()
widgetTrim.setFlags(widgetTrim.flags() & ~Qt.ItemIsSelectable)
</code>```

The flags are an OR'd together combination ItemFlag values. So a bitwise AND NOT operation is used to remove the ItemIsSelectable from the existing combination of flags.

Body:
I populate nested lists in a QTreeWidget, and I need to disable the selection of parent rows.

The code is:

def fillTree(self):
    '''
    Fill UI with list of parts
    '''
    roots = ['APLE', 'ORANGE', 'MANGO']
    childs = ['body', 'seed', 'stern']
    parent = self.treeWidget.invisibleRootItem()
    for root in roots:
        widgetTrim = QTreeWidgetItem()
        widgetTrim.setText(0, root)
        parent.addChild(widgetTrim)
        for child in childs:
            widgetPart = QTreeWidgetItem()
            widgetPart.setText(0, child)
            widgetTrim.addChild(widgetPart)

I need to avoid selection of the "fruit" items.

Body:
You must remove Qt.ItemIsSelectable from the item-flags:

widgetTrim = QTreeWidgetItem()
widgetTrim.setFlags(widgetTrim.flags() & ~Qt.ItemIsSelectable)

The flags are an OR'd together combination ItemFlag values. So a bitwise AND NOT operation is used to remove the ItemIsSelectable from the existing combination of flags.