问:
How to make a batch file delete itself?
Is it possible to make a batch file delete itself?

I have tried to make it execute another file to delete it but this did not work.

Does any one know how I could do it?

The batch file I am using is elevated. My OS is Windows 7 32 bit.

答:
In case someone else was trying to use user6811411's 3 run and then self destruct script and it was not working. I figured out the &'s were not being interpreted right. My solution was just to separate the commands like below.</p>

```<code>@Echo off
Rem batch main purpose
Rem
Rem
Set Tok=###
For /f %%C in ('find /C "%Tok%" ^<"%~f0"') Do Set /A Cnt=%%C
Echo Run-%Cnt%
If %Cnt% Geq 3 (goto) 2>nul & del "%~f0"
Echo %Tok%>>"%~f0" & Goto :Eof
</code>```

Title: How to make a batch file delete itself?

Body:
In case someone else was trying to use user6811411's 3 run and then self destruct script and it was not working. I figured out the &'s were not being interpreted right. My solution was just to separate the commands like below.

@Echo off
Rem batch main purpose
Rem
Rem
Set Tok=###
For /f %%C in ('find /C "%Tok%" ^<"%~f0"') Do Set /A Cnt=%%C
Echo Run-%Cnt%
If %Cnt% Geq 3 (goto) 2>nul & del "%~f0"
Echo %Tok%>>"%~f0" & Goto :Eof


来源: stackexchange

问:
Share gitlab-ci.yml between projects
We are thinking to move our ci from jenkins to gitlab. We have several projects that have the same build workflow. Right now we use a shared library where the pipelines are defined and the jenkinsfile inside the project only calls a method defined in the shared library defining the actual pipeline. So changes only have to be made at a single point affecting several projects.

I am wondering if the same is possible with gitlab ci? As far as i have found out it is not possible to define the gitlab-ci.yml outside the repository. Is there another way to define a pipeline and share this config with several projects to simplify maintainance?

答:
Since gitlab version 12.6, it's possible define a external .gitlab-cy.yml file.

To customize the path:

Go to the project's Settings > CI / CD.

Expand the General pipelines section.

Provide a value in the Custom CI configuration path field.

Click Save changes.
  ...

If the CI configuration will be hosted on an external site, the URL link must end with .yml:

http://example.com/generate/ci/config.yml

If the CI configuration will be hosted in a different project within
  GitLab, the path must be relative to the root directory in the other
  project, with the group and project name added to the end:

.gitlab-ci.yml@mygroup/another-project

my/path/.my-custom-file.yml@mygroup/another-project

ContentLicense: CC BY-SA 3.0

Title: Share gitlab-ci.yml between projects

ContentLicense: CC BY-SA 4.0


问:
How do I prevent auto-generated links in the GitHub wiki?
On a GitHub wiki page, if I type:

```<code>www.foobar.com
</code>```

GitHub automatically assumes this is a URL and makes the text a hyperlink to http://www.foobar.com. However, sometimes I do not want a hyperlink to be created. Is there a way to stop this behavior? Perhaps some sort of markdown?

答:
You can use a zero-width space to prevent most auto-linkers from interpreting characters as a URL

Here's an example with a zero width space inserted between https and :

https://example.com/

To insert one, you can copy from the url above or this page

See also this thread on twitter

Note: This can make it potentially very confusing for anyone trying to copy and paste the link manually into a URL, because it won't resolve, and it'll be unclear why.  This works best for joke URLs that you don't ever actually want to be traversed like www.great-answer-on-stack-overflow-kyle.com

Body:
On a GitHub wiki page, if I type:

www.foobar.com

GitHub automatically assumes this is a URL and makes the text a hyperlink to http://www.foobar.com. However, sometimes I do not want a hyperlink to be created. Is there a way to stop this behavior? Perhaps some sort of markdown?


问:
Why is it so hard to use gcloud commands from my host computer instead of the gcloud interactive shell?
Maybe I'm just a bit confused, but basically I'm trying to establish my workflow with using the gcloud cli through my own host (Mac) terminal rather than the provided gcloud interactive shell.

I'm authenticating with an IAM member by running:

gcloud auth login

It takes me to the Google Cloud login page, which I successfully authenticate with and then I get the following in my shell:

```<code>You are now logged in as [MY_EMAIL@gmail.com].
Your current project is [myproperty-1537056464248].  You can change this setting by running:

  $ gcloud config set project PROJECT_ID
</code>```

After this, I try to issue the following command:

```<code>gcloud container clusters create somename
</code>```

And I get the following error message:

```<code>ERROR: (gcloud.container.clusters.create) ResponseError: code=400, message=Project "myproperty-1537056464248" has no network named "default".
</code>```

My IAM user has the following roles:

Kubernetes Engine Cluster Admin

Owner

All I want to do is avoid using the gcloud interactive shell so I can:

Create clusters through the command line

Push docker builds to the Google Container Registry

List clusters

Create pods

etc...

But these IAM policies aren't really working how I expect.

Should I be using a service account instead?

答:
New projects should come with a network called default but I somehow ended up with one that didn't have a any networks at all (which caused me to see the same error).

After creating one...

```<code>gcloud compute networks create default
</code>```

I was able to create a GKE cluster like so:

```<code>gcloud container clusters create mattscluster --zone us-west2 --machine-type e2-standard-2
</code>```

Body:
Maybe I'm just a bit confused, but basically I'm trying to establish my workflow with using the gcloud cli through my own host (Mac) terminal rather than the provided gcloud interactive shell.

I'm authenticating with an IAM member by running:

gcloud auth login

It takes me to the Google Cloud login page, which I successfully authenticate with and then I get the following in my shell:

You are now logged in as [MY_EMAIL@gmail.com].
Your current project is [myproperty-1537056464248].  You can change this setting by running:

  $ gcloud config set project PROJECT_ID

After this, I try to issue the following command:

gcloud container clusters create somename

And I get the following error message:

ERROR: (gcloud.container.clusters.create) ResponseError: code=400, message=Project "myproperty-1537056464248" has no network named "default".

My IAM user has the following roles:

Kubernetes Engine Cluster Admin

Owner

All I want to do is avoid using the gcloud interactive shell so I can:

Create clusters through the command line

Push docker builds to the Google Container Registry

List clusters

Create pods

etc...

But these IAM policies aren't really working how I expect.

Should I be using a service account instead?

Body:
New projects should come with a network called default but I somehow ended up with one that didn't have a any networks at all (which caused me to see the same error).

After creating one...

gcloud compute networks create default

I was able to create a GKE cluster like so:

gcloud container clusters create mattscluster --zone us-west2 --machine-type e2-standard-2


问:
Using Laravel Homestead: "no input file specified"
I'm new to this so it's kinda have been taking me a while to set up, but following the official guide I still don't know where did I go wrong, my homestead.yaml looks like this

ip: "192.168.10.10" memory: 2048 cpus: 2 provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
      - ~/.ssh/id_rsa

folders:
      - map: C:\Users\user\Documents\Projects

to: /home/vagrant/code

sites:
      - map: homestead.test

to: /home/vagrant/code/public

databases:
      - homestead

features:
      - mariadb: false
      - ohmyzsh: false
      - webdriver: false

my host file looks like this:

192.168.10.10   homestead.test

but whenever I try to access http://homestead.test/ I get "no input file specified"
and I've tried most of the solutions online with entering vagrant reload --provision
and go through vagrant ssh and then create a new project using composer. Nothing worked for me.

I'd appreciate any additional guidance.

P.S.: I'm using Windows 10

答:
For homestead.yaml file, the spacing has to be 'spacebar' space, and spacing, indentation must be same as provide.

From the file alignment, clearly the spacing and indentation has ran off.


问:
ASP.NET Core 3.x - Access IoC Container
In ASP.NET Core 3.x, the usage of IoC containers like Autofac changed. Instead of returning some adapter instance in ConfigureServices, we have to use the new ConfigureContainer method.

My question is: how can I access the Autofac IContainer instance in the Configure method? I tried to call containerBuilder.Build within ConfigureContainer, to get a reference to the container instance, but then I get an exception that the container can only built once.

I am well aware that in normal use cases, there should be no need to pass around the container (Service Locator anti pattern etc.....). However, in this special case, we are using a middleware that resolves Command and Event handler types and it is based on Autofac. It needs the container instance.

Any chance to reference the IContainer instance once it has been built by the framework?

答:
If you really need to have dependency on the container you should add a dependency on ILifetimeScope and then resolve from this scope.

```<code>public class FooMiddleware
{
    public FooMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    private readonly RequestDelegate _next;

    public async Task InvokeAsync(HttpContext context, ILifetimeScope scope)
    {
        scope.Resolve<Foo>();
        await this._next(context);
    }
}
</code>```

Title: ASP.NET Core 3.x - Access IoC Container

Body:
If you really need to have dependency on the container you should add a dependency on ILifetimeScope and then resolve from this scope.

public class FooMiddleware
{
    public FooMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    private readonly RequestDelegate _next;

    public async Task InvokeAsync(HttpContext context, ILifetimeScope scope)
    {
        scope.Resolve<Foo>();
        await this._next(context);
    }
}


问:
Java regex question
I have a text something like

```<code>ab1ab2ab3ab4cd
</code>```

Can one create a java regular expression to obtain all subtrings that start with "ab" and end with "cd"? e.g:

```<code>ab1ab2ab3ab4cd
ab2ab3ab4cd
ab3ab4cd
ab4cd
</code>```

Thanks

答: Looks like you want either ab\w+?cd or \bab\w+?cd\b

Title: Java regex question

Body:
I have a text something like

ab1ab2ab3ab4cd

Can one create a java regular expression to obtain all subtrings that start with "ab" and end with "cd"? e.g:

ab1ab2ab3ab4cd
ab2ab3ab4cd
ab3ab4cd
ab4cd

Thanks


问:
python spider return empty json file
I created Json file in python to store scraped data using scrapy , but json file is empty although python scrapy spider scraped all data.i'm trying to store all scraped data into json file.in terminal on crawl command spider display all data but it did not import into json file. i can't find any solution
i'm sharing both files spider and also items.py

i use this command scrapy crawl scraper -o products.json

Spider.py

```<code>import scrapy
from bs4 import BeautifulSoup as Soup
from ..items import ScrapyArbiItem
import requests
from idna import unicode

class Scraper(scrapy.Spider):
    name = "scraper"

    start_urls = [
          'https://www.fenom.com/en/263-men',
        # 'https://www.fenom.com/en/263-men#/page-2',
        # 'https://www.fenom.com/en/263-men#/page-3',
        # 'https://www.fenom.com/en/263-men#/page-4',
        # 'https://www.fenom.com/en/263-men#/page-5',
        # 'https://www.fenom.com/en/263-men#/page-6',
        # 'https://www.fenom.com/en/263-men#/page-7',
    ]

    def parse(self, response):

        items = ScrapyArbiItem()

        page_soup = Soup(response.text, 'html.parser')
        uls = page_soup.find_all("ul", class_="product_list grid row")[0]
        # import pdb;
        # pdb.set_trace()
        for li in uls.find_all("li", class_="ajax_block_product block_home col-xs-6 col-sm-4
        col-md-3"):
            data_to_write = []
            try:
                # print("gnbfrgjrnbgfjnbruigbnruig")
                div = li.find('div', class_='product-container')
                left_block = div.find('div', class_="left-block")
                image_container = left_block.find('div', class_="product-image-container")
                image = image_container.find('a')
                image_url_a = image_container.find('a', class_="product_img_link")
                image_url = image_url_a.find('img', class_='replace-2x img-responsive')
                image_url = image_url.get('src')  # image_url
                url = image.get('href')  # url of product
                right_block = div.find('div', class_="right-block")
                right_a = right_block.find('a')
                product = right_a.find('span', class_="product-name")
                product_name = product.text  # product_name
                pp = right_a.find('span', class_="content_price")
                product_p = pp.find('span', class_="product-price")
                product_price = product_p.text  # product_price

                items ['product_name'] = product_name
                items['product_price'] = product_price
                items['url'] = url

                print(items)
                #print(product_name)
                #print(product_price)
                #print(url)
                #print(image_url)
                next_page = url
                # import pdb;pdb.set_trace()
                # print(url)
                # if url:
                #     yield scrapy.Request(url, callback=self.parsetwo, dont_filter=True)
            except:
                pass
</code>```

items.py

in this file is to arrange all extracted data into temporary containers

```<code>import scrapy

class ScrapyArbiItem(scrapy.Item):
    # define the fields for your item here like:
    product_name = scrapy.Field()
    product_price = scrapy.Field()
    url = scrapy.Field()
</code>```

答:
i use  yield(items) instead of  print(items) and it resolve issue.</p>

```<code>`import scrapy
from bs4 import BeautifulSoup as Soup
from ..items import ScrapyArbiItem
import requests
from idna import unicode

class Scraper(scrapy.Spider):
    name = "scraper"

    page_number = 2 #for paginatiom

    start_urls = [
          'https://www.fenom.com/en/263-men#/page-1', #firstpage
    ]

    def parse(self, response):

        items = ScrapyArbiItem() #for items container-storing extracted data

        page_soup = Soup(response.text, 'html.parser')
        uls = page_soup.find_all("ul", class_="product_list grid row")[0]

        for li in uls.find_all("li", class_="ajax_block_product block_home col-xs-6 col-sm-4 col-md-3"):

            try:
                # print("gnbfrgjrnbgfjnbruigbnruig")
                div = li.find('div', class_='product-container')
                left_block = div.find('div', class_="left-block")
                image_container = left_block.find('div', class_="product-image-container")
                image = image_container.find('a')
                image_url_a = image_container.find('a', class_="product_img_link")
                image_url = image_url_a.find('img', class_='replace-2x img-responsive')
                image_url = image_url.get('src')  # image_url
                url = image.get('href')  # url of product
                right_block = div.find('div', class_="right-block")
                right_a = right_block.find('a')
                product = right_a.find('span', class_="product-name")
                product_name = product.text  # product_name
                pp = right_a.find('span', class_="content_price")
                product_p = pp.find('span', class_="product-price")
                product_price = product_p.text  # product_price

                items ['product_name'] = product_name
                items['product_price'] = product_price
                items['url'] = url

                yield (items)
                #print(product_name)
                #print(product_price)
                #print(url)
                #print(image_url)
            except:
                pass`
</code>```

Title: python spider return empty json file

Body:
I created Json file in python to store scraped data using scrapy , but json file is empty although python scrapy spider scraped all data.i'm trying to store all scraped data into json file.in terminal on crawl command spider display all data but it did not import into json file. i can't find any solution
i'm sharing both files spider and also items.py

i use this command scrapy crawl scraper -o products.json

Spider.py

import scrapy
from bs4 import BeautifulSoup as Soup
from ..items import ScrapyArbiItem
import requests
from idna import unicode

class Scraper(scrapy.Spider):
    name = "scraper"

    start_urls = [
          'https://www.fenom.com/en/263-men',
        # 'https://www.fenom.com/en/263-men#/page-2',
        # 'https://www.fenom.com/en/263-men#/page-3',
        # 'https://www.fenom.com/en/263-men#/page-4',
        # 'https://www.fenom.com/en/263-men#/page-5',
        # 'https://www.fenom.com/en/263-men#/page-6',
        # 'https://www.fenom.com/en/263-men#/page-7',
    ]

    def parse(self, response):

        items = ScrapyArbiItem()

        page_soup = Soup(response.text, 'html.parser')
        uls = page_soup.find_all("ul", class_="product_list grid row")[0]
        # import pdb;
        # pdb.set_trace()
        for li in uls.find_all("li", class_="ajax_block_product block_home col-xs-6 col-sm-4
        col-md-3"):
            data_to_write = []
            try:
                # print("gnbfrgjrnbgfjnbruigbnruig")
                div = li.find('div', class_='product-container')
                left_block = div.find('div', class_="left-block")
                image_container = left_block.find('div', class_="product-image-container")
                image = image_container.find('a')
                image_url_a = image_container.find('a', class_="product_img_link")
                image_url = image_url_a.find('img', class_='replace-2x img-responsive')
                image_url = image_url.get('src')  # image_url
                url = image.get('href')  # url of product
                right_block = div.find('div', class_="right-block")
                right_a = right_block.find('a')
                product = right_a.find('span', class_="product-name")
                product_name = product.text  # product_name
                pp = right_a.find('span', class_="content_price")
                product_p = pp.find('span', class_="product-price")
                product_price = product_p.text  # product_price

                items ['product_name'] = product_name
                items['product_price'] = product_price
                items['url'] = url

                print(items)
                #print(product_name)
                #print(product_price)
                #print(url)
                #print(image_url)
                next_page = url
                # import pdb;pdb.set_trace()
                # print(url)
                # if url:
                #     yield scrapy.Request(url, callback=self.parsetwo, dont_filter=True)
            except:
                pass

items.py

in this file is to arrange all extracted data into temporary containers

import scrapy

class ScrapyArbiItem(scrapy.Item):
    # define the fields for your item here like:
    product_name = scrapy.Field()
    product_price = scrapy.Field()
    url = scrapy.Field()

Body:
i use  yield(items) instead of  print(items) and it resolve issue.

`import scrapy
from bs4 import BeautifulSoup as Soup
from ..items import ScrapyArbiItem
import requests
from idna import unicode

class Scraper(scrapy.Spider):
    name = "scraper"

    page_number = 2 #for paginatiom

    start_urls = [
          'https://www.fenom.com/en/263-men#/page-1', #firstpage
    ]

    def parse(self, response):

        items = ScrapyArbiItem() #for items container-storing extracted data

        page_soup = Soup(response.text, 'html.parser')
        uls = page_soup.find_all("ul", class_="product_list grid row")[0]

        for li in uls.find_all("li", class_="ajax_block_product block_home col-xs-6 col-sm-4 col-md-3"):

            try:
                # print("gnbfrgjrnbgfjnbruigbnruig")
                div = li.find('div', class_='product-container')
                left_block = div.find('div', class_="left-block")
                image_container = left_block.find('div', class_="product-image-container")
                image = image_container.find('a')
                image_url_a = image_container.find('a', class_="product_img_link")
                image_url = image_url_a.find('img', class_='replace-2x img-responsive')
                image_url = image_url.get('src')  # image_url
                url = image.get('href')  # url of product
                right_block = div.find('div', class_="right-block")
                right_a = right_block.find('a')
                product = right_a.find('span', class_="product-name")
                product_name = product.text  # product_name
                pp = right_a.find('span', class_="content_price")
                product_p = pp.find('span', class_="product-price")
                product_price = product_p.text  # product_price

                items ['product_name'] = product_name
                items['product_price'] = product_price
                items['url'] = url

                yield (items)
                #print(product_name)
                #print(product_price)
                #print(url)
                #print(image_url)
            except:
                pass`


问:
Group by of dataframe with average of a column
I am really new to python..just a week ago started learning it. I have a query and hope you guys can help me to solve it. Thanks in advance..!!

I have data in below format.

```<code>Date        Product Price   Discount
1/1/2020    A   17,490  30
1/1/2020    B   34,990  21
1/1/2020    C   20,734  11
1/2/2020    A   16,884  26
1/2/2020    B   26,990  40
1/2/2020    C   17,936  10
1/3/2020    A   16,670  36
1/3/2020    B   12,990  13
1/3/2020    C   30,990  43
</code>```

I want to take the average of discount column for each date and just have 2 columns.. It aint working out.. :(

```<code>Date        AVG_Discount
1/1/2020    x %
1/2/2020    y %
1/3/2020    z %
</code>```

What I have tried doing is below.. As I said, I am novice in Python so approach might be incorrect.. Need guidance guys.. TIA

```<code>mean_col=df.groupby(df['time'])['discount'].mean()
df=df.set_index(['time'])
df['mean_col']=mean_col
df=df.reset_index()
</code>```

答:
df.groupby(df['time'])['discount'].mean() Is already returning series with time as index.

All you need to do is just use reset_index function on this.

```<code>grouped_df = df.groupby(df['time'])['discount'].mean().reset_index()
</code>```

As Quang Hoang Suggested in comments. You can also pass as_index=False to groupby.

Body:
I am really new to python..just a week ago started learning it. I have a query and hope you guys can help me to solve it. Thanks in advance..!!

I have data in below format.

Date        Product Price   Discount
1/1/2020    A   17,490  30
1/1/2020    B   34,990  21
1/1/2020    C   20,734  11
1/2/2020    A   16,884  26
1/2/2020    B   26,990  40
1/2/2020    C   17,936  10
1/3/2020    A   16,670  36
1/3/2020    B   12,990  13
1/3/2020    C   30,990  43

I want to take the average of discount column for each date and just have 2 columns.. It aint working out.. :(

Date        AVG_Discount
1/1/2020    x %
1/2/2020    y %
1/3/2020    z %

What I have tried doing is below.. As I said, I am novice in Python so approach might be incorrect.. Need guidance guys.. TIA

mean_col=df.groupby(df['time'])['discount'].mean()
df=df.set_index(['time'])
df['mean_col']=mean_col
df=df.reset_index()

Body:
df.groupby(df['time'])['discount'].mean() Is already returning series with time as index.

All you need to do is just use reset_index function on this.

grouped_df = df.groupby(df['time'])['discount'].mean().reset_index()

As Quang Hoang Suggested in comments. You can also pass as_index=False to groupby.


问:
Calculating shadow values for all Material Design elevations
In the latest Material Design documentation (https://www.google.com/design/spec/what-is-material/elevation-shadows.html#elevation-shadows-elevation-android-) an exhaustive set of UI elements are referenced with their respective elevation (z-index in dp). For example a switch is elevated by 1dp, while a dialog is elevated by 24dp. Currently Google's list of UI elements uses 10 different elevation levels. Since the elevation decides the shadow of the element, we'll need 10 different shadows. And that's where I'm lost.

How do you calculate/deduce the right shadow values (color, x-offset, y-offset, blur, spread) for each elevation level?

I've found different sources that have calculated shadow values for 5 different elevations (https://news.layervault.com/stories/42319-calculating-shadow-values-for-material-design). However, 5 elevation steps is not enough, nor do they give an explanation as to how they got to these respective values.

答:
The following JS function receives level of elevation, and returns results which are very close to Google's Material components.

export const getShadow = (elevation=1) => {
    const extraEl = elevation-1
    const getSize = (v1, v24) => `${v1+Math.round(((v24-v1)/23)*extraEl)}px`
    const getShade = (y, blur, spread, alpha) =>
        `0 ${getSize(y[0], y[1])} ${getSize(blur[0], blur[1])} ${getSize(spread[0], spread[1])} rgba(0,0,0,${alpha})`

    return `box-shadow: ${getShade([2,11], [1,15], [-1,-7], 0.2)}, ${getShade([1,24], [1,38], [0,3], 0.14)}, ${getShade([1,9], [3,46], [0,8], 0.12)};`
}
```

<h3>Demo</h3>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const getShadow = (elevation=1) => {
 const extraEl = elevation-1
 const getSize = (v1, v24) => `${v1+Math.round(((v24-v1)/23)*extraEl)}px`
 const getShade = (y, blur, spread, alpha) =>
  `0 ${getSize(y[0], y[1])} ${getSize(blur[0], blur[1])} ${getSize(spread[0], spread[1])} rgba(0,0,0,${alpha})`

 return `box-shadow: ${getShade([2,11], [1,15], [-1,-7], 0.2)}, ${getShade([1,24], [1,38], [0,3], 0.14)}, ${getShade([1,9], [3,46], [0,8], 0.12)};`
}

const appDiv = document.getElementById('app');
appDiv.innerHTML = `<div style="margin: 50px; width: 100px; height: 100px; ${getShadow(12)}">Hello world</div>`;</code>```

```

It uses values from the first and last (24th) levels of elevation.

Body:
The following JS function receives level of elevation, and returns results which are very close to Google's Material components.

export const getShadow = (elevation=1) => {
    const extraEl = elevation-1
    const getSize = (v1, v24) => `${v1+Math.round(((v24-v1)/23)*extraEl)}px`
    const getShade = (y, blur, spread, alpha) =>
        `0 ${getSize(y[0], y[1])} ${getSize(blur[0], blur[1])} ${getSize(spread[0], spread[1])} rgba(0,0,0,${alpha})`

    return `box-shadow: ${getShade([2,11], [1,15], [-1,-7], 0.2)}, ${getShade([1,24], [1,38], [0,3], 0.14)}, ${getShade([1,9], [3,46], [0,8], 0.12)};`
}

Demo

const getShadow = (elevation=1) => {
 const extraEl = elevation-1
 const getSize = (v1, v24) => `${v1+Math.round(((v24-v1)/23)*extraEl)}px`
 const getShade = (y, blur, spread, alpha) =>
  `0 ${getSize(y[0], y[1])} ${getSize(blur[0], blur[1])} ${getSize(spread[0], spread[1])} rgba(0,0,0,${alpha})`

 return `box-shadow: ${getShade([2,11], [1,15], [-1,-7], 0.2)}, ${getShade([1,24], [1,38], [0,3], 0.14)}, ${getShade([1,9], [3,46], [0,8], 0.12)};`
}

const appDiv = document.getElementById('app');
appDiv.innerHTML = `<div style="margin: 50px; width: 100px; height: 100px; ${getShadow(12)}">Hello world</div>`;

<div id="app"></div>

It uses values from the first and last (24th) levels of elevation.


问:
How can keep or save the selected value?
I am working with Spring boot, security and Thymeleaf:
I have a table with the data from a database, I have created filters, when I select a value, the table show the data filtered, so I want to implement multiple filters and keep the value selected when I change the page. So I had the idea to create variables where I can keep the selected values:

```<code>private Optional <TRACKING_CARD> typeSelected;

private Optional <STATUS> statusSelected;

private Optional <Boolean> flagStaff;
</code>```

and when I select the values:

```<code>typeSelected = filter.getType();
statusSelected = filter.getStatus();
flagStaff = filter.getFlag();
</code>```

But the problem is that the variables are global, so if more than one user is logged in the same time, they share the value of the variables.

How can solve this?

Thanks

答:
You need to initialise them separately for all users or instances. So every user will have their own instance. Even filters need to be initialise with user login.

Different instances for users will solve this problem.

Body:
I am working with Spring boot, security and Thymeleaf:
I have a table with the data from a database, I have created filters, when I select a value, the table show the data filtered, so I want to implement multiple filters and keep the value selected when I change the page. So I had the idea to create variables where I can keep the selected values:

private Optional <TRACKING_CARD> typeSelected;

private Optional <STATUS> statusSelected;

private Optional <Boolean> flagStaff;

and when I select the values:

typeSelected = filter.getType();
statusSelected = filter.getStatus();
flagStaff = filter.getFlag();

But the problem is that the variables are global, so if more than one user is logged in the same time, they share the value of the variables.

How can solve this?

Thanks


问:
Retaining Leading Zero when Copy & Pasting
I have the below code that is copy & pasting data from one sheet to another.

If you need further details:Offset the Copy Row as part of a Loop

The main problem I am having is retaining the leading zero on the sizes once split into individual rows.

```<code>    COL_SIZE in "SS21 Master Sheet"= 06|612|1218|1824
    Column "AH" in "Buysheet" is = 6
                                   612
                                   1218
                                   1824
</code>```

How can i set column AH as Text so that it retains the zero (06)? I have tried a couple of options but none of them are working at the moment.

```<code>Private Sub Workbook_Open()

Sheets("BUYSHEET").Cells.Clear

  Const COL_SIZE As String = "AO" 'This is the column with all the sizes listed in the mini master

  Dim wb1 As Workbook, wsSource As Worksheet
  Set wb1 = Workbooks.Open("U:\Design\KIDS\SS21 Kids Miniscale (Master) .xlsm") ' This is the file path to your mini master.
  Dim wb2 As Workbook, wsTarget As Worksheet
  Set wb2 = ThisWorkbook
  Dim iLastRow As Long, iTarget As Long, iRow As Long
  Dim rngSource As Range, ar As Variant, i As Integer

  Set wsSource = wb1.Sheets("SS21 Master Sheet") ' This is the name of your manster tab
  Set wsTarget = wb2.Sheets("BUYSHEET") 'this ths the name of your buysheet tab

  iLastRow = wsSource.Range("A" & Rows.Count).End(xlUp).Row
  iTarget = wsTarget.Range("A" & Rows.Count).End(xlUp).Row

  With wsSource
  For iRow = 1 To iLastRow
     Set rngSource = Intersect(.Rows(iRow).EntireRow, .Range("A:C, E:Y, Z:AF, AH:AI, AO:AO")) 'This columns you want to pull though to the buysheet tab (if one column must still be range eg, AO:AO)
     If iRow = 1 Then
        rngSource.Copy wsTarget.Range("A1")
        iTarget = iTarget + 1
     Else
       ar = Split(.Range(COL_SIZE & iRow), "|")
       For i = 0 To UBound(ar)
           rngSource.Copy wsTarget.Cells(iTarget, 1)
           wsTarget.Range("AH" & iTarget).Value = ar(i) 'AI is the column the sizes will populate in - We want this to replace the size list
           iTarget = iTarget + 1
       Next
     End If
    Next

  MsgBox "Completed"
  End With
</code>```

答:
Ok, I see what's going on now.

```<code>wsTarget.Range("AH" & iTarget).Value = ar(i)
</code>```

If that's writing 06, then Excel will be treating that as a number and make it 6.

You could "format as text" like this, before you write the value:

```<code>With wsTarget.Range("AH" & iTarget)
    .NumberFormat = "@"
    .Value = ar(i)
End With
</code>```

Or you could just prefix the value with an apostrophe / single-quote:

```<code>wsTarget.Range("AH" & iTarget).Value = "'" & ar(i)
</code>```

Either will do what you want.

Body:
I have the below code that is copy & pasting data from one sheet to another.

If you need further details:Offset the Copy Row as part of a Loop

The main problem I am having is retaining the leading zero on the sizes once split into individual rows.

    COL_SIZE in "SS21 Master Sheet"= 06|612|1218|1824
    Column "AH" in "Buysheet" is = 6
                                   612
                                   1218
                                   1824

How can i set column AH as Text so that it retains the zero (06)? I have tried a couple of options but none of them are working at the moment.

Private Sub Workbook_Open()

Sheets("BUYSHEET").Cells.Clear

  Const COL_SIZE As String = "AO" 'This is the column with all the sizes listed in the mini master

  Dim wb1 As Workbook, wsSource As Worksheet
  Set wb1 = Workbooks.Open("U:\Design\KIDS\SS21 Kids Miniscale (Master) .xlsm") ' This is the file path to your mini master.
  Dim wb2 As Workbook, wsTarget As Worksheet
  Set wb2 = ThisWorkbook
  Dim iLastRow As Long, iTarget As Long, iRow As Long
  Dim rngSource As Range, ar As Variant, i As Integer

  Set wsSource = wb1.Sheets("SS21 Master Sheet") ' This is the name of your manster tab
  Set wsTarget = wb2.Sheets("BUYSHEET") 'this ths the name of your buysheet tab

  iLastRow = wsSource.Range("A" & Rows.Count).End(xlUp).Row
  iTarget = wsTarget.Range("A" & Rows.Count).End(xlUp).Row

  With wsSource
  For iRow = 1 To iLastRow
     Set rngSource = Intersect(.Rows(iRow).EntireRow, .Range("A:C, E:Y, Z:AF, AH:AI, AO:AO")) 'This columns you want to pull though to the buysheet tab (if one column must still be range eg, AO:AO)
     If iRow = 1 Then
        rngSource.Copy wsTarget.Range("A1")
        iTarget = iTarget + 1
     Else
       ar = Split(.Range(COL_SIZE & iRow), "|")
       For i = 0 To UBound(ar)
           rngSource.Copy wsTarget.Cells(iTarget, 1)
           wsTarget.Range("AH" & iTarget).Value = ar(i) 'AI is the column the sizes will populate in - We want this to replace the size list
           iTarget = iTarget + 1
       Next
     End If
    Next

  MsgBox "Completed"
  End With

Body:
Ok, I see what's going on now.

wsTarget.Range("AH" & iTarget).Value = ar(i)

If that's writing 06, then Excel will be treating that as a number and make it 6.

You could "format as text" like this, before you write the value:

With wsTarget.Range("AH" & iTarget)
    .NumberFormat = "@"
    .Value = ar(i)
End With

Or you could just prefix the value with an apostrophe / single-quote:

wsTarget.Range("AH" & iTarget).Value = "'" & ar(i)

Either will do what you want.


问:
How to rewrite link text in reCAPTCHA form? (localization issue)
There is an issue which prevents all the reCAPTCHA widget being translated.

The "Play sound again" and "Download sound as MP3" links don't translate when using pre-defined non-english translations like "es" but obviously works fine for my own translations, e.g. for zh.

Is there any way around this?

Can I rewrite the links in JavaScript?

(I'm asking for code)

Or can I override the predefined translations for languages like German, Spanish, etc. with my own?

答: The documentation says you can override the translation by populating the custom_translations attribute of the RecaptchaOptions.


问:
Sieve of Eratosthenes algorithm in JavaScript running endless for large number
I have been trying to write Sieve of Eratosthenes algorithm in JavaScript. Basically I just literally followed the steps below:

Create a list of consecutive integers from 2 to (n-1)

Let first prime number p equal 2

Starting from p, count up in increments of p and removes each of these numbers (p and multiples of p)

Go to the next number in the list and repeat 2,3,4

Add unintentionally deleted prime numbers back to the list

and this is what I have come up with:

```<code>function eratosthenes(n){
var array = [];
var tmpArray = []; // for containing unintentionally deleted elements like 2,3,5,7,...
var maxPrimeFactor = 0;
var upperLimit = Math.sqrt(n);
var output = [];

// Eratosthenes algorithm to find all primes under n

// Make an array from 2 to (n - 1)
//used as a base array to delete composite number from
for(var i = 2; i < n; i++){
    array.push(i);
}

// Remove multiples of primes starting from 2, 3, 5,...
for(var i = array[0]; i < upperLimit; i = array[0]){
    removeMultiples:
    for(var j = i, k = i; j < n; j += i){
        var index = array.indexOf(j);
        if(index === -1)
            continue removeMultiples;
        else
            array.splice(index,1);
    }
    tmpArray.push(k);
}
array.unshift(tmpArray);
return array;
}
</code>```

It works for small numbers but not for numbers larger than one million. I used Node.js to test and the process just seems endless and no memory error shown up. I've read a solution here(also in javascript) but still cannot fully comprehend it.

Question: How to make this work for sufficiently large numbers such as one million and above?

答:
```<code>function sieveOfEratosthenes(num, fromSt = null) {
let boolArr = Array(num + 1).fill(true); // Taking num+1 for simplicity
boolArr[0] = false;
boolArr[1] = false;

for (
    let divisor = 2;
    divisor * divisor <= num;
    divisor = boolArr.indexOf(true, divisor + 1)
)
    for (let j = 2 * divisor; j <= num; j += divisor) boolArr[j] = false;

let primeArr = [];
for (
    let idx = fromSt || boolArr.indexOf(true);
    idx !== -1;
    idx = boolArr.indexOf(true, idx + 1)
)
    primeArr.push(idx);

return primeArr;
}
</code>```

Body:
I have been trying to write Sieve of Eratosthenes algorithm in JavaScript. Basically I just literally followed the steps below:

Create a list of consecutive integers from 2 to (n-1)

Let first prime number p equal 2

Starting from p, count up in increments of p and removes each of these numbers (p and multiples of p)

Go to the next number in the list and repeat 2,3,4

Add unintentionally deleted prime numbers back to the list

and this is what I have come up with:

function eratosthenes(n){
var array = [];
var tmpArray = []; // for containing unintentionally deleted elements like 2,3,5,7,...
var maxPrimeFactor = 0;
var upperLimit = Math.sqrt(n);
var output = [];

// Eratosthenes algorithm to find all primes under n

// Make an array from 2 to (n - 1)
//used as a base array to delete composite number from
for(var i = 2; i < n; i++){
    array.push(i);
}

// Remove multiples of primes starting from 2, 3, 5,...
for(var i = array[0]; i < upperLimit; i = array[0]){
    removeMultiples:
    for(var j = i, k = i; j < n; j += i){
        var index = array.indexOf(j);
        if(index === -1)
            continue removeMultiples;
        else
            array.splice(index,1);
    }
    tmpArray.push(k);
}
array.unshift(tmpArray);
return array;
}

It works for small numbers but not for numbers larger than one million. I used Node.js to test and the process just seems endless and no memory error shown up. I've read a solution here(also in javascript) but still cannot fully comprehend it.

Question: How to make this work for sufficiently large numbers such as one million and above?


问:
Problem in angular when I want recover informations of array
I have a problem with my angular code.
This is the code in my animal.component.ts :

```<code>import { Component, OnInit } from '@angular/core';
import { AnimalService } from "./animal.service";
import { Animal } from "./animal";

@Component({
  selector: 'app-animal',
  templateUrl: './animal.component.html',
  styleUrls: ['./animal.component.css']
})
export class AnimalComponent implements OnInit {

  private animaux:Array<Animal>;
  private especeAnimalPresente:Array<string>;
  constructor(private animalService: AnimalService) { }

  ngOnInit() {
    this.recupAllAnimals();
    this.recupEspecePresent();
  }

  recupAllAnimals(){
    this.animalService.getAllAnimaux().subscribe(
      data => {console.log(this.animaux), this.animaux = data, console.log(this.animaux)}
    )
  }

  recupEspecePresent(){
    for (let animal of this.animaux) {
    }
  }
}
</code>```

But I have this error in my console :

```<code>ERROR TypeError: "this.animaux is undefined"
    recupEspecePresent animal.component.ts:28
    ngOnInit animal.component.ts:18
    Angular 5
    View_AnimalComponent_Host_0 (index):1
    Angular 26
    RxJS 5
    Angular 11
</code>```

I don't understand this problem especially that my array animaux contains many animals. And I display this array in my html code.
This is ma web page :

答:
Data for this.animaux are fetched asynchronously and there is no guarantee that your recupEspecePresent is called after the data are fetched. You should run that function after the fetching is done:

ngOnInit(): void {
  this.recupAllAnimals();
}

recupAllAnimals(): void {
  this.animalService.getAllAnimaux().subscribe(data => {
    this.animaux = data;
    this.recupEspecePrsent();
  })
}

recupEspecePresent(): void {
  for (let animal of this.animaux) {
    // do something
  }
}
```

Body:
I have a problem with my angular code.
This is the code in my animal.component.ts :

import { Component, OnInit } from '@angular/core';
import { AnimalService } from "./animal.service";
import { Animal } from "./animal";

@Component({
  selector: 'app-animal',
  templateUrl: './animal.component.html',
  styleUrls: ['./animal.component.css']
})
export class AnimalComponent implements OnInit {

  private animaux:Array<Animal>;
  private especeAnimalPresente:Array<string>;
  constructor(private animalService: AnimalService) { }

  ngOnInit() {
    this.recupAllAnimals();
    this.recupEspecePresent();
  }

  recupAllAnimals(){
    this.animalService.getAllAnimaux().subscribe(
      data => {console.log(this.animaux), this.animaux = data, console.log(this.animaux)}
    )
  }

  recupEspecePresent(){
    for (let animal of this.animaux) {
    }
  }
}

But I have this error in my console :

ERROR TypeError: "this.animaux is undefined"
    recupEspecePresent animal.component.ts:28
    ngOnInit animal.component.ts:18
    Angular 5
    View_AnimalComponent_Host_0 (index):1
    Angular 26
    RxJS 5
    Angular 11

I don't understand this problem especially that my array animaux contains many animals. And I display this array in my html code.
This is ma web page :


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
There seem to be two themes coming from the answers:

You need to pick a project that might involve more than 1K LOC in order to get the true experience of the project.

You need to also pair up with an experienced C++ developer, who can help you think through problems and avoid pitfalls associated with the language.

You can get around both of these by swing by sourceforge.net and signing up to help with an existing C++ project. As long as you don't mind your code being open source, you should be able to find an existing project to learn from plus experienced developers who can help by reviewing your code and offering guidance.

OwnerDisplayName: climatewarrior

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5


问:
Eclipse regex for $_GET['whatever']
I would like to find replace this in eclipse:

find:
$_GET['whatever']

replace:
$this->input->get('whatever')

答:
Try this.  You have to make sure you have regular expressions turned on in the Find/Replace window.

```<code>Find: \$_GET\[('.*')\]
Replace: \$this->input->get($1)
</code>```

It's not clear to me what your 'whatever' needs to be.  If it's only word characters you can replace the .* with \w.  You have to precede the dollar sign and the left and right brackets with a backslash (escape them) because they are special characters in the regex and if not escaped would be treated differently by the regex parser.

Good luck.

Title: Eclipse regex for $_GET['whatever']

Body:
Try this.  You have to make sure you have regular expressions turned on in the Find/Replace window.

Find: \$_GET\[('.*')\]
Replace: \$this->input->get($1)

It's not clear to me what your 'whatever' needs to be.  If it's only word characters you can replace the .* with \w.  You have to precede the dollar sign and the left and right brackets with a backslash (escape them) because they are special characters in the regex and if not escaped would be treated differently by the regex parser.

Good luck.


问:
UIImagePickerController delegate not called Swift 3
On the surface I thought that this had to be a delegate issue, but after asking for the delegate the right one was returned.

I created an ImagePicker class to handle all the UIImagePickerController stuff. Every thing works until the delegate methods need to be called. After I pick a photo, the imagePicker dismisses, but the didFinishPickingMediaWithInfo method never gets called. Please help! Thanks :)

```<code>func selectPhoto() {
    imagePicker.delegate = self //Delegate gets set here

    let photoAsk = UIAlertController.init( //Ask user if they want to take picture or choose one
        title: "Edit Profile Picture",
        message: nil,
        preferredStyle: .alert)
    let cameraAction = UIAlertAction.init(
        title: "Take Photo",
        style: .default) { (UIAlertAction) in
            if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
                self.imagePicker.sourceType = .camera
                UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
            } else {
                print("Cannot access camera in simulator.")
                return
            }
    }
    let photoLibraryAction = UIAlertAction.init(
        title: "Photo Library",
        style: .default) { (UIAlertAction) in
            self.imagePicker.sourceType = .photoLibrary
            UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
            print("UIImagePickerDelegate: \(self.imagePicker.delegate.debugDescription)") // <--THIS PRINTS OUT "AppName.ImagePicker: 0x145d7bdf0>", and the class name is ImagePicker
    }
    let cancelAction = UIAlertAction.init(
        title: "Cancel",
        style: .cancel) { (UIAlertAction) in return }

    photoAsk.addAction(cameraAction)
    photoAsk.addAction(photoLibraryAction)
    photoAsk.addAction(cancelAction)

    imagePicker.mediaTypes = [kUTTypeImage as String]

    UIApplication.topViewController()?.present(photoAsk, animated: true, completion: nil)
    }
}
</code>```

This never gets called:

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    print("Image picked.") //NEVER PRINTS
}
</code>```

答:
swift 4.2

Add Delegate method according ViewController

UIImagePickerControllerDelegate,UINavigationControllerDelegate

```<code>//IBOutlet
@IBOutlet weak var ImagePhoto: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
}

//Button Action Take Photo
@IBAction func btnPhotoTap(_ sender: Any) {

           let imagePicker = UIImagePickerController()
           imagePicker.delegate = self
           imagePicker.sourceType = .photoLibrary // Or .camera as you require
           imagePicker.allowsEditing = true
           self.present(imagePicker, animated: true, completion: nil)
}

//MARK:-imagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
           let image1 =  info[UIImagePickerController.InfoKey.editedImage] as? UIImage
           self.ImagePhoto.image = image1
           self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

           print("Cancel")
           self.dismiss(animated: true, completion: nil)
}
</code>```

Body:
On the surface I thought that this had to be a delegate issue, but after asking for the delegate the right one was returned.

I created an ImagePicker class to handle all the UIImagePickerController stuff. Every thing works until the delegate methods need to be called. After I pick a photo, the imagePicker dismisses, but the didFinishPickingMediaWithInfo method never gets called. Please help! Thanks :)

func selectPhoto() {
    imagePicker.delegate = self //Delegate gets set here

    let photoAsk = UIAlertController.init( //Ask user if they want to take picture or choose one
        title: "Edit Profile Picture",
        message: nil,
        preferredStyle: .alert)
    let cameraAction = UIAlertAction.init(
        title: "Take Photo",
        style: .default) { (UIAlertAction) in
            if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
                self.imagePicker.sourceType = .camera
                UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
            } else {
                print("Cannot access camera in simulator.")
                return
            }
    }
    let photoLibraryAction = UIAlertAction.init(
        title: "Photo Library",
        style: .default) { (UIAlertAction) in
            self.imagePicker.sourceType = .photoLibrary
            UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
            print("UIImagePickerDelegate: \(self.imagePicker.delegate.debugDescription)") // <--THIS PRINTS OUT "AppName.ImagePicker: 0x145d7bdf0>", and the class name is ImagePicker
    }
    let cancelAction = UIAlertAction.init(
        title: "Cancel",
        style: .cancel) { (UIAlertAction) in return }

    photoAsk.addAction(cameraAction)
    photoAsk.addAction(photoLibraryAction)
    photoAsk.addAction(cancelAction)

    imagePicker.mediaTypes = [kUTTypeImage as String]

    UIApplication.topViewController()?.present(photoAsk, animated: true, completion: nil)
    }
}

This never gets called:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    print("Image picked.") //NEVER PRINTS
}

Body:
swift 4.2

Add Delegate method according ViewController

UIImagePickerControllerDelegate,UINavigationControllerDelegate

//IBOutlet
@IBOutlet weak var ImagePhoto: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
}

//Button Action Take Photo
@IBAction func btnPhotoTap(_ sender: Any) {

           let imagePicker = UIImagePickerController()
           imagePicker.delegate = self
           imagePicker.sourceType = .photoLibrary // Or .camera as you require
           imagePicker.allowsEditing = true
           self.present(imagePicker, animated: true, completion: nil)
}

//MARK:-imagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
           let image1 =  info[UIImagePickerController.InfoKey.editedImage] as? UIImage
           self.ImagePhoto.image = image1
           self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

           print("Cancel")
           self.dismiss(animated: true, completion: nil)
}


问:
How would I vectorize a function in pandas that returns a list?
I've been reading about how to optimize pandas code for speed, and I'm trying to refactor my code, changing from iterrows() to vectorization. Here is an example of the old code and its result:

Old Code

```<code>import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
for index, row in df.iterrows():
    df.at[index,"repeatedAsList"] = repeatAsList(row['values'])
df
</code>```

Old Result

```<code>+--------+----------------+
| values | repeatedAsList |
+--------+----------------+
|      1 | [1, 1]         |
|      2 | [2, 2]         |
|      3 | [3, 3]         |
+--------+----------------+
</code>```

New Code

```<code>import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
df["repeatedAsList"] = repeatAsList(df["values"])
</code>```

New Result

```<code>ValueError: Length of values does not match length of index
</code>```

I'd like to understand why the new code above fails, and if it's possible to run a different way and achieve speed improvements from the old code. I feel like I'm missing a key point of vectorization, and it would be nice to learn why the values have to be scalar.

答:
If i understand your problem correctly the below code should be able to complete your requested task easily :

```<code>df['repeated_column'] = [[item, item] for item in df['values'].to_list()]
</code>```

Please check and let me know.

Body:
I've been reading about how to optimize pandas code for speed, and I'm trying to refactor my code, changing from iterrows() to vectorization. Here is an example of the old code and its result:

Old Code

import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
for index, row in df.iterrows():
    df.at[index,"repeatedAsList"] = repeatAsList(row['values'])
df

Old Result

+--------+----------------+
| values | repeatedAsList |
+--------+----------------+
|      1 | [1, 1]         |
|      2 | [2, 2]         |
|      3 | [3, 3]         |
+--------+----------------+

New Code

import pandas as pd
def repeatAsList(value):
    return([value, value])
df = pd.DataFrame({"values": [1,2,3], "repeatedAsList":None})
df["repeatedAsList"] = repeatAsList(df["values"])

New Result

ValueError: Length of values does not match length of index

I'd like to understand why the new code above fails, and if it's possible to run a different way and achieve speed improvements from the old code. I feel like I'm missing a key point of vectorization, and it would be nice to learn why the values have to be scalar.

Body:
If i understand your problem correctly the below code should be able to complete your requested task easily :

df['repeated_column'] = [[item, item] for item in df['values'].to_list()]

Please check and let me know.


问:
How can i make first letter of all words in a string uppercase recursively?
I wonder how can i make this. I don't want any iteration or isalpha() and toupper() functions. We want to use our own code to read input. We assume that user enters all characters lowercase. This is what i've tried so far:

```<code>define MAX_LENGTH 100

int read_line(char str[],int);
void capitalize(char[]);

int main (void){
    char A[MAX_LENGTH];
printf("Enter a text \n");
read_line(A, MAX_LENGTH);

capitalize(A);
puts(A);

}

int read_line(char str[],int n){
    int ch,i=0;

    while ((ch = getchar()) != '\n'){
        if(i<MAX_LENGTH)
            str[i++] = ch;
    }
    str[i] = '\0';
    return i;
}

void capitalize(char str[]){
 int x = strlen(str);
 static int i = 0;
    if(str[i]=='\0')
    return;
    if(str[i-1]==' '|| i == 0)
      str[i] -= 32;
      i++;
      return capitalize(&str[i]);
 }
</code>```

Output is like this:

Enter a text:

asdf sdf df

Asdf sdf df

What is wrong with my code?

答:
Should do the job:

```<code>void capitalize(char *s)
{
    while(1) {
        while (*s==' ') s++;                // skip spaces
        if (!*s) return;                    // check for end
        if ('a'<=*s && *s<='z') *s -= 32;   // capitalize if needed
        while (*s && *s!=' ') s++;          // advance
    }                                       // loop
}
</code>```

(I call this "Stupid Character Processing")

Body:
I wonder how can i make this. I don't want any iteration or isalpha() and toupper() functions. We want to use our own code to read input. We assume that user enters all characters lowercase. This is what i've tried so far:

define MAX_LENGTH 100

int read_line(char str[],int);
void capitalize(char[]);

int main (void){
    char A[MAX_LENGTH];
printf("Enter a text \n");
read_line(A, MAX_LENGTH);

capitalize(A);
puts(A);

}

int read_line(char str[],int n){
    int ch,i=0;

    while ((ch = getchar()) != '\n'){
        if(i<MAX_LENGTH)
            str[i++] = ch;
    }
    str[i] = '\0';
    return i;
}

void capitalize(char str[]){
 int x = strlen(str);
 static int i = 0;
    if(str[i]=='\0')
    return;
    if(str[i-1]==' '|| i == 0)
      str[i] -= 32;
      i++;
      return capitalize(&str[i]);
 }

Output is like this:

Enter a text:

asdf sdf df

Asdf sdf df

What is wrong with my code?

Body:
Should do the job:

void capitalize(char *s)
{
    while(1) {
        while (*s==' ') s++;                // skip spaces
        if (!*s) return;                    // check for end
        if ('a'<=*s && *s<='z') *s -= 32;   // capitalize if needed
        while (*s && *s!=' ') s++;          // advance
    }                                       // loop
}

(I call this "Stupid Character Processing")


问:
Positioning problem of a child element in css on Firefox and internet explorer
I'm trying to properly position the toggle eye of the password field using CSS.The problem is the positioning works well in google chrome but it's not working in firefox and ie.I tried to figure out the solution but being a beginner in web development I didn't get a solution. Please help me to figure out the solution.

My HTML part

```<code>        <div id="password">
            <label for="pwd">Password</label>
            <div>
                <input type="password" id="pwd" name="pass_word" autocomplete="off" maxlength="12" value="<?php echo $pwd; ?>">
                <span class="icon"><i id="show-pwd" class="far fa-eye hide"></i></span>
                <span class="icon"><i id="hide-pwd" class="far fa-eye-slash"></i></span>
            </div>
            <div id="perr" class="err"><?php echo $pwderr; ?></div>
        </div>

        <div id="confirm-password">
            <label for="cnfpwd">Confirm Password</label>
            <div>
                <input type="password" id="cnfpwd" name="cnf_pwd" autocomplete="off" maxlength="12" value="<?php echo $cpwd; ?>">
                <span class="icon"><i id="show-cnfpwd" class="far fa-eye hide"></i></span>
                <span class="icon"><i id="hide-cnfpwd" class="far fa-eye-slash"></i></span>
            </div>
            <div id="cperr" class="err"><?php echo $cpwderr; ?></div>
        </div>
</code>```

My CSS part

```<code>.confirm-password{
    position: relative;
}

.icon{
    position: absolute;
    transform: translate3d(-140%,40%,0);
    color: #555;
}
</code>```

The first image shows how it looks in chrome and the second shows how it looks in firefox.

答: Your div has an ID of confirm-password but your CSS rule is for a class: .confirm-password. Change . to # and your div will now have position: relative assigned to it.

Body:
I'm trying to properly position the toggle eye of the password field using CSS.The problem is the positioning works well in google chrome but it's not working in firefox and ie.I tried to figure out the solution but being a beginner in web development I didn't get a solution. Please help me to figure out the solution.

My HTML part

            Password

                <input type="password" id="pwd" name="pass_word" autocomplete="off" maxlength="12" value="<?php echo $pwd; ?>">

<?php echo $pwderr; ?>

            Confirm Password

                <input type="password" id="cnfpwd" name="cnf_pwd" autocomplete="off" maxlength="12" value="<?php echo $cpwd; ?>">

<?php echo $cpwderr; ?>

My CSS part

.confirm-password{
    position: relative;
}

.icon{
    position: absolute;
    transform: translate3d(-140%,40%,0);
    color: #555;
}

The first image shows how it looks in chrome and the second shows how it looks in firefox.


问:
Why does string concatenation create extra parameters using Access and PYODBC?

I created this procedure that I call with the cursor.execute method. The problem that I'm having is that PYODBC sees extra parameters than what I've given.
In this example query, the "-" and "-" are being read as extra parameters by PYODBC. Does anyone know why this is the case? This is happening any time I do any string concatenation in Access.

```<code>def GetAccessResults(self):

    with pyodbc.connect(SQL.DBPath) as con:
        cursor = con.cursor()

        if self.parameters == None:
            cursor.execute('{{Call {}}}'.format(self.storedProc))
        else:
            callString = self.__CreateStoredProcString()
            cursor.execute(callString, self.parameters)

        returnValue = cursor.fetchall()

    return returnValue

def __CreateStoredProcString(self):

    questionMarks = ('?,' * len(self.parameters))[:-1]

    return '{{Call {} ({})}}'.format(self.storedProc, questionMarks)
</code>```

答:
Try using ampersands:

```<code>Select "*-" & Service_Abbreviation & "-*"
</code>```

Also, Like expects a string wrapped in quotes, and your subquery doesn't return that. So perhaps:

```<code>Select "'*-" & Service_Abbreviation & "-*'"
</code>```

Body:
I created this procedure that I call with the cursor.execute method. The problem that I'm having is that PYODBC sees extra parameters than what I've given.
In this example query, the "-" and "-" are being read as extra parameters by PYODBC. Does anyone know why this is the case? This is happening any time I do any string concatenation in Access.

def GetAccessResults(self):

    with pyodbc.connect(SQL.DBPath) as con:
        cursor = con.cursor()

        if self.parameters == None:
            cursor.execute('{{Call {}}}'.format(self.storedProc))
        else:
            callString = self.__CreateStoredProcString()
            cursor.execute(callString, self.parameters)

        returnValue = cursor.fetchall()

    return returnValue

def __CreateStoredProcString(self):

    questionMarks = ('?,' * len(self.parameters))[:-1]

    return '{{Call {} ({})}}'.format(self.storedProc, questionMarks)

Body:
Try using ampersands:

Select "*-" & Service_Abbreviation & "-*"

Also, Like expects a string wrapped in quotes, and your subquery doesn't return that. So perhaps:

Select "'*-" & Service_Abbreviation & "-*'"


问:
Get max value in MySQL?
I've following values in my database:

```<code>Column1
-----
 10
 20
 30
 05
 12
 21
 10
 40
</code>```

As you can see, the value is increasing in the first three rows. It starts again in the fourth row with some value like 5. and then starts again in the 7th row with 10, for example. That is, it lowers and then increases again to some extent. The value starts with different numbers. I want to get the highest of each. i.e. I want to get rows with value 30,21, and 40.

Note that I've only the sorted list, It can be done with some variable in programming language but how to do this in mysql with some query?

答:
I would insert all the values into another table which will have only 2 columns (id AUTOINCREMENT and Val as your values).

And then I would use this select:

```<code>SELECT
Val
FROM (
  SELECT
      T1.id, T1.Val, (Select Val from MyTable T2 where T2.id = T1.id + 1) NextVal
  FROM
      MyTable T1
)
WHERE
Val > NextVal
</code>```

Title: Get max value in MySQL?

Body:
I've following values in my database:

Column1
-----
 10
 20
 30
 05
 12
 21
 10
 40

As you can see, the value is increasing in the first three rows. It starts again in the fourth row with some value like 5. and then starts again in the 7th row with 10, for example. That is, it lowers and then increases again to some extent. The value starts with different numbers. I want to get the highest of each. i.e. I want to get rows with value 30,21, and 40.

Note that I've only the sorted list, It can be done with some variable in programming language but how to do this in mysql with some query?

Body:
I would insert all the values into another table which will have only 2 columns (id AUTOINCREMENT and Val as your values).

And then I would use this select:

SELECT
Val
FROM (
  SELECT
      T1.id, T1.Val, (Select Val from MyTable T2 where T2.id = T1.id + 1) NextVal
  FROM
      MyTable T1
)
WHERE
Val > NextVal


问:
Axios Post Request against express server succeeds with images, fails with .mp4 files
I have an axios post request to my express server that looks like this:

```<code>const formData = new FormData();
formData.append("file", this.state.file[0]);
const transport = axios.create({ withCredentials: true });

transport
      .post(DomainInfo.baseUrl + path, body, {
        headers: { "Content-Type": "multipart/form-data" },
        timeout: 0
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(error => {
        handleError(reject, error);
      });
</code>```

When I post an image it succeeds, but when I try to post a video (.mp4) I get the error:
"Access to XMLHttpRequest at 'https://staging.clubwealth.com/university/organization/contentFolder' from origin 'https://127.0.0.1:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
The amount of time it takes for this error to be thrown corresponds directly to the size of the .mp4 file.

My Express Server

```<code>var app = express();
var corsBaseOptions = {
  origin: 'https://127.0.0.1:3000',
  optionsSuccessStatus: 200,
  credentials: true
}
app.use(cors(corsBaseOptions));
app.use(session({...  }
}))
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
var myArgs = process.argv.slice(2);
var port = myArgs[0];
var server = http.createServer(app).listen(port, function(){
  console.log("listening on port ", port);
})
server.setTimeout(50000000000);
module.exports = app;
</code>```

I'm pretty dang stumped. It would be amazing if you guys could help point me in the right direction here.
THanks!
I've tried stripping my post route down to just responding with res.status(200).send('ok') and still get the same result, so I figure it must be some kind of axios problem or express config problem. Don't hesitate to tell me i'm flat out wrong though! XD

答:
I found my error. I neglected the most important detail here, which my express server is set with nginx as a reverse proxy.

Nginx has a default maximum request size of 1M, which is why the videos weren't working.
When the size is too large Nginx responds with  413, which browsers do not properly display, which is perhaps why I was getting a CORS error.

If anyone runs into a similar problem, on ubuntu I went to etc/nginx/ngninx.conf and added the line client_max_body_size 20M; under http. If anyone else has additional insight as to why I was getting a CORS error with 403 file to large that would be great!

Thanks!

Body:
I have an axios post request to my express server that looks like this:

const formData = new FormData();
formData.append("file", this.state.file[0]);
const transport = axios.create({ withCredentials: true });

transport
      .post(DomainInfo.baseUrl + path, body, {
        headers: { "Content-Type": "multipart/form-data" },
        timeout: 0
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(error => {
        handleError(reject, error);
      });

When I post an image it succeeds, but when I try to post a video (.mp4) I get the error:
"Access to XMLHttpRequest at 'https://staging.clubwealth.com/university/organization/contentFolder' from origin 'https://127.0.0.1:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
The amount of time it takes for this error to be thrown corresponds directly to the size of the .mp4 file.

My Express Server

var app = express();
var corsBaseOptions = {
  origin: 'https://127.0.0.1:3000',
  optionsSuccessStatus: 200,
  credentials: true
}
app.use(cors(corsBaseOptions));
app.use(session({...  }
}))
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
var myArgs = process.argv.slice(2);
var port = myArgs[0];
var server = http.createServer(app).listen(port, function(){
  console.log("listening on port ", port);
})
server.setTimeout(50000000000);
module.exports = app;

I'm pretty dang stumped. It would be amazing if you guys could help point me in the right direction here.
THanks!
I've tried stripping my post route down to just responding with res.status(200).send('ok') and still get the same result, so I figure it must be some kind of axios problem or express config problem. Don't hesitate to tell me i'm flat out wrong though! XD


问:
django.db.utils.IntegrityError: column "venue_city" contains null values
I have read a lot of other posts here on stackoverflow and google but I could not find a solution.

It all started when I changed the model from a CharField to a ForeignKey.
The error I recieve is:

```<code>Operations to perform:
  Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages
  Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying venues.0016_auto_20160514_2141...Traceback (most recent call last):
  File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.IntegrityError: column "venue_city" contains null values
</code>```

My model is as follows:

```<code>class Venue(models.Model):
    venue_city = models.ForeignKey(City, null=True,)
    venue_country=models.ForeignKey(Country, null=True)
</code>```

venue_country did not exist before so that migration happened successfully. But venue_city was a CharField.

I made some changes to my migration file so that it would execute the sql as follows:

```<code># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('venues', '0011_venue_map_activation'),
    ]

    migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING  venue_city::integer '''),

    migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''),

    migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES  cities_light (id) DEFERRABLE INITIALLY DEFERRED'''),
</code>```

Thanks in advance!

UPDATE: my new migration file:

```<code># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('cities_light', '0006_compensate_for_0003_bytestring_bug'),
        ('venues', '0024_remove_venue_venue_city'),
    ]

    operations = [
        migrations.AddField(
            model_name='venue',
            name='venue_city',
            field=models.ForeignKey(null=True, to='cities_light.City'),
        ),
    ]
</code>```

答:
I solved it by below:

First delete last migration that face problem

Then add like venue_city = models.CharField(blank=True, null=True)

Finally use makemigrations and migrate command

Body:
I have read a lot of other posts here on stackoverflow and google but I could not find a solution.

It all started when I changed the model from a CharField to a ForeignKey.
The error I recieve is:

Operations to perform:
  Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages
  Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying venues.0016_auto_20160514_2141...Traceback (most recent call last):
  File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.IntegrityError: column "venue_city" contains null values

My model is as follows:

class Venue(models.Model):
    venue_city = models.ForeignKey(City, null=True,)
    venue_country=models.ForeignKey(Country, null=True)

venue_country did not exist before so that migration happened successfully. But venue_city was a CharField.

I made some changes to my migration file so that it would execute the sql as follows:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('venues', '0011_venue_map_activation'),
    ]

    migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING  venue_city::integer '''),

    migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''),

    migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES  cities_light (id) DEFERRABLE INITIALLY DEFERRED'''),

Thanks in advance!

UPDATE: my new migration file:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('cities_light', '0006_compensate_for_0003_bytestring_bug'),
        ('venues', '0024_remove_venue_venue_city'),
    ]

    operations = [
        migrations.AddField(
            model_name='venue',
            name='venue_city',
            field=models.ForeignKey(null=True, to='cities_light.City'),
        ),
    ]


问:
gRPC unable to create connection to server (Go) from client (Python)
I have this Python code that is supposed to use a certificate and connect to a server via the server's IP address (no FQDN available) but I get an error every time I try it:

```<code>ssl_transport_security.cc:222]                 LOOP - TLS client process_change_ciph  - !!!!!!
ssl_transport_security.cc:222]                 LOOP - TLS client read_server_finishe  - !!!!!!
ssl_transport_security.cc:222]                 LOOP - TLS client finish_client_hands  - !!!!!!
ssl_transport_security.cc:222]                 LOOP -                TLS client done  - !!!!!!
ssl_transport_security.cc:222]       HANDSHAKE DONE -                TLS client done  - !!!!!!
security_handshaker.cc:184] Security handshake failed: {"created":"@1582052112.923538253","description":"Peer name 172.18.0.14 is not in peer certificate","file":"src/core/lib/security/security_connector/ssl/ssl_security_connector.cc","file_line":55}
subchannel.cc:1003]         Connect failed: {"created":"@1582052112.923538253","description":"Peer name 172.18.0.14 is not in peer certificate","file":"src/core/lib/security/security_connector/ssl/ssl_security_connector.cc","file_line":55}
subchannel.cc:940]          Subchannel 0x55ad70542020: Retry immediately
subchannel.cc:967]          Failed to connect to channel, retrying
</code>```

From what I understand this could be due to me connecting to an ip address and not a FQDN but these are servers and I only have access to IP addresses. Any idea how to overcome this?

Python code used:

```<code>def get_secure_channel(host, port):
    if os.environ.get('https_proxy'):
        del os.environ['https_proxy']
    if os.environ.get('http_proxy'):
        del os.environ['http_proxy']

    with open(os.path.join(settings.DJANGO_ROOT, '../grpc_proto/cert/server.crt'), 'rb') as f:
        cert = f.read()

    credentials = grpc.ssl_channel_credentials(root_certificates=cert)
    return grpc.secure_channel('{}:{}'.format(host, port), credentials)

def reset_client(channel, ip_address):
    stub = dnsadblock_pb2_grpc.DnsadblockServiceStub(channel)
    return stub.ResetClient(dnsadblock_pb2.ResetClientRequest(ipAddress=ip_address))

channel = get_secure_channel(c.server.hostname, settings.GRPC_PORT)
rpc.reset_client(channel, c.ip_address)
</code>```

答:
https://support.dnsimple.com/articles/what-is-common-name/

In this case, the endpoint you are connecting are not matching the description of peer's certificate. Hence, the connection was rejected. You could either try to use one of the CN in your certificate to connect to the server. Or adding the endpoint to your certificate.

Body:
I have this Python code that is supposed to use a certificate and connect to a server via the server's IP address (no FQDN available) but I get an error every time I try it:

ssl_transport_security.cc:222]                 LOOP - TLS client process_change_ciph  - !!!!!!
ssl_transport_security.cc:222]                 LOOP - TLS client read_server_finishe  - !!!!!!
ssl_transport_security.cc:222]                 LOOP - TLS client finish_client_hands  - !!!!!!
ssl_transport_security.cc:222]                 LOOP -                TLS client done  - !!!!!!
ssl_transport_security.cc:222]       HANDSHAKE DONE -                TLS client done  - !!!!!!
security_handshaker.cc:184] Security handshake failed: {"created":"@1582052112.923538253","description":"Peer name 172.18.0.14 is not in peer certificate","file":"src/core/lib/security/security_connector/ssl/ssl_security_connector.cc","file_line":55}
subchannel.cc:1003]         Connect failed: {"created":"@1582052112.923538253","description":"Peer name 172.18.0.14 is not in peer certificate","file":"src/core/lib/security/security_connector/ssl/ssl_security_connector.cc","file_line":55}
subchannel.cc:940]          Subchannel 0x55ad70542020: Retry immediately
subchannel.cc:967]          Failed to connect to channel, retrying

From what I understand this could be due to me connecting to an ip address and not a FQDN but these are servers and I only have access to IP addresses. Any idea how to overcome this?

Python code used:

def get_secure_channel(host, port):
    if os.environ.get('https_proxy'):
        del os.environ['https_proxy']
    if os.environ.get('http_proxy'):
        del os.environ['http_proxy']

    with open(os.path.join(settings.DJANGO_ROOT, '../grpc_proto/cert/server.crt'), 'rb') as f:
        cert = f.read()

    credentials = grpc.ssl_channel_credentials(root_certificates=cert)
    return grpc.secure_channel('{}:{}'.format(host, port), credentials)

def reset_client(channel, ip_address):
    stub = dnsadblock_pb2_grpc.DnsadblockServiceStub(channel)
    return stub.ResetClient(dnsadblock_pb2.ResetClientRequest(ipAddress=ip_address))

channel = get_secure_channel(c.server.hostname, settings.GRPC_PORT)
rpc.reset_client(channel, c.ip_address)


问:
JavaScript Debugging
I am using Visual Studio 2010 Express Developer edition. Developing a Website. I'm using JavaScript in my .aspx pages. How to put breakpoints in Javascript.

Any help is highly appreciated.

Thank You

答: Using FireBug & Internet Explorer Debuging tool let you debug and put breakpoint on your javascript files

Title: JavaScript Debugging


问:
Find out which rows are duplicates when inserting into a DB table?
I have the following scenario:

Database table, let's call it ZDBX with primary keys:

```<code>MATNR, LIFNR, ZART
</code>```

In a report i have internal table lt_table TYPE TABLE OF ZDBX

```<code>DELETE ADJACENT DUPLICATES FROM lt_table
   COMPARING matnr lifnr zart fact_code.

DELETE FROM ZDBX.
INSERT ZDBX FROM TABLE lt_table.
</code>```

The INSERT statement will lead to a short dump because there are rows in the internal table with identical primary keys, but different fact_code.

Now, I know that the obvious solution is to only compare primary keys in the DELETE ADJACENT DUPLICATES statement, but this does not work in my case, because the user wants to decide which fact_code will be deleted.

For now, my solution is to export the local table (right before INSERT) into a excel and find the duplicates and ask the user which fact_code he wants.

Can I find out (trough a system variable or in ST22) at which line the INSERT crashed?
(So I dont have to do all the excel work)

My ideal solution would be to put the INSERT into a TRY-CATCH, find the duplicate row, and write a message into the Job-Log with the duplicate data.

Is it possible ?

(Also, setting the column fact_code as primary key is not a solution that the user agrees with)

答:
There's no particular solution to know which lines are duplicate, you have to code the algorithm from scratch.

Possible solutions:

Worst one: INSERT one line at a time and test SY-SUBRC, it will be 0 if the insertion is successful, another value is usually a duplicate line. Rollback the insertions if there is any duplicate.

```<code>LOOP AT lt_table INTO DATA(ls_table).
  INSERT zdbx FROM ls_table. " one line at a time
  IF sy-subrc <> 0.
    APPEND ls_table TO lt_error.
  ENDIF.
ENDLOOP.
IF lt_error IS NOT INITIAL.
  ROLLBACK WORK.
ELSE.
  COMMIT WORK.
ENDIF.
</code>```

Best one:

Read the current lines of the database table into the internal table lt_duplicates; you may read only the important lines by using mkysoft proposal: FOR ALL ENTRIES; be careful, it's important to make sure that lt_table is not empty otherwise all lines of the table are read.

Check which lines of your internal table lt_table exist in lt_duplicates. They are all duplicates.

For all those lines of lt_table which don't exist in lt_duplicates, you must make sure that there's not another line of lt_table with the same primary key. You can do it by first sorting the internal table by the primary key, read the next line(s) which have the same primary key fields, all of these lines are duplicates.

Body:
I have the following scenario:

Database table, let's call it ZDBX with primary keys:

MATNR, LIFNR, ZART

In a report i have internal table lt_table TYPE TABLE OF ZDBX

DELETE ADJACENT DUPLICATES FROM lt_table
   COMPARING matnr lifnr zart fact_code.

DELETE FROM ZDBX.
INSERT ZDBX FROM TABLE lt_table.

The INSERT statement will lead to a short dump because there are rows in the internal table with identical primary keys, but different fact_code.

Now, I know that the obvious solution is to only compare primary keys in the DELETE ADJACENT DUPLICATES statement, but this does not work in my case, because the user wants to decide which fact_code will be deleted.

For now, my solution is to export the local table (right before INSERT) into a excel and find the duplicates and ask the user which fact_code he wants.

Can I find out (trough a system variable or in ST22) at which line the INSERT crashed?
(So I dont have to do all the excel work)

My ideal solution would be to put the INSERT into a TRY-CATCH, find the duplicate row, and write a message into the Job-Log with the duplicate data.

Is it possible ?

(Also, setting the column fact_code as primary key is not a solution that the user agrees with)

Body:
There's no particular solution to know which lines are duplicate, you have to code the algorithm from scratch.

Possible solutions:

Worst one: INSERT one line at a time and test SY-SUBRC, it will be 0 if the insertion is successful, another value is usually a duplicate line. Rollback the insertions if there is any duplicate.

LOOP AT lt_table INTO DATA(ls_table).
  INSERT zdbx FROM ls_table. " one line at a time
  IF sy-subrc <> 0.
    APPEND ls_table TO lt_error.
  ENDIF.
ENDLOOP.
IF lt_error IS NOT INITIAL.
  ROLLBACK WORK.
ELSE.
  COMMIT WORK.
ENDIF.

Best one:

Read the current lines of the database table into the internal table lt_duplicates; you may read only the important lines by using mkysoft proposal: FOR ALL ENTRIES; be careful, it's important to make sure that lt_table is not empty otherwise all lines of the table are read.

Check which lines of your internal table lt_table exist in lt_duplicates. They are all duplicates.

For all those lines of lt_table which don't exist in lt_duplicates, you must make sure that there's not another line of lt_table with the same primary key. You can do it by first sorting the internal table by the primary key, read the next line(s) which have the same primary key fields, all of these lines are duplicates.


问:
Grep a "text" and print all the line before and after the text. each log session is separated by 2 blank lines
```<code>1
1
1
1
  Text
11
1
1
1
</code>```

The text above can be anywhere therefore grep -C wont help.
I have tried that using AWK but i want to do it using grep

```<code>zgrep -C25 "Text" engine.*.log.gz
</code>```

doesn't work as text may appear anywhere

I know the awk option but it doesn't work on .gz file i have to convert it its a lengthy  process

  awk -v RS= '/Text/' engine.*.log.gz

答:
Just do it the trivial, obvious, robust, portable way:

```<code>zcat engine.*.log.gz | awk -v RS= '/Text/{print; exit}'
</code>```

That should also be pretty efficient since the SIGPIPE that zcat gets when awk exits on finding the first Text should terminate the zcat.

Or if Text can appear multiple times in the input and you want all associated records output:

```<code>zcat engine.*.log.gz | awk -v RS= -v ORS='\n\n' '/Text/'
</code>```

Body:
1
1
1
1
  Text
11
1
1
1

The text above can be anywhere therefore grep -C wont help.
I have tried that using AWK but i want to do it using grep

zgrep -C25 "Text" engine.*.log.gz

doesn't work as text may appear anywhere

I know the awk option but it doesn't work on .gz file i have to convert it its a lengthy  process

  awk -v RS= '/Text/' engine.*.log.gz

Body:
Just do it the trivial, obvious, robust, portable way:

zcat engine.*.log.gz | awk -v RS= '/Text/{print; exit}'

That should also be pretty efficient since the SIGPIPE that zcat gets when awk exits on finding the first Text should terminate the zcat.

Or if Text can appear multiple times in the input and you want all associated records output:

zcat engine.*.log.gz | awk -v RS= -v ORS='\n\n' '/Text/'


问:
How to get filenames with last modified dates from a network drive using Python?
```<code>import os
import time
from pathlib import Path

startDir = os.getcwd()

pt = r"K:\Folder"

asm_pths = [pth for pth in Path(pt).iterdir()
            if pth.suffix == '.jpg']

for file in asm_pths:
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
    for root, dirs, files in os.walk(pt):
        for filename in files:
            print(str(filename) + "," + str(time.ctime(mtime)))
</code>```

I am using the above code to extract filenames with last modified dates from a network drive. Code executes with no errors, but the output has the same 'last modified date' for all the files which is not the case when you check the folder. I tried using the code on a local directory and it gives me desired output.
There is one more issue the compiler keeps executing the code.
So far I have tried sys.exit(), exit(), os.__exit(0). Very confused. Please help.

I am using Komodo Edit and python 3.8.

答:
With os.walk() you have to use os.stat() inside for-loop with different filename or rather os.path.join( root, filename )

```<code>import os
import time

pt = r"K:\Folder"

for root, dirs, files in os.walk(pt):
    for filename in files:
        if filename.endswith('.jpg'):
            fullpath = os.path.join(root, filename)
            (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(fullpath)
            print(str(filename) + "," + str(time.ctime(mtime)))
</code>```

Or without os.walk()

```<code>from pathlib import Path
import os
import time

pt = r"K:\Folder"

asm_pths = [pth for pth in Path(pt).iterdir() if pth.suffix == '.jpg']

for filename in asm_pths:
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(filename)
    print(str(filename) + "," + str(time.ctime(mtime)))
</code>```

or

```<code>from pathlib import Path
import os
import time

pt = r"K:\Folder"

for filename in Path(pt).iterdir():
    if filename.suffix == '.jpg':
        (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(filename)
        print(str(filename) + "," + str(time.ctime(mtime)))
</code>```

You mixed two different methods

Body:
import os
import time
from pathlib import Path

startDir = os.getcwd()

pt = r"K:\Folder"

asm_pths = [pth for pth in Path(pt).iterdir()
            if pth.suffix == '.jpg']

for file in asm_pths:
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
    for root, dirs, files in os.walk(pt):
        for filename in files:
            print(str(filename) + "," + str(time.ctime(mtime)))

I am using the above code to extract filenames with last modified dates from a network drive. Code executes with no errors, but the output has the same 'last modified date' for all the files which is not the case when you check the folder. I tried using the code on a local directory and it gives me desired output.
There is one more issue the compiler keeps executing the code.
So far I have tried sys.exit(), exit(), os.__exit(0). Very confused. Please help.

I am using Komodo Edit and python 3.8.

Body:
With os.walk() you have to use os.stat() inside for-loop with different filename or rather os.path.join( root, filename )

import os
import time

pt = r"K:\Folder"

for root, dirs, files in os.walk(pt):
    for filename in files:
        if filename.endswith('.jpg'):
            fullpath = os.path.join(root, filename)
            (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(fullpath)
            print(str(filename) + "," + str(time.ctime(mtime)))

Or without os.walk()

from pathlib import Path
import os
import time

pt = r"K:\Folder"

asm_pths = [pth for pth in Path(pt).iterdir() if pth.suffix == '.jpg']

for filename in asm_pths:
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(filename)
    print(str(filename) + "," + str(time.ctime(mtime)))

or

from pathlib import Path
import os
import time

pt = r"K:\Folder"

for filename in Path(pt).iterdir():
    if filename.suffix == '.jpg':
        (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(filename)
        print(str(filename) + "," + str(time.ctime(mtime)))

You mixed two different methods


问:
Installing executables with Powershell DSC
I am trying to install Visual Studio 2013 using PowerShell DSC but I'm running into a few issues and hoping that you guys could clear it up for me. Is DSC capable for rebooting the node and then resuming an installation of VS? Does anyone know what this error means? "vs_ultimate.exe was installed, but the specified ProductId and/or Name does not match package details"

Does anyone have any more specific examples of trying to install .exe with this method?

How does someone find out the ProductID?

Does anyone know the exact syntax of the ReturnCode?

Any help would be great!

答:
I wrote a PowerShell function to find the product information</p>

```<code>Function Get-InstallerProductProperty
{
    # Define parameters
    Param($installerFilePath,
    $PropertyName)

    # Verify file exists
    if((Test-Path -Path $installerFilePath) -eq $true)
    {
        $path = $installerFilePath

        $comObjWI = New-Object -ComObject WindowsInstaller.Installer
        $MSIDatabase = $comObjWI.GetType().InvokeMember("OpenDatabase","InvokeMethod",$Null,$comObjWI,@($Path,0))
        $Query = "SELECT Value FROM Property WHERE Property = '$PropertyName'"
        $results = $View = $MSIDatabase.GetType().InvokeMember("OpenView","InvokeMethod",$null,$MSIDatabase,($Query))
        $View.GetType().InvokeMember("Execute", "InvokeMethod", $null, $View, $null)
        $Record = $View.GetType().InvokeMember("Fetch","InvokeMethod",$null,$View,$null)
        $Value = $Record.GetType().InvokeMember("StringData","GetProperty",$null,$Record,1)

        # Return the product id
        return $Value.Replace("{", "").Replace("}", "")
    }
}
</code>```

Body:
I wrote a PowerShell function to find the product information

Function Get-InstallerProductProperty
{
    # Define parameters
    Param($installerFilePath,
    $PropertyName)

    # Verify file exists
    if((Test-Path -Path $installerFilePath) -eq $true)
    {
        $path = $installerFilePath

        $comObjWI = New-Object -ComObject WindowsInstaller.Installer
        $MSIDatabase = $comObjWI.GetType().InvokeMember("OpenDatabase","InvokeMethod",$Null,$comObjWI,@($Path,0))
        $Query = "SELECT Value FROM Property WHERE Property = '$PropertyName'"
        $results = $View = $MSIDatabase.GetType().InvokeMember("OpenView","InvokeMethod",$null,$MSIDatabase,($Query))
        $View.GetType().InvokeMember("Execute", "InvokeMethod", $null, $View, $null)
        $Record = $View.GetType().InvokeMember("Fetch","InvokeMethod",$null,$View,$null)
        $Value = $Record.GetType().InvokeMember("StringData","GetProperty",$null,$Record,1)

        # Return the product id
        return $Value.Replace("{", "").Replace("}", "")
    }
}


问:
Why doesn't PHP auto html decode my POST?
I'm using Zend Framework for a project. Why when I make POST request and get the params in my controller by $this->_request->getParams() it shows undecoded values? For example a string like Speakers & keyboards in my HTML form is retrieved as Speakers & keyboards from getParams() within PHP.

Doesn't PHP autodecode every posted value?

答:
Hi John, thanks for the hint! I think that's the problem really as I'm making an AJAX POST request and it takes data from the page HTML. So I better use something like urlDecode() before sending the request... What do you think?

The problem then, is that you are sending HTML and you want text.

When you grab the content from the page, get text instead of HTML. So don't use innerHTML or jQuery's .html(). Get a textNode and read its data property, or use jQuery's .text().


问:
Celsius to Fahrenheit method doesn't work
I'm a novice in the computer devlopment world and I start with Python.

I try to create a Celsius - Fahrenheit (and vice-versa) converter using Tkinter. I create a method named "celsius_to_fahrenheit" and I define it like that :

```<code>def celsius_to_fahrenheit():
    n = celsius_entry.get()
    result = n * 9 / 5 + 32
    fahrenheit_entry.delete(0, END)
    fahrenheit_entry.insert(0, result)
</code>```

The method is started by a button and when I push it, this error appeared :

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\[Me]\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "D:/Mes Documents/[Me]/Programmation/Python/Projets/ui/degree_farenheit.py", line 7, in celsius_to_fahrenheit
    result = n * 9 / 5 + 32
TypeError: unsupported operand type(s) for /: 'str' and 'int'
</code>```

I hope you can help me !

答:
The type of n is str. This needs to be converted into FLOAT before the calculation.</p>

```<code>n = float(celsius_entry.get())
</code>```

Body:
I'm a novice in the computer devlopment world and I start with Python.

I try to create a Celsius - Fahrenheit (and vice-versa) converter using Tkinter. I create a method named "celsius_to_fahrenheit" and I define it like that :

def celsius_to_fahrenheit():
    n = celsius_entry.get()
    result = n * 9 / 5 + 32
    fahrenheit_entry.delete(0, END)
    fahrenheit_entry.insert(0, result)

The method is started by a button and when I push it, this error appeared :

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\[Me]\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "D:/Mes Documents/[Me]/Programmation/Python/Projets/ui/degree_farenheit.py", line 7, in celsius_to_fahrenheit
    result = n * 9 / 5 + 32
TypeError: unsupported operand type(s) for /: 'str' and 'int'

I hope you can help me !

Body:
The type of n is str. This needs to be converted into FLOAT before the calculation.

n = float(celsius_entry.get())