问:
How to implement a component to show a number of div elements initially, and then show a number of more elements?
I have build a review-system in HTML, PHP and AJAX so users can post their opinion on a website. This review-system consists of two scripts:

PHP-script:

```<code><?php
... code
?>

<div class="overall_rating">
    <span class="num"><?=number_format($reviews_info['overall_rating'], 1)?></span>
    <span class="stars"><?=str_repeat('★', round($reviews_info['overall_rating']))?></span>
    <span class="total"><?=$reviews_info['total_reviews']?> reviews</span>
</div>
<a href="#" class="write_review_btn">Schrijf review</a>
<div class="write_review">
    <form>
        <input name="name" type="text" placeholder="Uw voornaam" required>
        <input name="rating" type="number" min="1" max="5" placeholder="Uw beoordeling (1-5)" required>
        <textarea name="content" placeholder="Schrijf hier uw review" required></textarea>
        <button type="submit">Plaats review</button>
    </form>
</div>
<?php foreach ($reviews as $review): ?>
<div class="review">
    <h3 class="name"><?=htmlspecialchars($review['name'], ENT_QUOTES)?></h3>
    <div>
        <span class="rating"><?=str_repeat('★', $review['rating'])?></span>
        <span class="date"><?=time_elapsed_string($review['submit_date'])?></span>
    </div>
    <p class="content"><?=htmlspecialchars($review['content'], ENT_QUOTES)?></p>
</div>
<?php endforeach ?>
</code>```

HTML-/AJAX-script:

```<code><div class="container wow fadeInDown content home" data-wow-duration="500ms">
   <div class="reviews"></div>
   <script>
      const reviews_page_id = 1;
      fetch("reviews.php?page_id=" + reviews_page_id).then(response => response.text()).then(data => {
        document.querySelector(".reviews").innerHTML = data;
        document.querySelector(".reviews .write_review_btn").onclick = event => {
            event.preventDefault();
            document.querySelector(".reviews .write_review").style.display = 'block';
            document.querySelector(".reviews .write_review input[name='name']").focus();
        };
        document.querySelector(".reviews .write_review form").onsubmit = event => {
            event.preventDefault();
            fetch("reviews.php?page_id=" + reviews_page_id, {
                method: 'POST',
                body: new FormData(document.querySelector(".reviews .write_review form"))
            }).then(response => response.text()).then(data => {
                document.querySelector(".reviews .write_review").innerHTML = data;
            });
        };
      });
   </script>
</div>
</code>```

I don't know how to implement a component to show a number of div elements initially, and then show a number of more elements. For example: when opening the website only show 10 reviews initially (but keep the overall rating), and after clicking on a component show 10 more.

So it's not about filtering data, but about showing or not showing div elements. I tried to reproduce this with a simple example from Stackoverflow (see snippet below), but I still can't figure out how to implement this into my own code. Do you have any idea how to achieve this?

Example:

<!DOCTYPE html>

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 20

      show more

```

答:
The typical way of preforming a "Load More" type functionality is to display the 10 items immediately on load.

Then when the user asks for additional items, you would make an AJAX call to get the additional items, and then use Javascript to append them to the list.

In order to take your snippet and apply it to your code, it should be fairly straightforward. You can continue to print out all the reviews and hide the ones .review:gt(x) the limit. This won't follow the above pattern, but should continue to give you the results you're looking for.

Body:
I have build a review-system in HTML, PHP and AJAX so users can post their opinion on a website. This review-system consists of two scripts:

PHP-script:

<?php
... code
?>

    <?=number_format($reviews_info['overall_rating'], 1)?>
    <?=str_repeat('★', round($reviews_info['overall_rating']))?>
    <?=$reviews_info['total_reviews']?> reviews

Schrijf review

    <form>
        <input name="name" type="text" placeholder="Uw voornaam" required>
        <input name="rating" type="number" min="1" max="5" placeholder="Uw beoordeling (1-5)" required>
        <textarea name="content" placeholder="Schrijf hier uw review" required></textarea>
        <button type="submit">Plaats review</button>
    </form>

<?php foreach ($reviews as $review): ?>

<?=htmlspecialchars($review['name'], ENT_QUOTES)?>

        <?=str_repeat('★', $review['rating'])?>
        <?=time_elapsed_string($review['submit_date'])?>

<?=htmlspecialchars($review['content'], ENT_QUOTES)?>

<?php endforeach ?>

HTML-/AJAX-script:

I don't know how to implement a component to show a number of div elements initially, and then show a number of more elements. For example: when opening the website only show 10 reviews initially (but keep the overall rating), and after clicking on a component show 10 more.

So it's not about filtering data, but about showing or not showing div elements. I tried to reproduce this with a simple example from Stackoverflow (see snippet below), but I still can't figure out how to implement this into my own code. Do you have any idea how to achieve this?

Example:

<!DOCTYPE html>

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 1

data 2

data 20

      show more


来源: stackexchange

问:
can't understand scipy.sparse.csr_matrix example
I can't wrap my head around csr_matrix examples in scipy documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html

Can someone explain how this example work?

```<code>>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])
</code>```

I believe this is following this format.

csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])

where data, row_ind and col_ind satisfy the relationship a[row_ind[k], col_ind[k]] = data[k].

What is a here?

答:
Represent the "data" in a 4 X 4 Matrix:

```<code>data = np.array([10,0,5,99,25,9,3,90,12,87,20,38,1,8])
indices = np.array([0,1,2,3,0,2,3,0,1,2,3,1,2,3])
indptr  = np.array([0,4,7,11,14])
</code>```

'indptr'- Index pointers is linked list of pointers to 'indices' (Column
index Pointers)...

indptr[i:i+1] represents i to i+1 index of pointer

14 reprents len of Data len(data)...
    indptr  = np.array([0,4,7,11,len(data)]) other way of represenint 'indptr'

0,4 --> 0:4 represents pointers to indices 0,1,2,3

4,7 --> 4:7 represents the pointers of indices 0,2,3

7,11 --> 7:11 represents the pointers of 0,1,2,3

11,14 --> 11:14 represents pointers 1,2,3

```<code>#  Representing the data in a 4,4 matrix

a = csr_matrix((data,indices,indptr),shape=(4,4),dtype=np.int)
a.todense()

matrix([[10,  0,  5, 99],
        [25,  0,  9,  3],
        [90, 12, 87, 20],
        [ 0, 38,  1,  8]])
</code>```

Another Stackoverflow explanation

ContentLicense: CC BY-SA 4.0

Body:
I can't wrap my head around csr_matrix examples in scipy documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html

Can someone explain how this example work?

>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])

I believe this is following this format.

csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])

where data, row_ind and col_ind satisfy the relationship a[row_ind[k], col_ind[k]] = data[k].

What is a here?

Body:
Represent the "data" in a 4 X 4 Matrix:

data = np.array([10,0,5,99,25,9,3,90,12,87,20,38,1,8])
indices = np.array([0,1,2,3,0,2,3,0,1,2,3,1,2,3])
indptr  = np.array([0,4,7,11,14])

'indptr'- Index pointers is linked list of pointers to 'indices' (Column
index Pointers)...

indptr[i:i+1] represents i to i+1 index of pointer

14 reprents len of Data len(data)...
    indptr  = np.array([0,4,7,11,len(data)]) other way of represenint 'indptr'

0,4 --> 0:4 represents pointers to indices 0,1,2,3

4,7 --> 4:7 represents the pointers of indices 0,2,3

7,11 --> 7:11 represents the pointers of 0,1,2,3

11,14 --> 11:14 represents pointers 1,2,3

#  Representing the data in a 4,4 matrix

a = csr_matrix((data,indices,indptr),shape=(4,4),dtype=np.int)
a.todense()

matrix([[10,  0,  5, 99],
        [25,  0,  9,  3],
        [90, 12, 87, 20],
        [ 0, 38,  1,  8]])

Another Stackoverflow explanation


问:
What are the default mappings for the up and down arrows keys in zsh
I am trying to bind the default functionality of the up and down arrow keys in zsh to something else. I.e. Now when I press up, it basically shows me the previous command and when I press up again it shows me the command before that. I would like to bind this functionality to another key (say ^k and ^j). So the bind would look like:

```<code>bindkey '^k' up-line-or-history
bindkey '^j' down-line-or-history
</code>```

However, I was searching around and found many possibilities: up-line, up-line-or-history etc. Which mappings are the default used by zsh for the up and down arrow keys ? I'm guessing its up-line-or-history and down-line-or-history but I can't be too sure.

Version:
zsh 5.7.1 (x86_64-apple-darwin19.0)

答:
up-line is unbound by default; from man zshzle

up-line (unbound) (unbound) (unbound)

which you can confirm by grepping for up-line in the output of bindkeys:

```<code>% bindkey | grep up-line
"^P" up-line-or-history
"^[OA" up-line-or-history
"^[[A" up-line-or-history
</code>```

The documentation mentions that up-line-history is bound to ^P and up-arrow:

up-line-or-history (^P ESC-[A) (k) (ESC-[A)

Both ^[OA and ^[[A refer to the up-arrow key; I believe the duplication depends on your terminal emulator's settings, with the sequence generated by up-arrow depending on the "mode" of the terminal.

Body:
I am trying to bind the default functionality of the up and down arrow keys in zsh to something else. I.e. Now when I press up, it basically shows me the previous command and when I press up again it shows me the command before that. I would like to bind this functionality to another key (say ^k and ^j). So the bind would look like:

bindkey '^k' up-line-or-history
bindkey '^j' down-line-or-history

However, I was searching around and found many possibilities: up-line, up-line-or-history etc. Which mappings are the default used by zsh for the up and down arrow keys ? I'm guessing its up-line-or-history and down-line-or-history but I can't be too sure.

Version:
zsh 5.7.1 (x86_64-apple-darwin19.0)

Body:
up-line is unbound by default; from man zshzle

up-line (unbound) (unbound) (unbound)

which you can confirm by grepping for up-line in the output of bindkeys:

% bindkey | grep up-line
"^P" up-line-or-history
"^[OA" up-line-or-history
"^[[A" up-line-or-history

The documentation mentions that up-line-history is bound to ^P and up-arrow:

up-line-or-history (^P ESC-[A) (k) (ESC-[A)

Both ^[OA and ^[[A refer to the up-arrow key; I believe the duplication depends on your terminal emulator's settings, with the sequence generated by up-arrow depending on the "mode" of the terminal.


问:
Saving arrays on Flutter
I have an array that contains widgets List<ListCard> listsList= []; And inside each widget I have an array that has objects of a class called Product List<Product> products = [];. Through the app you can add products to the list but I want to save this 2 arrays (and the inner objects). How can I do it? I thought I can do a database but maybe there is something more straightforward than designing all the schema.

答:
There are two ways to this:

1) Use this package, it's pretty simple to use and doesn't require you to write anything super complex. One downside - data is saved on the device, so if the app is deleted - all information is lost.

2) Attach Firebase Storage, using official packages. Installation of it is not complex at all, though you will need to convert your Product to Map

Both methods are valid and pretty fast to implement without groundbreaking changes.

If any questions occur - feel free to ask :3

Title: Saving arrays on Flutter


问:
Gradle Kotlin Script, trying to assign classpatch via builtin variable
Why this:

```<code>val runVersionSplicer by tasks.registering(type = JavaExec::class) {
    classpath = sourceSets.main.runtimeClasspath // error
    main = "com.concurnas.build.VersionSplicer"
}
</code>```

returns:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
  public val NamedDomainObjectContainer.runtimeClasspath: NamedDomainObjectProvider defined in org.gradle.kotlin.dsl

While this works fine instead?

```<code>val runVersionSplicer by tasks.registering(type = JavaExec::class) {
    classpath = sourceSets["main"].runtimeClasspath
    main = "com.concurnas.build.VersionSplicer"
}
</code>```

I know that sourceSets.main is so defined:

```<code>val org.gradle.api.tasks.SourceSetContainer.`main`: NamedDomainObjectProvider<org.gradle.api.tasks.SourceSet>
    get() = named<org.gradle.api.tasks.SourceSet>("main")
</code>```

However isn't supposed to replace the sourceSets["main"] construct?

答:
Because one of them is a provider and the other is the object.

sourceSets.main uses NamedDomainObjectCollection.named under the hood as you found out. If you look at the javadoc for named, you see that it returns the following:

A Provider that will return the object when queried. The object may be created and configured at this point, if not already

sourceSets["main"] returns the source set directly, because it uses NamedDomainObjectCollection.getByName instead, whi:

The object with the given name. Never returns null.

So these two are equivalent:

```<code>sourceSets.main.get()
sourceSets["main"]
</code>```

In Groovy the following are equivalent:

```<code>sourceSets.main
sourceSets["main"]
sourceSets.getAt("main")
</code>```

Which are all different syntax of the getAt method implemented by the NamedDomainObjectCollection class. This is why you don't see a lot of get() in Groovy scripts but you see a lot more in Kotlin DSL scripts.

Body:
Why this:

val runVersionSplicer by tasks.registering(type = JavaExec::class) {
    classpath = sourceSets.main.runtimeClasspath // error
    main = "com.concurnas.build.VersionSplicer"
}

returns:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
  public val NamedDomainObjectContainer.runtimeClasspath: NamedDomainObjectProvider defined in org.gradle.kotlin.dsl

While this works fine instead?

val runVersionSplicer by tasks.registering(type = JavaExec::class) {
    classpath = sourceSets["main"].runtimeClasspath
    main = "com.concurnas.build.VersionSplicer"
}

I know that sourceSets.main is so defined:

val org.gradle.api.tasks.SourceSetContainer.`main`: NamedDomainObjectProvider<org.gradle.api.tasks.SourceSet>
    get() = named<org.gradle.api.tasks.SourceSet>("main")

However isn't supposed to replace the sourceSets["main"] construct?

Body:
Because one of them is a provider and the other is the object.

sourceSets.main uses NamedDomainObjectCollection.named under the hood as you found out. If you look at the javadoc for named, you see that it returns the following:

A Provider that will return the object when queried. The object may be created and configured at this point, if not already

sourceSets["main"] returns the source set directly, because it uses NamedDomainObjectCollection.getByName instead, whi:

The object with the given name. Never returns null.

So these two are equivalent:

sourceSets.main.get()
sourceSets["main"]

In Groovy the following are equivalent:

sourceSets.main
sourceSets["main"]
sourceSets.getAt("main")

Which are all different syntax of the getAt method implemented by the NamedDomainObjectCollection class. This is why you don't see a lot of get() in Groovy scripts but you see a lot more in Kotlin DSL scripts.


问:
how to turn text into a dictionary list
I have a text with the content shown below.
This is a string.

```<code>{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}
</code>```

If possible, I would like someone to help me build a list of dictionaries with this information.
It looks like this:

```<code>list = [{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}]
</code>```

Best wishes!

答:
You can use regex to split the string, and json.loads to convert each element of the resulting list into a dict:</p>

```<code>import re
import json

s = "{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}"

#json.loads expects double quotes, so replace single with double
s = s.replace("'", '"')

# regex pattern to match ", " between } and { characters
pattern = "(?<={)*, (?={)"

# split string based on regex pattern, parse each element to a dict with json.loads
d = [json.loads(d) for d in re.split(pattern, s)]
print(d)
</code>```

Title: how to turn text into a dictionary list

Body:
I have a text with the content shown below.
This is a string.

{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}

If possible, I would like someone to help me build a list of dictionaries with this information.
It looks like this:

list = [{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}]

Best wishes!

Body:
You can use regex to split the string, and json.loads to convert each element of the resulting list into a dict:

import re
import json

s = "{'tempo': 99000, 'lider': 0, 'visao': 1}, {'tempo': 99000, 'lider': 1, 'visao': 0}"

#json.loads expects double quotes, so replace single with double
s = s.replace("'", '"')

# regex pattern to match ", " between } and { characters
pattern = "(?<={)*, (?={)"

# split string based on regex pattern, parse each element to a dict with json.loads
d = [json.loads(d) for d in re.split(pattern, s)]
print(d)


问:
How to insert a dictionary to a sqlite database?
I'm trying to write a dictionary into sql database, but without success giving me:

```<code>Error binding parameter 3 - probably unsupported type.
</code>```

data structure:

```<code>{
"url": "https://www.wellness.com/dir/6022571/acupuncturist/ri/east-greenwich/hwasook-lee-phoenix-
fertility-center-dac",
"First_and_Last_Name": "Hwasook Lee, D.Ac.",
"About": "Phoenix Fertility Center specializes in the treatment of infertility, hormonal imbalances,
women's health and pregnancy related conditions. Our passion revolves around empowering you to
understand how your body works and how your everyday habits like eating and sleeping have a direct
impact on your health. ",
"Services": [
"When I entered acupuncture school, I knew that I wanted to specialize in women's health and
gynecology. ", "One of my mandates as an acupuncturist is to empower my...", "Fertility"
]}
</code>```

code:

```<code>db = sqlite3.connect('wellness.db')

    db.execute('''CREATE TABLE IF NOT EXISTS wellness(id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                   url TEXT, First_and_Last_Name TEXT,
                                                   About TEXT, Services TEXT);''')
    cursor = db.cursor()
    cursor.execute('INSERT INTO wellness(url, First_and_Last_Name, About, Services) VALUES(?, ?, ?, ?)',
                  (item['url'], item['First_and_Last_Name'], item['About'], item['Services']))

    db.commit()
    db.close()
</code>```

答:
The

item['Services']

it contains a list and not a string

```<code>cursor.execute('INSERT INTO wellness(url, First_and_Last_Name, About, Services) VALUES(?, ?, ?, ?)',
                  (item['url'], item['First_and_Last_Name'], item['About'], '-'.join(item['Services'])  ))
</code>```

try to use join in order for them to make a full string since the item['Services'] is a list

Body:
I'm trying to write a dictionary into sql database, but without success giving me:

Error binding parameter 3 - probably unsupported type.

data structure:

{
"url": "https://www.wellness.com/dir/6022571/acupuncturist/ri/east-greenwich/hwasook-lee-phoenix-
fertility-center-dac",
"First_and_Last_Name": "Hwasook Lee, D.Ac.",
"About": "Phoenix Fertility Center specializes in the treatment of infertility, hormonal imbalances,
women's health and pregnancy related conditions. Our passion revolves around empowering you to
understand how your body works and how your everyday habits like eating and sleeping have a direct
impact on your health. ",
"Services": [
"When I entered acupuncture school, I knew that I wanted to specialize in women's health and
gynecology. ", "One of my mandates as an acupuncturist is to empower my...", "Fertility"
]}

code:

db = sqlite3.connect('wellness.db')

    db.execute('''CREATE TABLE IF NOT EXISTS wellness(id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                   url TEXT, First_and_Last_Name TEXT,
                                                   About TEXT, Services TEXT);''')
    cursor = db.cursor()
    cursor.execute('INSERT INTO wellness(url, First_and_Last_Name, About, Services) VALUES(?, ?, ?, ?)',
                  (item['url'], item['First_and_Last_Name'], item['About'], item['Services']))

    db.commit()
    db.close()

Body:
The

item['Services']

it contains a list and not a string

cursor.execute('INSERT INTO wellness(url, First_and_Last_Name, About, Services) VALUES(?, ?, ?, ?)',
                  (item['url'], item['First_and_Last_Name'], item['About'], '-'.join(item['Services'])  ))

try to use join in order for them to make a full string since the item['Services'] is a list


问:
Connecting a Javascript client with Node.js/express server
My friend finished developing a functioning client website via Javascript. I have my server code running in which it grabs certain data via MySQL. Could you guys give us some tips on how we could connect the Node.js server code to the client side? (in which we're hoping for the client side and server side to be separate, and have a medium connecting both together). From what I've gathered from my research, socket could be a viable option? Any help is greatly appreciated!! </p>

答: You can try to build a sort of API server side and then use something like ajax/xhr requests to import data into the client.</p>


问:
Can't add a .egg file to scrapyd addversion.json
The problem I had is I can't upload my .egg file to scrapyd using

curl http://127.0.0.1:6800/addversion.json -F project=scraper_app -F version=r1 egg=@scraper_app-0.0.1-py3.8.egg

its returning an error message like this

{"node_name": "Workspace", "status": "error", "message": "b'egg'"}

So I'm using Django and Scrapy in the same project, and I had this folder structure

```<code>my_app/
-- apps/  # django apps folder
   -- crawler/
      -- __init__.py
      -- admin.py
      -- apps.py
      -- etc..
   -- pages/
      -- __init__.py
      -- admin.py
      -- apps.py
      -- etc..
-- my_app/  # django project folder
   -- __init__.py
   -- asgi.py
   -- settings.py
   -- etc..
-- scraper_app/ # scrapy dir
   -- scraper_app/ # scrapy project folder
      -- spiders/
         -- abc_spider.py
      -- __init__.py
      -- middlewares.py
      -- pipelines.py
      -- settings.py
      -- etc..
   -- scrapy.cfg
-- manage.py
-- scrapyd.conf
-- setup.py  # setuptools for creating the egg file
-- etc..
</code>```

and here is what my setup.py looks like

from setuptools import setup, find_packages

setup(
    name="scraper_app",
    version="1.0.0",
    author="Khrisna Gunanasurya",
    author_email="contact@khrisnagunanasurya.com",
    description="Create egg file from 'scraper_app'",
    packages=find_packages(where=['scraper_app'])
)
```

<p>my <code>scrapyd.conf</code> file</p>

<pre class="lang-py prettyprint-override"><code>[scrapyd]
eggs_dir    = eggs
logs_dir    = logs
logs_to_keep = 5
dbs_dir     = dbs
max_proc    = 0
max_proc_per_cpu = 4
http_port   = 6800
debug       = off
runner      = scrapyd.runner
application = scrapyd.app.application
</code>```

and my scrapy.cfg content

[settings]
default = scraper_app.settings

[deploy]
url = http://127.0.0.1:6800/
project = scraper_app
```

So what I want is add an .egg file to my scrapyd/addversion.json and here is my step by step to achieve what I want:

run py setup.py bdist_egg

.egg file being generated in dist/ folder and its called scraper_app-0.0.1-py3.8.egg

cd to dist/ folder

run curl http://127.0.0.1:6800/addversion.json -F project=scraper_app -F version=r1 -F egg=@scraper_app-0.0.1-py3.8.egg

and then what I got is an error message, if I tried to run the curl from the root dirs, and run something like this curl http://127.0.0.1:6800/addversion.json -F project=scraper_app -F version=r1 -F egg=@dist\scraper_app-0.0.1-py3.8.egg (im using windows) it'll returning this error

curl: (6) Could not resolve host: dist\scraper_app-0.0.1-py3.8.egg

I already tried to googled it but I can't find how to solved this or what wrong step I make here, and I already tried to create the .egg file from the scraper_app dir directly, so just create an egg file from the scraper_app project folder, but its not working as well.

Can someone tell me whats wrong with my project? or what I do wrong in here?

thank you

答:
after I googled it more, and tried the scrapyd-client but there are lots of problem with windows, it doesnt easy to use the scrapyd-deploy, but I found a video on youtube that show me what is the correct way to install the scrapyd-client.

so here is the correct way to install it.

Make sure you inside a virtualenv, and then install the scrapyd-client with pip install git+https://github.com/scrapy/scrapyd.git. So it doesnt show any error or any difficulties to install it

and then you can just run scrapyd-deploy on the scrapy project folder.

Body:
The problem I had is I can't upload my .egg file to scrapyd using

curl http://127.0.0.1:6800/addversion.json -F project=scraper_app -F version=r1 egg=@scraper_app-0.0.1-py3.8.egg

its returning an error message like this

{"node_name": "Workspace", "status": "error", "message": "b'egg'"}

So I'm using Django and Scrapy in the same project, and I had this folder structure

my_app/
-- apps/  # django apps folder
   -- crawler/
      -- __init__.py
      -- admin.py
      -- apps.py
      -- etc..
   -- pages/
      -- __init__.py
      -- admin.py
      -- apps.py
      -- etc..
-- my_app/  # django project folder
   -- __init__.py
   -- asgi.py
   -- settings.py
   -- etc..
-- scraper_app/ # scrapy dir
   -- scraper_app/ # scrapy project folder
      -- spiders/
         -- abc_spider.py
      -- __init__.py
      -- middlewares.py
      -- pipelines.py
      -- settings.py
      -- etc..
   -- scrapy.cfg
-- manage.py
-- scrapyd.conf
-- setup.py  # setuptools for creating the egg file
-- etc..

and here is what my setup.py looks like

from setuptools import setup, find_packages

setup(
    name="scraper_app",
    version="1.0.0",
    author="Khrisna Gunanasurya",
    author_email="contact@khrisnagunanasurya.com",
    description="Create egg file from 'scraper_app'",
    packages=find_packages(where=['scraper_app'])
)

my scrapyd.conf file

[scrapyd]
eggs_dir    = eggs
logs_dir    = logs
logs_to_keep = 5
dbs_dir     = dbs
max_proc    = 0
max_proc_per_cpu = 4
http_port   = 6800
debug       = off
runner      = scrapyd.runner
application = scrapyd.app.application

and my scrapy.cfg content

[settings]
default = scraper_app.settings

[deploy]
url = http://127.0.0.1:6800/
project = scraper_app

So what I want is add an .egg file to my scrapyd/addversion.json and here is my step by step to achieve what I want:

run py setup.py bdist_egg

.egg file being generated in dist/ folder and its called scraper_app-0.0.1-py3.8.egg

cd to dist/ folder

run curl http://127.0.0.1:6800/addversion.json -F project=scraper_app -F version=r1 -F egg=@scraper_app-0.0.1-py3.8.egg

and then what I got is an error message, if I tried to run the curl from the root dirs, and run something like this curl http://127.0.0.1:6800/addversion.json -F project=scraper_app -F version=r1 -F egg=@dist\scraper_app-0.0.1-py3.8.egg (im using windows) it'll returning this error

curl: (6) Could not resolve host: dist\scraper_app-0.0.1-py3.8.egg

I already tried to googled it but I can't find how to solved this or what wrong step I make here, and I already tried to create the .egg file from the scraper_app dir directly, so just create an egg file from the scraper_app project folder, but its not working as well.

Can someone tell me whats wrong with my project? or what I do wrong in here?

thank you


问:
Can't see project folders in IntelliJ IDEA
Every once in a while, I open an old project and I can't see any of the folders in the intelliJ project viewer. I can see all the files at the root.. but no folders. Yes I can delete the .iml file and .idea folder and re-create the project, but come on.. there's gotta be an easier way to fix this.

Is there?

答:
All the project-specific settings for a project opened through Intellij IDE are stored in the .idea folder.

The .idea folder (hidden on OS X) in the solution root contains
  IntelliJ’s project-specific settings files. These include per-project
  details such as VCS mapping and run and debug configurations, as well
  as per-user details, such as currently open files, navigation history
  and currently selected configuration.

So, if you are not able to see the project file structure in your Intellij IDE, just delete the .idea folder,

rm -rf .idea

and reload the project, then after reload you'll be easily able to get your project structure displayed.

ContentLicense: CC BY-SA 3.0


问:
Pyspark: How do I extract lowest values per key?
My dataframe df:

```<code>C1    C2    C3
A     1     5
A     1     4
A     2     6
B     2     9
B     5     5

</code>```

I would like to extract the lowest value from C2 per distinct value in C1 as a new dataframe. So the output would be

```<code>C1    C2
A     1
B     2
</code>```

I think I'd have to use df.groupBy("C1"), but I'm not sure how to apply it correctly.

答:
below is another way of doing it.</p>
```<code>from pyspark.sql import functions as F

df.groupBy(F.col("C1")).agg({"C2":"min"}).orderBy(F.col("C1")).show()
</code>```

Body:
My dataframe df:

C1    C2    C3
A     1     5
A     1     4
A     2     6
B     2     9
B     5     5

I would like to extract the lowest value from C2 per distinct value in C1 as a new dataframe. So the output would be

C1    C2
A     1
B     2

I think I'd have to use df.groupBy("C1"), but I'm not sure how to apply it correctly.

Body:
below is another way of doing it.

from pyspark.sql import functions as F

df.groupBy(F.col("C1")).agg({"C2":"min"}).orderBy(F.col("C1")).show()


问:
Label that is passed not appearing
I am trying to create a tableview where once a tableview cell is selected, it passes the name of the cell to a new view controller. When I run this and select a tableview cell, I am brought to another view controller, but the organization label is not there. How do I fix this?

Here is my code for the first view controller.

```<code>import UIKit

struct Organizations {
    var sectionTitle = String()
    var rowTitles = [String]()
}

class SearchOrganizationsViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var searchOrganizations: Organizations?
    var organizations = [
        Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
        Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
        Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"]),
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
            cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
            cell?.textLabel?.numberOfLines = 3
            if searching {
                cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
            } else {
                cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
            }
            return cell!
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            selectedOrganizations = organizations[indexPath.row]
            performSegue(withIdentifier: "organizationDetailSegue", sender: self)
        }

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let destination = segue.destination as? OrganizationsDetailViewController {
                destination.organization = selectedOrganizations
            }
        }
    }
}
</code>```

Here is my code for the second view controller.

```<code>import UIKit

class OrganizationsDetailViewController: UIViewController {
    @IBOutlet weak var organizationNameLabel: UILabel!

    var organization: Organizations?

    var organizationName: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        organizationNameLabel.text = organizationName
    }
}
</code>```

答:
Do this experiment. Change

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? OrganizationsDetailViewController {
        destination.organization = selectedOrganizations
    }
}
</code>```

To

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? OrganizationsDetailViewController {
        destination.organizationName = "Zampabalooie"
    }
}
</code>```

Do you see something now? If so, now change it again, to show the text you actually want to see.

Title: Label that is passed not appearing

Body:
I am trying to create a tableview where once a tableview cell is selected, it passes the name of the cell to a new view controller. When I run this and select a tableview cell, I am brought to another view controller, but the organization label is not there. How do I fix this?

Here is my code for the first view controller.

import UIKit

struct Organizations {
    var sectionTitle = String()
    var rowTitles = [String]()
}

class SearchOrganizationsViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var searchOrganizations: Organizations?
    var organizations = [
        Organizations(sectionTitle: "section 1", rowTitles: ["organization 1", "organization 2", "organization 3"]),
        Organizations(sectionTitle: "section 2", rowTitles: ["organization 1", "organization 2"]),
        Organizations(sectionTitle: "section 3", rowTitles: ["organization 1"]),
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    extension SearchOrganizationsViewController: UITableViewDelegate, UITableViewDataSource {
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell")
            cell?.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
            cell?.textLabel?.numberOfLines = 3
            if searching {
                cell?.textLabel?.text = self.searchArray[indexPath.section].rowTitles[indexPath.row]
            } else {
                cell?.textLabel?.text = self.organizations[indexPath.section].rowTitles[indexPath.row]
            }
            return cell!
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            selectedOrganizations = organizations[indexPath.row]
            performSegue(withIdentifier: "organizationDetailSegue", sender: self)
        }

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let destination = segue.destination as? OrganizationsDetailViewController {
                destination.organization = selectedOrganizations
            }
        }
    }
}

Here is my code for the second view controller.

import UIKit

class OrganizationsDetailViewController: UIViewController {
    @IBOutlet weak var organizationNameLabel: UILabel!

    var organization: Organizations?

    var organizationName: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        organizationNameLabel.text = organizationName
    }
}

Body:
Do this experiment. Change

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? OrganizationsDetailViewController {
        destination.organization = selectedOrganizations
    }
}

To

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? OrganizationsDetailViewController {
        destination.organizationName = "Zampabalooie"
    }
}

Do you see something now? If so, now change it again, to show the text you actually want to see.


问:
Saving data to a file doesn't behave as expected
I have a simple project where I created a Store with customers, products and employees. Each is represented by a Class of course and I also have a CSV file for each one of them to be able to load data from and save data to it.

I'm facing issues where the file reading/writing is working, but not really. For example, I have the ability to save each file individually so if for instance I want to create a new customer, I'd save it to the list and then to the file. Issue is, once I do it for another Class (i.e if I create a new employee) and then save it again, the customer file object I saw in the CSV earlier is deleted. BUT, once I add a new object again, that same object reappears again. Hope you can somehow understand, but here is a more detailed view:

customer.csv is empty:

Me creating a new customer:

Created and saved to CSV:

Now, if I go to the other menu, and click on "Save all data" that jon snow customer object will be gone. Then if I create a new customer, then it will be added to the CSV file, along with the jon snow I added earlier. So why is it gone in the first place?

So here is the whole file reader/writer code I'm using:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

class CSV {

    static void CreateFile(String filename) { //Create new file
        try {
            File fileToCreate = new File(filename);
            if (fileToCreate.createNewFile()) {
                System.out.println("File created sucessfully: " + fileToCreate.getName());
            }
        } catch (IOException e) {
            System.out.println("Cannot create file!");
        }
    }

    static void ReadFile(String path_and_filename){
        try {
            File fileToRead = new File(path_and_filename);
            Scanner myReader = new Scanner(fileToRead);
            System.out.println("Reading file "+path_and_filename+" :");
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                System.out.println(data);
            }
            myReader.close();
            System.out.println();
        } catch (FileNotFoundException e) {
            System.out.println("There is no such file "+"\"path_and_filename\""+".\n");
        }
    }

    // The StringBuilder in Java represents a mutable sequence of characters.
    // Java's built in String class is not mutable.
    static void saveArrayListToFile(List<Output> listToSave, String fileName, String sep) throws Exception {
        StringBuilder ans = new StringBuilder();
        for (Output record : listToSave) {
            ans.append(record.createOutput());
            ans.append(sep);
        }
        saveStringToFile(ans.toString(), fileName);
        System.out.println("\nData saved to "+ fileName);
    }

    static void saveArrayListToFile1(ArrayList<String> listToSave, String fileName, String sep){
        StringBuilder ans = new StringBuilder();
        for (Object record : listToSave) {
            ans.append(record.toString());
            ans.append(sep);
        }
        saveStringToFile(ans.toString(), fileName);
        System.out.println("\nList was saved to file "+fileName+"\n");
    }

    static void saveStringToFile(String data, String fileName){
        BufferedWriter bufferedWriter=null;
        try {
            bufferedWriter = new BufferedWriter(
                    new FileWriter(fileName,false));
            bufferedWriter.write(data);
        } catch (IOException e) {
            System.out.println("Cannot write to file");
        } finally {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                System.out.println("Cannot write to file");
            }
        }
    }
}

```

<p>When I'm creating a new customer, I call it from a menu and it looks like this: </p>

<pre class="lang-java prettyprint-override"><code>            switch (selection) {
                case 1:
                    try {
                        System.out.println("You're registering as a new customer");
                        String custID = ObjectIDs.generateID();
                        System.out.println("Enter first name:");
                        String firstName = sc.next();
                        System.out.println("Enter last name:");
                        String lastName = sc.next();
                        st.newCustomer(custID, firstName, lastName);
                        st.saveCustomersList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
</code>```

the saveCustomerList() function is this:

@SuppressWarnings("unchecked")
    void saveCustomersList() throws Exception {
        CSV.saveArrayListToFile((List<Output>)(List<?>) customers, CUSTOMERS_FILE_PATH,"\n");
    }
```

And then the functions calls saveArrayListToFile() to save it.

The behavior is the same with Product and Employee projects, so I randomly chose to show how it acts when creating a new Product.

I hope I added enough information. If needed, I can paste more code in but I already feel it's very cluttered. Hopefully it's ok.

Thank you very much :)

答:
At the moment it's hard to say, as one can only hypothesise as to what happens when you click on "Save all data". There are some weird things (what is saveArrayListToFile and saveArrayListToFile11? Why does one declare an exception? When are these called?).

Having said that, look at the actual file writing method saveStringToFile, it says:

```<code>bufferedWriter = new BufferedWriter(new FileWriter(fileName,false));
</code>```

This false there means 'do not append to file, rewrite it from scratch'. So each time you call it, file contents are discarded and replaced from what you provide to the method call. So my somewhat educated guess would be:

You save customer one to file (gets cleared, customer 1 written) and
append the customer to a list of customers (that's my guess)

You
save customer two to file (file gets cleared, so only customer 2 is
saved), you add to list to customers (do you?)

Then you choose 'save all' which gets list of customers, and save them in one go, a single call to the method. The file is cleared, all customers are saved.

But it's all guessing. Try creating a minimal, reproducible example

Body:
I have a simple project where I created a Store with customers, products and employees. Each is represented by a Class of course and I also have a CSV file for each one of them to be able to load data from and save data to it.

I'm facing issues where the file reading/writing is working, but not really. For example, I have the ability to save each file individually so if for instance I want to create a new customer, I'd save it to the list and then to the file. Issue is, once I do it for another Class (i.e if I create a new employee) and then save it again, the customer file object I saw in the CSV earlier is deleted. BUT, once I add a new object again, that same object reappears again. Hope you can somehow understand, but here is a more detailed view:

customer.csv is empty:

Me creating a new customer:

Created and saved to CSV:

Now, if I go to the other menu, and click on "Save all data" that jon snow customer object will be gone. Then if I create a new customer, then it will be added to the CSV file, along with the jon snow I added earlier. So why is it gone in the first place?

So here is the whole file reader/writer code I'm using:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

class CSV {

    static void CreateFile(String filename) { //Create new file
        try {
            File fileToCreate = new File(filename);
            if (fileToCreate.createNewFile()) {
                System.out.println("File created sucessfully: " + fileToCreate.getName());
            }
        } catch (IOException e) {
            System.out.println("Cannot create file!");
        }
    }

    static void ReadFile(String path_and_filename){
        try {
            File fileToRead = new File(path_and_filename);
            Scanner myReader = new Scanner(fileToRead);
            System.out.println("Reading file "+path_and_filename+" :");
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                System.out.println(data);
            }
            myReader.close();
            System.out.println();
        } catch (FileNotFoundException e) {
            System.out.println("There is no such file "+"\"path_and_filename\""+".\n");
        }
    }

    // The StringBuilder in Java represents a mutable sequence of characters.
    // Java's built in String class is not mutable.
    static void saveArrayListToFile(List<Output> listToSave, String fileName, String sep) throws Exception {
        StringBuilder ans = new StringBuilder();
        for (Output record : listToSave) {
            ans.append(record.createOutput());
            ans.append(sep);
        }
        saveStringToFile(ans.toString(), fileName);
        System.out.println("\nData saved to "+ fileName);
    }

    static void saveArrayListToFile1(ArrayList<String> listToSave, String fileName, String sep){
        StringBuilder ans = new StringBuilder();
        for (Object record : listToSave) {
            ans.append(record.toString());
            ans.append(sep);
        }
        saveStringToFile(ans.toString(), fileName);
        System.out.println("\nList was saved to file "+fileName+"\n");
    }

    static void saveStringToFile(String data, String fileName){
        BufferedWriter bufferedWriter=null;
        try {
            bufferedWriter = new BufferedWriter(
                    new FileWriter(fileName,false));
            bufferedWriter.write(data);
        } catch (IOException e) {
            System.out.println("Cannot write to file");
        } finally {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                System.out.println("Cannot write to file");
            }
        }
    }
}

When I'm creating a new customer, I call it from a menu and it looks like this:

            switch (selection) {
                case 1:
                    try {
                        System.out.println("You're registering as a new customer");
                        String custID = ObjectIDs.generateID();
                        System.out.println("Enter first name:");
                        String firstName = sc.next();
                        System.out.println("Enter last name:");
                        String lastName = sc.next();
                        st.newCustomer(custID, firstName, lastName);
                        st.saveCustomersList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

the saveCustomerList() function is this:

@SuppressWarnings("unchecked")
    void saveCustomersList() throws Exception {
        CSV.saveArrayListToFile((List<Output>)(List<?>) customers, CUSTOMERS_FILE_PATH,"\n");
    }

And then the functions calls saveArrayListToFile() to save it.

The behavior is the same with Product and Employee projects, so I randomly chose to show how it acts when creating a new Product.

I hope I added enough information. If needed, I can paste more code in but I already feel it's very cluttered. Hopefully it's ok.

Thank you very much :)

Body:
At the moment it's hard to say, as one can only hypothesise as to what happens when you click on "Save all data". There are some weird things (what is saveArrayListToFile and saveArrayListToFile11? Why does one declare an exception? When are these called?).

Having said that, look at the actual file writing method saveStringToFile, it says:

bufferedWriter = new BufferedWriter(new FileWriter(fileName,false));

This false there means 'do not append to file, rewrite it from scratch'. So each time you call it, file contents are discarded and replaced from what you provide to the method call. So my somewhat educated guess would be:

You save customer one to file (gets cleared, customer 1 written) and
append the customer to a list of customers (that's my guess)

You
save customer two to file (file gets cleared, so only customer 2 is
saved), you add to list to customers (do you?)

Then you choose 'save all' which gets list of customers, and save them in one go, a single call to the method. The file is cleared, all customers are saved.

But it's all guessing. Try creating a minimal, reproducible example


问:
Pandas multiple ISO time columns to_datetime
I have multiple columns with ISO data strings like

"CreateDate": "2020-04-30T06:12:29.424Z", "ApprovedDate": "2020-04-30T06:21:30.504Z"

When I use column by column with

df['CreateDate'] = pd.to_datetime(df['CreateDate'], infer_datetime_format=True, utc=True)

it works fine. But

df[['CreateDate', 'ApprovedDate']] = pd.to_datetime(df[['CreateDate', 'ApprovedDate']], infer_datetime_format=True, utc=True)

gives me

ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing

Any ideas how to solve that? Tried all to_datetime options, but no succes.

答:
Since you have nice ISO format strings, you should not be required to call to_datetime with any keywords. Therefore, a simple apply should be an option:

```<code>import pandas as pd
df = pd.DataFrame({"CreateDate": ["2020-04-30T06:12:29.424Z"],
                   "ApprovedDate": ["2020-04-30T06:21:30.504Z"]})

df[['CreateDate', 'ApprovedDate']] = df[['CreateDate', 'ApprovedDate']].apply(pd.to_datetime)
# df
#                         CreateDate                     ApprovedDate
# 0 2020-04-30 06:12:29.424000+00:00 2020-04-30 06:21:30.504000+00:00
</code>```

Body:
Since you have nice ISO format strings, you should not be required to call to_datetime with any keywords. Therefore, a simple apply should be an option:

import pandas as pd
df = pd.DataFrame({"CreateDate": ["2020-04-30T06:12:29.424Z"],
                   "ApprovedDate": ["2020-04-30T06:21:30.504Z"]})

df[['CreateDate', 'ApprovedDate']] = df[['CreateDate', 'ApprovedDate']].apply(pd.to_datetime)
# df
#                         CreateDate                     ApprovedDate
# 0 2020-04-30 06:12:29.424000+00:00 2020-04-30 06:21:30.504000+00:00


问:
Deploy React-Redux webpack on heroku
Well, Im having a big problem, I have a front-end only react that send request to a ruby on rails api, we use redux, babel and webpack. My problem is, I cant make this react project work on Heroku.

This is a 503 response error from heroku.

Package.json:

```<code>{
  "name": "real-networking-ui",
  "version": "1.0.0",
  "description": "Real Netoworking UI",
  "main": "index.js",
  "scripts": {
    "start": "node -r babel-register ./node_modules/webpack-dev-server/bin/webpack-dev-server --config ./webpack.config.dev.js --progress --profile --colors",
    "build": "node -r babel-register ./node_modules/webpack/bin/webpack --config ./webpack.config.prod --progress --profile --colors",
    "lint": "eslint app test *.js"
  },
  "engines": {
    "node": "6.6.0"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^6.3.6",
    "babel-core": "^6.10.4",
    "babel-eslint": "^6.1.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-dev-expression": "^0.2.1",
    "babel-plugin-lodash": "^3.2.11",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-plugin-transform-remove-console": "^6.8.0",
    "babel-plugin-transform-remove-debugger": "^6.8.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-react-optimize": "^1.0.1",
    "babel-preset-stage-0": "^6.5.0",
    "babel-register": "^6.9.0",
    "classnames": "^2.2.5",
    "css-loader": "^0.23.1",
    "eslint": "^2.13.1",
    "eslint-config-airbnb": "^9.0.1",
    "eslint-import-resolver-webpack": "^0.3.2",
    "eslint-loader": "^1.6.1",
    "eslint-plugin-import": "^1.10.0",
    "eslint-plugin-jsx-a11y": "^1.5.3",
    "eslint-plugin-react": "^5.2.2",
    "extract-text-webpack-plugin": "^1.0.1",
    "html-webpack-plugin": "^2.21.0",
    "json-loader": "^0.5.4",
    "postcss-css-variables": "^0.5.1",
    "postcss-loader": "^0.9.1",
    "postcss-mixins": "^5.0.0",
    "postcss-nested": "^1.0.0",
    "postcss-partial-import": "^1.3.0",
    "react-transform-hmr": "^1.0.4",
    "style-loader": "^0.13.1",
    "svg-react": "^1.0.9",
    "webpack": "^1.13.1",
    "webpack-dev-server": "^1.14.1"
  },
  "dependencies": {
    "axios": "^0.15.3",
    "core-js": "^2.4.1",
    "css-loader": "^0.23.1",
    "lodash": "^4.17.2",
    "moment": "^2.17.1",
    "node-sass": "^3.13.0",
    "react": "^15.1.0",
    "react-dom": "^15.1.0",
    "react-hot-loader": "^3.0.0-beta.6",
    "react-maskedinput": "^3.3.1",
    "react-modal": "^1.6.4",
    "react-redux": "^4.4.5",
    "react-router": "^3.0.0",
    "react-router-redux": "^4.0.5",
    "react-select": "^1.0.0-rc.2",
    "react-select-box": "^3.0.1",
    "redux": "^3.5.2",
    "redux-thunk": "^2.1.0",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "svg-react": "^1.0.9",
    "validator": "^6.2.0",
    "whatwg-fetch": "^2.0.1"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  }
}
</code>```

webpack.config.base:

```<code>    import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';

export default {
  entry: './app/app.js',
  output: {
    path: './app/App/dist',
    filename: '/bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.json$/,
        loader: 'json',
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('css!sass'),

      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('css!sass'),
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.svg$/,
        loader: 'babel?presets[]=es2015,presets[]=react!svg-react',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './app/App/index.html',
    }),
    new ExtractTextPlugin('/app/App/css/default.css', {
      allChunks: true,
    }),
  ],
};
</code>```

webpack.config.dev:

```<code>    import webpack from 'webpack';
import baseConfig from './webpack.config.base';

const config = {
  ...baseConfig,
  debug: true,
  devtool: 'cheap-module-eval-source-map',
  plugins: [
    ...baseConfig.plugins,
    new webpack.HotModuleReplacementPlugin(),
  ],
  devServer: {
    colors: true,
    historyApiFallback: true,
    inline: true,
    hot: true,
  },
};
export default config;
</code>```

webpack.config.prod.js:

```<code>    import webpack from 'webpack';
import baseConfig from './webpack.config.base';

const config = {
  ...baseConfig,
  plugins: [
    ...baseConfig.plugins,
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        screw_ie8: true,
        warnings: false,
      },
    }),
  ],
};
export default config;
</code>```

Procfile:

```<code>web: npm start
</code>```

If you need more information about that tell me that I edit it.

Thank you for the help.

答: My take on this is the devDependencies should be re-installed under dependencies. Under similar circumstances I had the error screen when trying to deploy on Heroku. The devDependencies are ignored and whenever your code asks for them Heroku alarms. </p>

Title: Deploy React-Redux webpack on heroku

Body:
Well, Im having a big problem, I have a front-end only react that send request to a ruby on rails api, we use redux, babel and webpack. My problem is, I cant make this react project work on Heroku.

This is a 503 response error from heroku.

Package.json:

{
  "name": "real-networking-ui",
  "version": "1.0.0",
  "description": "Real Netoworking UI",
  "main": "index.js",
  "scripts": {
    "start": "node -r babel-register ./node_modules/webpack-dev-server/bin/webpack-dev-server --config ./webpack.config.dev.js --progress --profile --colors",
    "build": "node -r babel-register ./node_modules/webpack/bin/webpack --config ./webpack.config.prod --progress --profile --colors",
    "lint": "eslint app test *.js"
  },
  "engines": {
    "node": "6.6.0"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^6.3.6",
    "babel-core": "^6.10.4",
    "babel-eslint": "^6.1.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-dev-expression": "^0.2.1",
    "babel-plugin-lodash": "^3.2.11",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-plugin-transform-remove-console": "^6.8.0",
    "babel-plugin-transform-remove-debugger": "^6.8.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-react-optimize": "^1.0.1",
    "babel-preset-stage-0": "^6.5.0",
    "babel-register": "^6.9.0",
    "classnames": "^2.2.5",
    "css-loader": "^0.23.1",
    "eslint": "^2.13.1",
    "eslint-config-airbnb": "^9.0.1",
    "eslint-import-resolver-webpack": "^0.3.2",
    "eslint-loader": "^1.6.1",
    "eslint-plugin-import": "^1.10.0",
    "eslint-plugin-jsx-a11y": "^1.5.3",
    "eslint-plugin-react": "^5.2.2",
    "extract-text-webpack-plugin": "^1.0.1",
    "html-webpack-plugin": "^2.21.0",
    "json-loader": "^0.5.4",
    "postcss-css-variables": "^0.5.1",
    "postcss-loader": "^0.9.1",
    "postcss-mixins": "^5.0.0",
    "postcss-nested": "^1.0.0",
    "postcss-partial-import": "^1.3.0",
    "react-transform-hmr": "^1.0.4",
    "style-loader": "^0.13.1",
    "svg-react": "^1.0.9",
    "webpack": "^1.13.1",
    "webpack-dev-server": "^1.14.1"
  },
  "dependencies": {
    "axios": "^0.15.3",
    "core-js": "^2.4.1",
    "css-loader": "^0.23.1",
    "lodash": "^4.17.2",
    "moment": "^2.17.1",
    "node-sass": "^3.13.0",
    "react": "^15.1.0",
    "react-dom": "^15.1.0",
    "react-hot-loader": "^3.0.0-beta.6",
    "react-maskedinput": "^3.3.1",
    "react-modal": "^1.6.4",
    "react-redux": "^4.4.5",
    "react-router": "^3.0.0",
    "react-router-redux": "^4.0.5",
    "react-select": "^1.0.0-rc.2",
    "react-select-box": "^3.0.1",
    "redux": "^3.5.2",
    "redux-thunk": "^2.1.0",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "svg-react": "^1.0.9",
    "validator": "^6.2.0",
    "whatwg-fetch": "^2.0.1"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  }
}

webpack.config.base:

    import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';

export default {
  entry: './app/app.js',
  output: {
    path: './app/App/dist',
    filename: '/bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.json$/,
        loader: 'json',
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('css!sass'),

      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('css!sass'),
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.svg$/,
        loader: 'babel?presets[]=es2015,presets[]=react!svg-react',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './app/App/index.html',
    }),
    new ExtractTextPlugin('/app/App/css/default.css', {
      allChunks: true,
    }),
  ],
};

webpack.config.dev:

    import webpack from 'webpack';
import baseConfig from './webpack.config.base';

const config = {
  ...baseConfig,
  debug: true,
  devtool: 'cheap-module-eval-source-map',
  plugins: [
    ...baseConfig.plugins,
    new webpack.HotModuleReplacementPlugin(),
  ],
  devServer: {
    colors: true,
    historyApiFallback: true,
    inline: true,
    hot: true,
  },
};
export default config;

webpack.config.prod.js:

    import webpack from 'webpack';
import baseConfig from './webpack.config.base';

const config = {
  ...baseConfig,
  plugins: [
    ...baseConfig.plugins,
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        screw_ie8: true,
        warnings: false,
      },
    }),
  ],
};
export default config;

Procfile:

web: npm start

If you need more information about that tell me that I edit it.

Thank you for the help.


问:
How to skip end-tags (HTML) in VS code editor?
I have installed VS code editor with default settings. When I type a html code, for example the starting tag, <title> the ending tag is automatically generated i.e. </title>. But after typing the title inside those tags. I have to press 'right arrow' button repeatedly(here, 8 times) to come out of this HTML element(</title> tag).

Is there any shortcut such that I don't have to press 'right arrow' button repeatedly and instead any single key, which will skip the closing tag in one stroke of any button ?

答:
I know that you can type the ending tag and it'll also progress through it as if the autocompleted version wasn't there.

You can also use ctrl+right arrow to skip to the end of the line.

And if you use the Emmet extension, you can just press tab.


答:
Open keyboard shortcut settings, press Ctrl + Shift + P on windows or Cmd + Shift + P on mac and type keyboard shortcuts. Select the first option.

search for cursorLineEnd. Set any keyboard key combination, if not already set.

Result:

Title: How to skip end-tags (HTML) in VS code editor?

Body:
I have installed VS code editor with default settings. When I type a html code, for example the starting tag, <title> the ending tag is automatically generated i.e. </title>. But after typing the title inside those tags. I have to press 'right arrow' button repeatedly(here, 8 times) to come out of this HTML element(</title> tag).

Is there any shortcut such that I don't have to press 'right arrow' button repeatedly and instead any single key, which will skip the closing tag in one stroke of any button ?


答: If you're on Mac, it's cmd + right arrow. If you're on Linux/Windows, it's ctrl + right arrow. This doesn't skip the closing tag but skips to the end of the line, which close to what you want.


问:
local variable referenced before assignment when trying to plot
I have the following code

```<code>from math import floor
import matplotlib.pyplot as plt
import numpy as np

def drive(n, n2all, sofar):
    assert n > 0
    if n == 1:
        result = n2all[1]
    else:
        result = set()
        push = result.add
        for i in range(1, n//2 + 1):
            for x in n2all[i]:
                for y in n2all[n-i]:
                    for z in x+y, x*y:
                        if z not in sofar:
                            push(z)
    return result

def e(n):
    n2all = {1: set([1])}
    sofar = set([1])
    for i in range(1, n):
        this = drive(i, n2all, sofar)
        n2all[i] = this
        sofar |= this
    return min(list(this))

def E(n):
    k = floor(n / 3)
    if n ==1:
        return 1
    if n % 3 == 0:
        return 3 ** k
    if n % 3 == 1:
        return 4 * 3**(k-1)
    if n % 3 == 2:
        return 2 * 3**k

def func(n):
    return e(n) / E(n)
</code>```

and I want to get a picture of distribution of func(n). But whenever I try to calculate a values of func

```<code>n = 30
values = [func(i) for i in range(1, n)]
</code>```

I get the following error

local variable 'this' referenced before assignment

Or are there any other way to plot a hist or a line of this function?

答:
I think the problem lies in the e() function. The for loop need to be like so::

```<code>def e(n):
    n2all = {1: set([1])}
    sofar = set([1])
    for i in range(1, n+1):   #< ---just change this
    ...

</code>```

Body:
I have the following code

from math import floor
import matplotlib.pyplot as plt
import numpy as np

def drive(n, n2all, sofar):
    assert n > 0
    if n == 1:
        result = n2all[1]
    else:
        result = set()
        push = result.add
        for i in range(1, n//2 + 1):
            for x in n2all[i]:
                for y in n2all[n-i]:
                    for z in x+y, x*y:
                        if z not in sofar:
                            push(z)
    return result

def e(n):
    n2all = {1: set([1])}
    sofar = set([1])
    for i in range(1, n):
        this = drive(i, n2all, sofar)
        n2all[i] = this
        sofar |= this
    return min(list(this))

def E(n):
    k = floor(n / 3)
    if n ==1:
        return 1
    if n % 3 == 0:
        return 3 ** k
    if n % 3 == 1:
        return 4 * 3**(k-1)
    if n % 3 == 2:
        return 2 * 3**k

def func(n):
    return e(n) / E(n)

and I want to get a picture of distribution of func(n). But whenever I try to calculate a values of func

n = 30
values = [func(i) for i in range(1, n)]

I get the following error

local variable 'this' referenced before assignment

Or are there any other way to plot a hist or a line of this function?

Body:
I think the problem lies in the e() function. The for loop need to be like so::

def e(n):
    n2all = {1: set([1])}
    sofar = set([1])
    for i in range(1, n+1):   #< ---just change this
    ...


问:
Looping through Numpy Array elements
Is there a more readable way to code a loop in Python that goes through each element of a Numpy array? I have come up with the following code, but it seems cumbersome & not very readable:

```<code>import numpy as np
arr01 = np.random.randint(1,10,(3,3))
for i in range(0,(np.shape(arr01[0])[0]+1)):
    for j in range(0,(np.shape(arr01[1])[0]+1)):
        print (arr01[i,j])
</code>```

I could make it more explicit such as:

```<code>import numpy as np
arr01 = np.random.randint(1,10,(3,3))
rows = np.shape(arr01[0])[0]
cols = np.shape(arr01[1])[0]
for i in range(0, (rows + 1)):
    for j in range(0, (cols + 1)):
        print (arr01[i,j])
</code>```

However, that still seems a bit more cumbersome, compared to other languages, i.e. an equivalent code in VBA could read (supposing the array had already been populated):

```<code>dim i, j as integer
for i = lbound(arr01,1) to ubound(arr01,1)
   for j = lbound(arr01,2) to ubound(arr01,2)
       msgBox arr01(i, j)
   next j
next i
</code>```

答:
You should use the builtin function nditer, if you don't need to have the indexes values.

for elem in np.nditer(arr01):
    print(elem)
```

<p>EDIT: If you need indexes (as a tuple for 2D table), then:</p>

<pre class="lang-py prettyprint-override"><code>for index, elem in np.ndenumerate(arr01):
    print(index, elem)
</code>```

Title: Looping through Numpy Array elements

Body:
Is there a more readable way to code a loop in Python that goes through each element of a Numpy array? I have come up with the following code, but it seems cumbersome & not very readable:

import numpy as np
arr01 = np.random.randint(1,10,(3,3))
for i in range(0,(np.shape(arr01[0])[0]+1)):
    for j in range(0,(np.shape(arr01[1])[0]+1)):
        print (arr01[i,j])

I could make it more explicit such as:

import numpy as np
arr01 = np.random.randint(1,10,(3,3))
rows = np.shape(arr01[0])[0]
cols = np.shape(arr01[1])[0]
for i in range(0, (rows + 1)):
    for j in range(0, (cols + 1)):
        print (arr01[i,j])

However, that still seems a bit more cumbersome, compared to other languages, i.e. an equivalent code in VBA could read (supposing the array had already been populated):

dim i, j as integer
for i = lbound(arr01,1) to ubound(arr01,1)
   for j = lbound(arr01,2) to ubound(arr01,2)
       msgBox arr01(i, j)
   next j
next i

Body:
You should use the builtin function nditer, if you don't need to have the indexes values.

for elem in np.nditer(arr01):
    print(elem)

EDIT: If you need indexes (as a tuple for 2D table), then:

for index, elem in np.ndenumerate(arr01):
    print(index, elem)


问:
Flutter graphically show the user that the List has more items
I have a list of widgets with different heights. So it could be that the last item in the list is placed at the bottom of the screen and the user thinks the list is finished and does not recognize that he could scroll down.

Is there a way to graphically show that the user could scroll the list down?

Thanks for tips.

答:
According to a multitude of sources, the easiest way will be to show a scrollbar for a few seconds after the page has been loaded.

Feel free to check this post to find the best solution.


问:
Update multiple embeded documents in array based on their property values
I have a demo collection. In every document of the collection there is a array which contains several documents.A sample document is:

```<code>{
  _id: 1,
  persons: [{
    name: "Jack",
    gender: "Male"
  }, {
    name: "Ma",
    gender: "Female"
  }, {
    name: "Ho",
    gender: "Other"
  }]
}
</code>```

Think I want to change only the name property of gender= Male and gender= Other of  nested documents in persons array of document _id = 1 and based on the gender's value the name property  of each document value will be different.

Think gender= Male's document's name's value will be "Jul" and gender= Other's document's name's value will be "Tisa"

How can I design my single update query?

答:
You want to use arrayfilters

```<code>
db.collection.updateOne(
    {
        _id: 1,
    },
    {
        $set: {
            "persons.$[elem].name": "new_name",
        }
    },
    {
        arrayFilters: [{"elem.gender": {$in: ["Male", "Other"]}}]
    });
</code>```

EDIT:

```<code>db.collection.updateOne(
    {
        _id: 1,
    },
    {
        $set: {
            "persons.$[elem].name": "Jul",
            "persons.$[elem2].name": "Tisa",
        }
    },
    {
        arrayFilters: [
            {"elem.gender": "Male"},
            {"elem2.gender": "Other"},
        ]
    });
</code>```

Body:
I have a demo collection. In every document of the collection there is a array which contains several documents.A sample document is:

{
  _id: 1,
  persons: [{
    name: "Jack",
    gender: "Male"
  }, {
    name: "Ma",
    gender: "Female"
  }, {
    name: "Ho",
    gender: "Other"
  }]
}

Think I want to change only the name property of gender= Male and gender= Other of  nested documents in persons array of document _id = 1 and based on the gender's value the name property  of each document value will be different.

Think gender= Male's document's name's value will be "Jul" and gender= Other's document's name's value will be "Tisa"

How can I design my single update query?

Body:
You want to use arrayfilters

db.collection.updateOne(
    {
        _id: 1,
    },
    {
        $set: {
            "persons.$[elem].name": "new_name",
        }
    },
    {
        arrayFilters: [{"elem.gender": {$in: ["Male", "Other"]}}]
    });

EDIT:

db.collection.updateOne(
    {
        _id: 1,
    },
    {
        $set: {
            "persons.$[elem].name": "Jul",
            "persons.$[elem2].name": "Tisa",
        }
    },
    {
        arrayFilters: [
            {"elem.gender": "Male"},
            {"elem2.gender": "Other"},
        ]
    });


问:
Mongoose - How to incrementally subtract/reduce the value in subdocument array which is in another subdocument array
This one is pretty tricky,

I have this sample document

```<code>[{
  _id: '111',
  products: [{
    _id: 'productId',
    items: [{
      _id: 'aaa',
      quantity: 5
    }, {
      _id:'bbb',
      quantity: 8
    }]
  }]
}]
</code>```

Now when I buy an Item, I need the quantity to be reduced starting from the first one in items array down to the second, third etc...

This is to say, when I buy an Item, I need the quantity to be reduced in the first element of items array, and If the quantity to be reduced exceed, it should reduce the remained quantity in the second items array...and so forth

For example, If I buy 3 items, It should minus 3 items in the first array element and the resulting items array should be

```<code>...
    items: [{
      _id: 'aaa',
      quantity: 2
    }, {
      _id: 'bbb',
      quantity: 8
    }]
</code>```

On the other hand, If I would have bought 7 items, it should reduce all 5 items from first array element and then remove 2 items from the second element...and hence the final array would be like

```<code>...
    items: [{
      _id: 'aaa',
      quantity: 0
    }, {
      _id: 'bbb',
      quantity: 6
    }]
</code>```

WHAT I HAVE TRIED:

I tried using findOneAndUpdate like this, just to reach the items array, but I have no Idea how i should continue with the items part.

```<code>        Shop.findOneAndUpdate(
            { _id: '111', products._id: 'productId' }
        )
</code>```

答:
Although this is possible with MongoDB v4.2 (update pipeline) where you can update documents based on their current value. It would be very complex as you don't really have a native way to keep local variables (to keep track of how many items you already subtracted). You could use $reduce to keep that value, but it's going to look very complex as you have deeply nested data structures. It will be much easier if you can do it in the application layer, but then you have concurrency issues if your document changes in between.

Suggestions

Change your data structure, to be flatter, possibly separate into multiple collections. It's difficult to do updates in deeply nested items

Wait for MongoDB v4.4, where you have $accumulator and $function operators that can keep state and is more flexible to process your data using JavaScript

Use MongoDB v4.2 update pipeline, along with $reduce and $cond. With this approach, you have to maintain the state using $reduce and apply the quantity value according to the state, since you have nested array structures, you'll have to use $map as well.

As mentioned above, you can implement query the document, update in your application and put the change back to MongoDB, but you have to make sure there is no concurrent operation that is trying to update your document between read and write

Update: another solution is to wait for v4.4 $merge aggregation stage, which lets you output aggregation pipeline result to the same collection.

Update: I gave a try to implement #3 to show the complexity. Inspirations taken from an answer on your other question

Shop.updateOne({
  "_id": '111', "products._id": "productId" // don't forget to replace "productId"
}, [{
    "$set":{
      "products":{
        "$map":{
          "input":"$products", // iterate through products, we can not update inside the array directly as "arrayFilters" update option isn't available in pipeline update
          "in":{
            "$cond":[
              {
                "$ne":[
                  "$$this._id",
                  "productId" // don't forget to replace "productId"
                ]
              },
              "$$this",
              {
                "$mergeObjects":[
                  "$$this",
                  {
                    "items":{
                      "$reduce":{
                        "input":"$$this.items",
                        "initialValue":{ // initialise accumulator
                          "acc": 7, // the number you want to subtract
                          "items":[]
                        },
                        "in":{
                          "acc":{
                            "$subtract":[
                              "$$value.acc",
                              {
                                "$min":[
                                  "$$this.quantity",
                                  "$$value.acc"
                                ]
                              }
                            ]
                          },
                          "items":{
                            "$concatArrays":[
                              "$$value.items",
                              [
                                {
                                  "$mergeObjects":[
                                    "$$this",
                                    {
                                      "quantity":{
                                        "$subtract":[
                                          "$$this.quantity",
                                          {
                                            "$min":[
                                              "$$this.quantity",
                                              "$$value.acc"
                                            ]
                                          }
                                        ]
                                      }
                                    }
                                  ]
                                }
                              ]
                            ]
                          }
                        }
                      }
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }, // at this stage, you'll have all information you need, add the next stage only if you want it in the same structure
  {
    "$set":{
      "products":{
        "$map":{
          "input":"$products",
          "in":{
            "$cond":[
              {
                "$ne":[
                  "$$this._id",
                  "productId"
                ]
              },
              "$$this",
              {
                "$mergeObjects":[
                  "$$this",
                  {
                    "items":{
                      "$ifNull":[
                        "$$this.items.items",
                        "$$this.items"
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }
])
```

<p><em>Update #2 A "shorter" version which requires only one stage, using array instead of object to keep the accumulator.</em></p>

<pre class="lang-js prettyprint-override"><code>Shop.updateOne({
  "_id": '111', "products._id": "productId" // don't forget to replace "productId"
}, [
  {
    "$set": {
      "products": {
        "$map": {
          "input": "$products",
          "in": {
            "$cond": [
              {
                "$ne": [
                  "$$this._id",
                  "productId" // don't forget to replace "productId"
                ]
              },
              "$$this",
              {
                "$mergeObjects": [
                  "$$this",
                  {
                    "items": {
                      "$arrayElemAt": [
                        {
                          "$reduce": {
                            "input": "$$this.items",
                            "initialValue": [
                              7, // the number you want to subtract
                              []
                            ],
                            "in": [
                              {
                                "$subtract": [
                                  {
                                    "$arrayElemAt": [
                                      "$$value",
                                      0
                                    ]
                                  },
                                  {
                                    "$min": [
                                      "$$this.quantity",
                                      {
                                        "$arrayElemAt": [
                                          "$$value",
                                          0
                                        ]
                                      }
                                    ]
                                  }
                                ]
                              },
                              {
                                "$concatArrays": [
                                  {
                                    "$arrayElemAt": [
                                      "$$value",
                                      1
                                    ]
                                  },
                                  [
                                    {
                                      "$mergeObjects": [
                                        "$$this",
                                        {
                                          "quantity": {
                                            "$subtract": [
                                              "$$this.quantity",
                                              {
                                                "$min": [
                                                  "$$this.quantity",
                                                  {
                                                    "$arrayElemAt": [
                                                      "$$value",
                                                      0
                                                    ]
                                                  }
                                                ]
                                              }
                                            ]
                                          }
                                        }
                                      ]
                                    }
                                  ]
                                ]
                              }
                            ]
                          }
                        },
                        1
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }
])
</code>```

Body:
This one is pretty tricky,

I have this sample document

[{
  _id: '111',
  products: [{
    _id: 'productId',
    items: [{
      _id: 'aaa',
      quantity: 5
    }, {
      _id:'bbb',
      quantity: 8
    }]
  }]
}]

Now when I buy an Item, I need the quantity to be reduced starting from the first one in items array down to the second, third etc...

This is to say, when I buy an Item, I need the quantity to be reduced in the first element of items array, and If the quantity to be reduced exceed, it should reduce the remained quantity in the second items array...and so forth

For example, If I buy 3 items, It should minus 3 items in the first array element and the resulting items array should be

...
    items: [{
      _id: 'aaa',
      quantity: 2
    }, {
      _id: 'bbb',
      quantity: 8
    }]

On the other hand, If I would have bought 7 items, it should reduce all 5 items from first array element and then remove 2 items from the second element...and hence the final array would be like

...
    items: [{
      _id: 'aaa',
      quantity: 0
    }, {
      _id: 'bbb',
      quantity: 6
    }]

WHAT I HAVE TRIED:

I tried using findOneAndUpdate like this, just to reach the items array, but I have no Idea how i should continue with the items part.

        Shop.findOneAndUpdate(
            { _id: '111', products._id: 'productId' }
        )

Body:
Although this is possible with MongoDB v4.2 (update pipeline) where you can update documents based on their current value. It would be very complex as you don't really have a native way to keep local variables (to keep track of how many items you already subtracted). You could use $reduce to keep that value, but it's going to look very complex as you have deeply nested data structures. It will be much easier if you can do it in the application layer, but then you have concurrency issues if your document changes in between.

Suggestions

Change your data structure, to be flatter, possibly separate into multiple collections. It's difficult to do updates in deeply nested items

Wait for MongoDB v4.4, where you have $accumulator and $function operators that can keep state and is more flexible to process your data using JavaScript

Use MongoDB v4.2 update pipeline, along with $reduce and $cond. With this approach, you have to maintain the state using $reduce and apply the quantity value according to the state, since you have nested array structures, you'll have to use $map as well.

As mentioned above, you can implement query the document, update in your application and put the change back to MongoDB, but you have to make sure there is no concurrent operation that is trying to update your document between read and write

Update: another solution is to wait for v4.4 $merge aggregation stage, which lets you output aggregation pipeline result to the same collection.

Update: I gave a try to implement #3 to show the complexity. Inspirations taken from an answer on your other question

Shop.updateOne({
  "_id": '111', "products._id": "productId" // don't forget to replace "productId"
}, [{
    "$set":{
      "products":{
        "$map":{
          "input":"$products", // iterate through products, we can not update inside the array directly as "arrayFilters" update option isn't available in pipeline update
          "in":{
            "$cond":[
              {
                "$ne":[
                  "$$this._id",
                  "productId" // don't forget to replace "productId"
                ]
              },
              "$$this",
              {
                "$mergeObjects":[
                  "$$this",
                  {
                    "items":{
                      "$reduce":{
                        "input":"$$this.items",
                        "initialValue":{ // initialise accumulator
                          "acc": 7, // the number you want to subtract
                          "items":[]
                        },
                        "in":{
                          "acc":{
                            "$subtract":[
                              "$$value.acc",
                              {
                                "$min":[
                                  "$$this.quantity",
                                  "$$value.acc"
                                ]
                              }
                            ]
                          },
                          "items":{
                            "$concatArrays":[
                              "$$value.items",
                              [
                                {
                                  "$mergeObjects":[
                                    "$$this",
                                    {
                                      "quantity":{
                                        "$subtract":[
                                          "$$this.quantity",
                                          {
                                            "$min":[
                                              "$$this.quantity",
                                              "$$value.acc"
                                            ]
                                          }
                                        ]
                                      }
                                    }
                                  ]
                                }
                              ]
                            ]
                          }
                        }
                      }
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }, // at this stage, you'll have all information you need, add the next stage only if you want it in the same structure
  {
    "$set":{
      "products":{
        "$map":{
          "input":"$products",
          "in":{
            "$cond":[
              {
                "$ne":[
                  "$$this._id",
                  "productId"
                ]
              },
              "$$this",
              {
                "$mergeObjects":[
                  "$$this",
                  {
                    "items":{
                      "$ifNull":[
                        "$$this.items.items",
                        "$$this.items"
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Update #2 A "shorter" version which requires only one stage, using array instead of object to keep the accumulator.

Shop.updateOne({
  "_id": '111', "products._id": "productId" // don't forget to replace "productId"
}, [
  {
    "$set": {
      "products": {
        "$map": {
          "input": "$products",
          "in": {
            "$cond": [
              {
                "$ne": [
                  "$$this._id",
                  "productId" // don't forget to replace "productId"
                ]
              },
              "$$this",
              {
                "$mergeObjects": [
                  "$$this",
                  {
                    "items": {
                      "$arrayElemAt": [
                        {
                          "$reduce": {
                            "input": "$$this.items",
                            "initialValue": [
                              7, // the number you want to subtract
                              []
                            ],
                            "in": [
                              {
                                "$subtract": [
                                  {
                                    "$arrayElemAt": [
                                      "$$value",
                                      0
                                    ]
                                  },
                                  {
                                    "$min": [
                                      "$$this.quantity",
                                      {
                                        "$arrayElemAt": [
                                          "$$value",
                                          0
                                        ]
                                      }
                                    ]
                                  }
                                ]
                              },
                              {
                                "$concatArrays": [
                                  {
                                    "$arrayElemAt": [
                                      "$$value",
                                      1
                                    ]
                                  },
                                  [
                                    {
                                      "$mergeObjects": [
                                        "$$this",
                                        {
                                          "quantity": {
                                            "$subtract": [
                                              "$$this.quantity",
                                              {
                                                "$min": [
                                                  "$$this.quantity",
                                                  {
                                                    "$arrayElemAt": [
                                                      "$$value",
                                                      0
                                                    ]
                                                  }
                                                ]
                                              }
                                            ]
                                          }
                                        }
                                      ]
                                    }
                                  ]
                                ]
                              }
                            ]
                          }
                        },
                        1
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }
])


问:
Can't import tensorflow in Jupyter
The 'import tensorflow as tf" code seems to be giving me an Import Error response when I use that code in my Jupyter notebook. It would be important to note that I use Windows 10.

However, I am very sure that I downloaded tensorflow correctly.
enter image description here
1. I created a conda environment
2. Activated it
3. downloaded tensorflow
4. updated the version
5. used pip install IPykernel

Any tips? Thank you so much, Stack Overflow Community!

答:
Check whether you have installed the tensorflow library inside the environment.

Or else you can try coming out of the environment and trying again.

Title: Can't import tensorflow in Jupyter


问:
Mask for an Input to allow phone numbers?
Is it possible to have model-driven form in Angular 2 and implement a directive that would allow to mask an input field like a phone number entry (123) 123-4567?

答:
```<code><input type="text" formControlName="gsm" (input)="formatGsm($event.target.value)">

formatGsm(inputValue: String): String {
  const value = inputValue.replace(/[^0-9]/g, ''); // remove except digits
  let format = '(***) *** ** **'; // You can change format

  for (let i = 0; i < value.length; i++) {
    format = format.replace('*', value.charAt(i));
  }

  if (format.indexOf('*') >= 0) {
    format = format.substring(0, format.indexOf('*'));
  }

  return format.trim();
}
</code>```