问:
Intent for selecting wallpaper with wallpaper region highlighting
I would like to know if it's possible to create an Intent that makes the gallery cropper show wallpaper highlighting. This feature has been introduced in Honeycomb. To get an idea of what I'm looking for have a look at the tablet on the image (the three blue rectangles).

I had a look at the source code of the ICS gallery app, but I couldn't find what I'm looking for.

答:
Try this </p>

```<code>    // Set Home wallpaper the image
public void setHomeWallpaper () {
                BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable());
                Bitmap bitmap = bitmapDrawable.getBitmap();
                String bitmapPath = Images.Media.insertImage(getContentResolver(), bitmap, "", null);
                Uri bitmapUri = Uri.parse(bitmapPath);
                Intent intent = new Intent(Intent.ACTION_ATTACH_DATA).setDataAndType(bitmapUri,  "image/jpeg")
                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        .putExtra("mimeType", "image/jpeg");
                startActivity(Intent.createChooser(intent, getString(R.string.background)));
                Toast.makeText(PicassoDisplayImageAdapter.this, "قم بإختيار التطبيق المناسب لتعيين الصورة", Toast.LENGTH_SHORT).show();
}
</code>```

Body:
Try this

    // Set Home wallpaper the image
public void setHomeWallpaper () {
                BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable());
                Bitmap bitmap = bitmapDrawable.getBitmap();
                String bitmapPath = Images.Media.insertImage(getContentResolver(), bitmap, "", null);
                Uri bitmapUri = Uri.parse(bitmapPath);
                Intent intent = new Intent(Intent.ACTION_ATTACH_DATA).setDataAndType(bitmapUri,  "image/jpeg")
                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        .putExtra("mimeType", "image/jpeg");
                startActivity(Intent.createChooser(intent, getString(R.string.background)));
                Toast.makeText(PicassoDisplayImageAdapter.this, "قم بإختيار التطبيق المناسب لتعيين الصورة", Toast.LENGTH_SHORT).show();
}


来源: stackexchange

问:
pod install -bash: pod: command not found
I installed pod some time ago. However, it's stopped working so I'm working through this again.

However, I almost immediately run into a problem here:

```<code>pod install
-bash: pod: command not found
</code>```

Any suggestions why this happened?

答:
so I also had the same problem. This is probably happening because your computer has an older version of ruby. So you need to first update your ruby. Mine worked for ruby 2.6.3 version.I got this solution from sStackOverflow,

You need to first open terminal and put this code

```<code>curl -L https://get.rvm.io | bash -s stable
</code>```

Then put this command

```<code>rvm install ruby-2.6
</code>```

This would install the ruby for you if it hasn' t been installed.After this just update the ruby to the new version

```<code>rvm use ruby-2.6.3
</code>```

After this just make ruby 2.6.3 your default

```<code>rvm --default use 2.6.3
</code>```

This would possibly fix your issue. You can now put the command

```<code>sudo gem install cocoapods
</code>```

And the command

```<code>pod setup
</code>```

I hope this was useful

ContentLicense: CC BY-SA 3.0

Body:
I installed pod some time ago. However, it's stopped working so I'm working through this again.

However, I almost immediately run into a problem here:

pod install
-bash: pod: command not found

Any suggestions why this happened?

Body:
so I also had the same problem. This is probably happening because your computer has an older version of ruby. So you need to first update your ruby. Mine worked for ruby 2.6.3 version.I got this solution from sStackOverflow,

You need to first open terminal and put this code

curl -L https://get.rvm.io | bash -s stable

Then put this command

rvm install ruby-2.6

This would install the ruby for you if it hasn' t been installed.After this just update the ruby to the new version

rvm use ruby-2.6.3

After this just make ruby 2.6.3 your default

rvm --default use 2.6.3

This would possibly fix your issue. You can now put the command

sudo gem install cocoapods

And the command

pod setup

I hope this was useful

ContentLicense: CC BY-SA 4.0


问:
Databind value array to list datatemplate
I have a datatemplate for listbox:

```<code><DataTemplate>
    <Rectangle Width="10" Height="{Binding ???}" Fill="Black" HorizontalAlignment="Center"/>
</DataTemplate>
</code>```

The ItemSource of the list is set to int[] array. What should I specify in Binding ??? to make the binding path take the concrete value?

Thanks.

答:
Have you tried just {Binding}?

This will take the item itself.

Body:
I have a datatemplate for listbox:

<DataTemplate>
    <Rectangle Width="10" Height="{Binding ???}" Fill="Black" HorizontalAlignment="Center"/>
</DataTemplate>

The ItemSource of the list is set to int[] array. What should I specify in Binding ??? to make the binding path take the concrete value?

Thanks.


问:
Python/Boto - Writing to AWS CloudWatch Logs without sequence token
I am trying to send logs to AWS CloudWatch Logs using Python and Boto framework. I am doing this:

```<code>res=logs.put_log_events("FOO", "BAR",
     [{'timestamp':int(round(time.time() * 1000)),
       'message':time.strftime("%m/%d/%Y %H:%M:%S")+' Scheduled  monitoring check' }],
     sequence_token=None)
</code>```

I get an error each time I run:

```<code>boto.logs.exceptions.InvalidSequenceTokenException: InvalidSequenceTokenException: 400 Bad Request
{u'message': u'The given sequenceToken is invalid. The next expected sequenceToken is: 49540113336360065754596906019042392283494234157161146226', u'expectedSequenceToken': u'49540113336360065754596906019042392283494234157161146226', u'__type': u'InvalidSequenceTokenException'}
</code>```

It is somewhat impractical for me to store that token. It makes no sense, why can't I just append to the log stream ?

How can I get around this ?

答:
As it's mentioned in the docs:

You can also get the sequence token in the expectedSequenceToken field from InvalidSequenceTokenException.

However, the problem is that boto3 does not have the expectedSequenceToken field in the exception as it's discussed in the issue:

Boto3 doesn't support parsing additional parameters from exceptions, it only adds a Code and a Message. Labeling as a feature request, I think this is something we should add, but for now your best workaround would be to parse the error message.

Obviously, it's not ideal to parse the message to get the token because the format of the message may change. But it gives a simple working solution without calling describe_log_streams.

```<code>def append_log(group: str, stream: str, msg: str):
    logs = boto3.client('logs')

    def put(token=None, repeat: int = 0):
        events = [{
            'timestamp': int(round(time.time() * 1000)),
            'message': msg
        }]
        try:
            if token:
                logs.put_log_events(logGroupName=group, logStreamName=stream, logEvents=events, sequenceToken=token)
            else:
                logs.put_log_events(logGroupName=group, logStreamName=stream, logEvents=events)
        except (logs.exceptions.InvalidSequenceTokenException, logs.exceptions.DataAlreadyAcceptedException) as e:
            error_msg = e.response['Error']['Message']
            if repeat > 10:
                raise Exception("Too many repeats to write log")
            put(error_msg[error_msg.index(":") + 1:].strip(), repeat + 1)

    try:
        put()
    except logs.exceptions.ResourceNotFoundException:
        try:
            logs.create_log_stream(logGroupName=group, logStreamName=stream)
        except logs.exceptions.ResourceNotFoundException:
            logs.create_log_group(logGroupName=group)
            logs.create_log_stream(logGroupName=group, logStreamName=stream)
        put()
</code>```

The function will create the group and the stream if it does not exist.

Body:
I am trying to send logs to AWS CloudWatch Logs using Python and Boto framework. I am doing this:

res=logs.put_log_events("FOO", "BAR",
     [{'timestamp':int(round(time.time() * 1000)),
       'message':time.strftime("%m/%d/%Y %H:%M:%S")+' Scheduled  monitoring check' }],
     sequence_token=None)

I get an error each time I run:

boto.logs.exceptions.InvalidSequenceTokenException: InvalidSequenceTokenException: 400 Bad Request
{u'message': u'The given sequenceToken is invalid. The next expected sequenceToken is: 49540113336360065754596906019042392283494234157161146226', u'expectedSequenceToken': u'49540113336360065754596906019042392283494234157161146226', u'__type': u'InvalidSequenceTokenException'}

It is somewhat impractical for me to store that token. It makes no sense, why can't I just append to the log stream ?

How can I get around this ?

Body:
As it's mentioned in the docs:

You can also get the sequence token in the expectedSequenceToken field from InvalidSequenceTokenException.

However, the problem is that boto3 does not have the expectedSequenceToken field in the exception as it's discussed in the issue:

Boto3 doesn't support parsing additional parameters from exceptions, it only adds a Code and a Message. Labeling as a feature request, I think this is something we should add, but for now your best workaround would be to parse the error message.

Obviously, it's not ideal to parse the message to get the token because the format of the message may change. But it gives a simple working solution without calling describe_log_streams.

def append_log(group: str, stream: str, msg: str):
    logs = boto3.client('logs')

    def put(token=None, repeat: int = 0):
        events = [{
            'timestamp': int(round(time.time() * 1000)),
            'message': msg
        }]
        try:
            if token:
                logs.put_log_events(logGroupName=group, logStreamName=stream, logEvents=events, sequenceToken=token)
            else:
                logs.put_log_events(logGroupName=group, logStreamName=stream, logEvents=events)
        except (logs.exceptions.InvalidSequenceTokenException, logs.exceptions.DataAlreadyAcceptedException) as e:
            error_msg = e.response['Error']['Message']
            if repeat > 10:
                raise Exception("Too many repeats to write log")
            put(error_msg[error_msg.index(":") + 1:].strip(), repeat + 1)

    try:
        put()
    except logs.exceptions.ResourceNotFoundException:
        try:
            logs.create_log_stream(logGroupName=group, logStreamName=stream)
        except logs.exceptions.ResourceNotFoundException:
            logs.create_log_group(logGroupName=group)
            logs.create_log_stream(logGroupName=group, logStreamName=stream)
        put()

The function will create the group and the stream if it does not exist.


问:
Download from FTP server to client computer
I'm working on ASP.NET project and I need a function where a user downloads a file from FTP server and saved to his/her local machine. The files are in different FTP server and the ASP.NET project is hosted in different server. So to download, I passed the server address and FTP credentials. It works when I runs the project on localhost, but when I upload the project to server and try to download from the hosted site, the files doesn't download and save to my pc. </p>

<p>This my code below </p>

```<code> string inputfilepath = @"C:\Temp\"+_filename;
 string ftphost = "advhost11@14.182.126.8:3131";
 string ftpfilepath = _filename;

 string ftpfullpath = "ftp://" + ftphost +"/"+ ftpfilepath;

 using (WebClient request = new WebClient())
 {
      request.Credentials = new NetworkCredential("username", "password");
      byte[] fileData = request.DownloadData(ftpfullpath);

      Directory.CreateDirectory(Path.GetDirectoryName(inputfilepath));

      using (FileStream file = File.Create(inputfilepath))
      {
           file.Write(fileData, 0, fileData.Length);
           file.Close();
      }

      ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Receipt downloaded and saved at C:\\\\Temp\\\\BankTransfer.');", true);
 }
</code>```

答:
The (hosted) web server does not have access to the remote client (your PC).  When you are saving, you are saving to the web server's local C drive.  If you want them on your C drive, you are going to need to do one of two things:

Take the file you downloaded from the FTP site (which now sits on the web server) and deliver back to the client via HTTP.  This means you aren't sending the file via FTP (with all the pros and cons that come with that), but you also are sharing the FTP credentials.  You have no control of where the client saves the files.

Instead of downloading the file to the web server, you can just provide a link with the ftp protocol ('ftp://...'), including credentials.  This exposes your credentials, however it avoid having twice the bandwidth to the web server (because the client downloads it direct), and prevents you form having to manage a file now sitting on the server.  It also avoids and security risks (for the web server) if the file could be compromised.  You have no control of where the client saves the files.

Body:
I'm working on ASP.NET project and I need a function where a user downloads a file from FTP server and saved to his/her local machine. The files are in different FTP server and the ASP.NET project is hosted in different server. So to download, I passed the server address and FTP credentials. It works when I runs the project on localhost, but when I upload the project to server and try to download from the hosted site, the files doesn't download and save to my pc.

This my code below

 string inputfilepath = @"C:\Temp\"+_filename;
 string ftphost = "advhost11@14.182.126.8:3131";
 string ftpfilepath = _filename;

 string ftpfullpath = "ftp://" + ftphost +"/"+ ftpfilepath;

 using (WebClient request = new WebClient())
 {
      request.Credentials = new NetworkCredential("username", "password");
      byte[] fileData = request.DownloadData(ftpfullpath);

      Directory.CreateDirectory(Path.GetDirectoryName(inputfilepath));

      using (FileStream file = File.Create(inputfilepath))
      {
           file.Write(fileData, 0, fileData.Length);
           file.Close();
      }

      ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Receipt downloaded and saved at C:\\\\Temp\\\\BankTransfer.');", true);
 }


问:
How to embed the plot on Bokeh Flask without URL error?
I am new to Bokeh and HTML, and am working on setting up a graph which would change when the two filters are changed. But, I am getting a URL not found error on a different window when I run the code via FLASK. Below is the input page (first screenshot) and if i click on submit another URL is loading and saying "URL not found" (second screenshot), not sure what I am doing wrong. I need the input and output on the same page and I'd appreciate if anyone's able to guide me. thanks

first screenshot

second screenshot

my app.py code

```<code>import numpy as np
from bokeh.plotting import figure
import pandas as pd
from bokeh.models.tools import HoverTool
from flask import Flask, render_template, request
from bokeh.embed import components
from bokeh.io import show

x=np.random.random(100)
y=np.random.random(100)

f_12 = pd.Series(['f1', 'f2'])
f_12 = f_12.repeat(50)
f_34 = pd.Series(['f3', 'f4'])
f_34 = f_34.repeat(50)

sample_df = pd.DataFrame(data={'x': x
                          ,'y': y
                          ,'filter_12': f_12
                          ,'filter_34': f_34})

f12_list = sample_df['filter_12'].unique().tolist()
f34_list = sample_df['filter_34'].unique().tolist()

def grph(f_12, f_34):
    small_df = sample_df.loc[(sample_df['filter_12'] == f_12) & (sample_df['filter_34'] == f_34)]
    x = list(small_df['x'])
    y = list(small_df['y'])
    fig=figure(x_axis_label="x",y_axis_label="y")
    hover=HoverTool()
    hover.tooltips = [
            ('X ','@x'),
            ('Y', '@y')]
    hover.mode = 'mouse'
    fig.add_tools(hover)
    par = np.polyfit(x, y, 1, full=True)
    slope=par[0][0]
    intercept=par[0][1]
    y_cal = [slope*i + intercept  for i in x]

    fig.line(x, y_cal, color='red', legend="Line_fit")
    fig.circle(x, y, color='green', legend='A')

    return fig (#edited this from show(fig) to fig)

app = Flask(__name__, template_folder='templates')
# Index page
@app.route('/viz2')
def index():
    f_12 = request.args.get("f_12")
    if f_12 == None:
        f_12 = "f1"
    f_34 = request.args.get("f_34")
    if f_34 == None:
        f_34 = "f3"
    # Create the plot
    plot = grph(f_12, f_34)
            # Embed plot into HTML via Flask Render
    script, div = components(plot)
    return render_template("view1.html", script=script, div=div, f12_list=f12_list, f34_list=f34_list, f_12=f_12, f_34=f_34)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

my view1.html file

```<code><html>
<head>
<link
    href="http://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.css"
    rel="stylesheet" type="text/css">
<link
    href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.css"
    rel="stylesheet" type="text/css">

<script src="http://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.js"></script>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.js"></script>

</head>
<body>
<H1>Chart</H1>

<form action="/">
<select name="f_12">
    {% for f12 in f12_list %}
        {% if f12 == f_12 %}
            <option selected value="{{ f12 }}">{{ f12 }}</option>
        {% else %}
            <option value="{{ f12 }}">{{ f12 }}</option>
        {% endif %}
    {% endfor %}
</select>
<select name="f_34">
    {% for f34 in f34_list %}
        {% if f34 == f_34 %}
            <option selected value="{{ f34 }}">{{ f34 }}</option>
        {% else %}
            <option value="{{ f34 }}">{{ f34 }}</option>
        {% endif %}
    {% endfor %}
</select>
<input type="submit">
</form>

{{ script|safe }}
{{ div|safe }}

</body>
</html>

</code>```

答:
You are doing this:

```<code>return show(fig)
</code>```

But need to be doing this:

```<code>return fig
</code>```

Body:
I am new to Bokeh and HTML, and am working on setting up a graph which would change when the two filters are changed. But, I am getting a URL not found error on a different window when I run the code via FLASK. Below is the input page (first screenshot) and if i click on submit another URL is loading and saying "URL not found" (second screenshot), not sure what I am doing wrong. I need the input and output on the same page and I'd appreciate if anyone's able to guide me. thanks

first screenshot

second screenshot

my app.py code

import numpy as np
from bokeh.plotting import figure
import pandas as pd
from bokeh.models.tools import HoverTool
from flask import Flask, render_template, request
from bokeh.embed import components
from bokeh.io import show

x=np.random.random(100)
y=np.random.random(100)

f_12 = pd.Series(['f1', 'f2'])
f_12 = f_12.repeat(50)
f_34 = pd.Series(['f3', 'f4'])
f_34 = f_34.repeat(50)

sample_df = pd.DataFrame(data={'x': x
                          ,'y': y
                          ,'filter_12': f_12
                          ,'filter_34': f_34})

f12_list = sample_df['filter_12'].unique().tolist()
f34_list = sample_df['filter_34'].unique().tolist()

def grph(f_12, f_34):
    small_df = sample_df.loc[(sample_df['filter_12'] == f_12) & (sample_df['filter_34'] == f_34)]
    x = list(small_df['x'])
    y = list(small_df['y'])
    fig=figure(x_axis_label="x",y_axis_label="y")
    hover=HoverTool()
    hover.tooltips = [
            ('X ','@x'),
            ('Y', '@y')]
    hover.mode = 'mouse'
    fig.add_tools(hover)
    par = np.polyfit(x, y, 1, full=True)
    slope=par[0][0]
    intercept=par[0][1]
    y_cal = [slope*i + intercept  for i in x]

    fig.line(x, y_cal, color='red', legend="Line_fit")
    fig.circle(x, y, color='green', legend='A')

    return fig (#edited this from show(fig) to fig)

app = Flask(__name__, template_folder='templates')
# Index page
@app.route('/viz2')
def index():
    f_12 = request.args.get("f_12")
    if f_12 == None:
        f_12 = "f1"
    f_34 = request.args.get("f_34")
    if f_34 == None:
        f_34 = "f3"
    # Create the plot
    plot = grph(f_12, f_34)
            # Embed plot into HTML via Flask Render
    script, div = components(plot)
    return render_template("view1.html", script=script, div=div, f12_list=f12_list, f34_list=f34_list, f_12=f_12, f_34=f_34)

if __name__ == '__main__':
    app.run(debug=True)

my view1.html file

<link
    href="http://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.css"
    rel="stylesheet" type="text/css">
<link
    href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.css"
    rel="stylesheet" type="text/css">

Chart

<form action="/">
<select name="f_12">
    {% for f12 in f12_list %}
        {% if f12 == f_12 %}
            <option selected value="{{ f12 }}">{{ f12 }}</option>
        {% else %}
            <option value="{{ f12 }}">{{ f12 }}</option>
        {% endif %}
    {% endfor %}
</select>
<select name="f_34">
    {% for f34 in f34_list %}
        {% if f34 == f_34 %}
            <option selected value="{{ f34 }}">{{ f34 }}</option>
        {% else %}
            <option value="{{ f34 }}">{{ f34 }}</option>
        {% endif %}
    {% endfor %}
</select>
<input type="submit">
</form>

{{ script|safe }}
{{ div|safe }}

Body:
You are doing this:

return show(fig)

But need to be doing this:

return fig


问:
Passing parameters to a Bash function
I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.

I would like to pass parameters within my script. I tried:

```<code>myBackupFunction("..", "...", "xx")

function myBackupFunction($directory, $options, $rootPassword) {
     ...
}
</code>```

But the syntax is not correct. How can I pass a parameter to my function?

答:
There are two typical ways of declaring a function. I prefer the second approach.

```<code>function function_name {
   command...
}
</code>```

or

```<code>function_name () {
   command...
}
</code>```

To call a function with arguments:

```<code>function_name "$arg1" "$arg2"
</code>```

The function refers to passed arguments by their position (not by name), that is $1, $2, and so forth. $0 is the name of the script itself.

Example:

```<code>function_name () {
   echo "Parameter #1 is $1"
}
</code>```

Also, you need to call your function after it is declared.

```<code>#!/usr/bin/env sh

foo 1  # this will fail because foo has not been declared yet.

foo() {
    echo "Parameter #1 is $1"
}

foo 2 # this will work.
</code>```

Output:

./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
```

Reference: Advanced Bash-Scripting Guide.

Title: Passing parameters to a Bash function

Body:
I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.

I would like to pass parameters within my script. I tried:

myBackupFunction("..", "...", "xx")

function myBackupFunction($directory, $options, $rootPassword) {
     ...
}

But the syntax is not correct. How can I pass a parameter to my function?

Body:
There are two typical ways of declaring a function. I prefer the second approach.

function function_name {
   command...
}

or

function_name () {
   command...
}

To call a function with arguments:

function_name "$arg1" "$arg2"

The function refers to passed arguments by their position (not by name), that is $1, $2, and so forth. $0 is the name of the script itself.

Example:

function_name () {
   echo "Parameter #1 is $1"
}

Also, you need to call your function after it is declared.

#!/usr/bin/env sh

foo 1  # this will fail because foo has not been declared yet.

foo() {
    echo "Parameter #1 is $1"
}

foo 2 # this will work.

Output:

./myScript.sh: line 2: foo: command not found
Parameter #1 is 2

Reference: Advanced Bash-Scripting Guide.


问:
Docker file wait for postgres container
Hello I have the following error in my node project:

(node:51) UnhandledPromiseRejectionWarning: Error: getaddrinfo
  ENOTFOUND ${DB_HOST}

I'm thinking the problem is that my postgress is not yet started when my project starts
and so I'm not able to think of a solution on how to start my container after my postgres is ready, I read something about dockerize, but I'm not able to imagine how to apply

my docker file:

```<code>FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

CMD ["yarn", "dev"]
</code>```

my docker compose:

```<code>version: '3.7'

services:
  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    depends_on:
      - ci-postgres
    networks:
      - ci-network
  ci-postgres:
    image: postgres:12
    container_name: ci-postgres
    ports:
      - '${DB_PORT}:5432'
    environment:
      - ALLOW_EMPTY_PASSWORD=no
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASS}
      - POSTGRES_DB=${DB_NAME}
    volumes:
      - ci-postgres-data:/data
    networks:
      - ci-network

volumes:
  ci-postgres-data:

networks:
  ci-network:
    driver: bridge
</code>```

and this is my .env

```<code>SERVER_PORT=4000
DB_HOST=ci-postgres
DB_PORT=5432
DB_USER=spirit
DB_PASS=api
DB_NAME=emasa_ci
</code>```

答:
You can reference the below docker-compose.yml in which depends_on, healthcheck and links are added as web service depends on db service.

Reference:
Postgresql Container is not running in docker-compose file - Why is this?

```<code>version: "3"
services:
  webapp:
    build: .
    container_name: webapp
    ports:
      - "5000:5000"
    links:
      - postgres
    depends_on:
      postgres:
        condition: service_healthy

  postgres:
    image: postgres:11-alpine
    container_name: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=tmp
      - POSTGRES_USER=tmp
      - POSTGRES_PASSWORD=tmp_password
    volumes:  # Persist the db data
      - database-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  database-data:
</code>```

Title: Docker file wait for postgres container

Body:
Hello I have the following error in my node project:

(node:51) UnhandledPromiseRejectionWarning: Error: getaddrinfo
  ENOTFOUND ${DB_HOST}

I'm thinking the problem is that my postgress is not yet started when my project starts
and so I'm not able to think of a solution on how to start my container after my postgres is ready, I read something about dockerize, but I'm not able to imagine how to apply

my docker file:

FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

CMD ["yarn", "dev"]

my docker compose:

version: '3.7'

services:
  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    depends_on:
      - ci-postgres
    networks:
      - ci-network
  ci-postgres:
    image: postgres:12
    container_name: ci-postgres
    ports:
      - '${DB_PORT}:5432'
    environment:
      - ALLOW_EMPTY_PASSWORD=no
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASS}
      - POSTGRES_DB=${DB_NAME}
    volumes:
      - ci-postgres-data:/data
    networks:
      - ci-network

volumes:
  ci-postgres-data:

networks:
  ci-network:
    driver: bridge

and this is my .env

SERVER_PORT=4000
DB_HOST=ci-postgres
DB_PORT=5432
DB_USER=spirit
DB_PASS=api
DB_NAME=emasa_ci

Body:
You can reference the below docker-compose.yml in which depends_on, healthcheck and links are added as web service depends on db service.

Reference:
Postgresql Container is not running in docker-compose file - Why is this?

version: "3"
services:
  webapp:
    build: .
    container_name: webapp
    ports:
      - "5000:5000"
    links:
      - postgres
    depends_on:
      postgres:
        condition: service_healthy

  postgres:
    image: postgres:11-alpine
    container_name: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=tmp
      - POSTGRES_USER=tmp
      - POSTGRES_PASSWORD=tmp_password
    volumes:  # Persist the db data
      - database-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  database-data:


问:
Selecting IDs/rows within a databrame, based on n-grams
I have the following dataset:

```<code>ID       Text
12     Coolest fan we’ve ever seen.
12     SHARE this with anyone you know who can use this tip!
31     Time for a Royal Celebration! Save the date.
54     The way to a sports fan’s heart? Behind-the-scenes content from their favourite teams.
419    Start asking your questions now for tomorrow’s LIVE Q&A on careers you can do without going to university.
451    Save the date, we’re hosting a fabulous & fun meetup at Coffee Bar Bryant on 9/20. Stay tuned
</code>```

I have used ngrams to analyse text and words/sentences frequency.

```<code>from nltk import ngrams

text=df.Text.tolist()

list_n=[]

for i in text:
    n_grams = ngrams(i.split(), 3)

    for grams in n_grams:
        list_n.append(grams)

list_n
</code>```

Since I am interested in finding in which text a particular word/words sequence was used, I would need to create an association between text (i.e. ID)  and text with particular ngrams.
For example: I am interested in finding texts which contains "Save the date", i.e. ID=31 and ID=451.
To find the n-grams for one single word, I have been using this:

```<code>def ngram_filter(col, word, n):
    tokens = col.split()
    all_ngrams = ngrams(tokens, n)
    filtered_ngrams = [x for x in all_ngrams if word in x]
    return filtered_ngrams
</code>```

However, I do not know how to find the ID associated to the text and how to select more words in the function above.

How could I do this? Any idea?

Please feel free to change tags, if you require. Thanks

答:
I don't have much experience with ngrams, but you could get what you want with str.contains like:

```<code>import re
txt = 'save the date'
print (f'The ngrams "{txt}" is in IDs: ',
       df.loc[df['Text'].str.contains(txt, flags=re.IGNORECASE), 'ID'].tolist())
The ngrams "save the date" is in IDs:  [31, 451]
</code>```

Another option could be to do this, but the performance may not be good:

```<code>txt = 'save the date'

df_ = df.assign(ngrams=df.Text.str.replace(r'[^\w\s]+', '') #remove punctuation
                              .str.lower() # lower case
                              .str.split() #split over a whitespace
                              .apply(lambda x: list(ngrams(x, 3))))\
        .explode('ngrams') #create a row per ngram

print (df_.loc[df_['ngrams'].isin(ngrams(txt.lower().split(), 3))])
    ID                                               Text             ngrams
2   31       Time for a Royal Celebration! Save the date.  (save, the, date)
5  451  Save the date, we’re hosting a fabulous & fun ...  (save, the, date)
</code>```

Body:
I have the following dataset:

ID       Text
12     Coolest fan we’ve ever seen.
12     SHARE this with anyone you know who can use this tip!
31     Time for a Royal Celebration! Save the date.
54     The way to a sports fan’s heart? Behind-the-scenes content from their favourite teams.
419    Start asking your questions now for tomorrow’s LIVE Q&A on careers you can do without going to university.
451    Save the date, we’re hosting a fabulous & fun meetup at Coffee Bar Bryant on 9/20. Stay tuned

I have used ngrams to analyse text and words/sentences frequency.

from nltk import ngrams

text=df.Text.tolist()

list_n=[]

for i in text:
    n_grams = ngrams(i.split(), 3)

    for grams in n_grams:
        list_n.append(grams)

list_n

Since I am interested in finding in which text a particular word/words sequence was used, I would need to create an association between text (i.e. ID)  and text with particular ngrams.
For example: I am interested in finding texts which contains "Save the date", i.e. ID=31 and ID=451.
To find the n-grams for one single word, I have been using this:

def ngram_filter(col, word, n):
    tokens = col.split()
    all_ngrams = ngrams(tokens, n)
    filtered_ngrams = [x for x in all_ngrams if word in x]
    return filtered_ngrams

However, I do not know how to find the ID associated to the text and how to select more words in the function above.

How could I do this? Any idea?

Please feel free to change tags, if you require. Thanks

Body:
I don't have much experience with ngrams, but you could get what you want with str.contains like:

import re
txt = 'save the date'
print (f'The ngrams "{txt}" is in IDs: ',
       df.loc[df['Text'].str.contains(txt, flags=re.IGNORECASE), 'ID'].tolist())
The ngrams "save the date" is in IDs:  [31, 451]

Another option could be to do this, but the performance may not be good:

txt = 'save the date'

df_ = df.assign(ngrams=df.Text.str.replace(r'[^\w\s]+', '') #remove punctuation
                              .str.lower() # lower case
                              .str.split() #split over a whitespace
                              .apply(lambda x: list(ngrams(x, 3))))\
        .explode('ngrams') #create a row per ngram

print (df_.loc[df_['ngrams'].isin(ngrams(txt.lower().split(), 3))])
    ID                                               Text             ngrams
2   31       Time for a Royal Celebration! Save the date.  (save, the, date)
5  451  Save the date, we’re hosting a fabulous & fun ...  (save, the, date)


问:
loop over list of dictionaries conditional on the key existing
I'm looping over a list of dictionaries in Python, but a few of the dictionaries don't contain a key that most have. For such cases, I'd like the loop to conduct a different operation (say print 'key not found').

```<code>dict_list = [{'a' : 1, 'b' : 2}, {'a': 4}]
dict_list

for i in dict_list:
    print(i['b'])
</code>```

This gives me KeyError: 'b'. How do I introduce an operation conditional on the key existing?

答:
One option is to catch the exception:

```<code>for i in dict_list:
    try:
        print(i['b'])
    except KeyError:
        print("key not found")
</code>```

Another is to check the key before using it:

```<code>for i in dict_list:
    if 'b' in i:
        print(i['b'])
    else:
        print("key not found")
</code>```

Yet another is to use .get with a default:

```<code>for i in dict_list:
    print(i.get('b', "key not found"))
</code>```

Body:
I'm looping over a list of dictionaries in Python, but a few of the dictionaries don't contain a key that most have. For such cases, I'd like the loop to conduct a different operation (say print 'key not found').

dict_list = [{'a' : 1, 'b' : 2}, {'a': 4}]
dict_list

for i in dict_list:
    print(i['b'])

This gives me KeyError: 'b'. How do I introduce an operation conditional on the key existing?

Body:
One option is to catch the exception:

for i in dict_list:
    try:
        print(i['b'])
    except KeyError:
        print("key not found")

Another is to check the key before using it:

for i in dict_list:
    if 'b' in i:
        print(i['b'])
    else:
        print("key not found")

Yet another is to use .get with a default:

for i in dict_list:
    print(i.get('b', "key not found"))


问:
Angular Material Dialog - Sending data to dialog
I'm trying to use the same MAT DIALOG for both create client and edit client. I can get the create side going fine but for some reason I'm losing my mind on something that should be very easy. In the EDIT open dialog method I'm calling a service to get the client by ID, then adding that to the dialogConfig object as the second parameter of the open function. If I console log that dialog Config in the component that calls the open method I can see data has been appended to it, but in the dialog component, when picking up that data, I get NULL. For the life of me I can get data into that component.

I've used

dialogConfig.data = client
--and--
dialogConfig.data = {
  client: client
}

both return NULL

----- CALLING COMPONENT

```<code>editClientDialog(id: string) {
    // Create a dialog config object
    const dialogConfig = new MatDialogConfig();

    // Stop user from closing dialog by clicking elsewhere
    dialogConfig.disableClose = true;

    // Get client information from API
    this._clientService.getClient(id).subscribe((response) => {
      let client = response["client"];
      dialogConfig.data = client;
    });

    // Open dialog and also create reference to use for returned data
    let dialogRef = this.dialog.open(ClientDialogComponent, dialogConfig);

    // Returned data from dialog
    dialogRef.afterClosed().subscribe((result) => {
      if (result == undefined) {
        return;
      }
      console.log("AFTER CLOSED", result);
      // this._clientService.addClient(result).subscribe((response) => {
      //   console.log("Response", response);
      //   this.getClients();
      // });
    });
  }
</code>```

--- DIALOG COMPONENT

```<code>import { Component, OnInit, Inject, AfterViewInit } from "@angular/core";
import { ClientService } from "../../../core/services/client.service";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl,
} from "@angular/forms";
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog";
import { Client } from "src/app/core/models/client.interface";

@Component({
  templateUrl: "./client-dialog.component.html",
  styleUrls: ["./client-dialog.component.css"],
})
export class ClientDialogComponent implements OnInit {
  // Properties
  clientForm: FormGroup;
  submitted = false;
  client;

  constructor(
    public clientService: ClientService,
    private _fb: FormBuilder,
    private dialogRef: MatDialogRef<ClientDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    console.log("IN CONSTRUCTOR", data);   <------- this value of data is NULL
  }

  ngOnInit() {
    this.buildClientForm();
    if (this.client !== undefined) {
      this.patchForm(this.client);
    }
  }

  buildClientForm() {
    this.clientForm = this._fb.group({
      individualAsBusiness: new FormControl(false),
      name: [null, [Validators.required]],
      email: [null, Validators.email],
      phone: [
        null,
        [
          Validators.minLength(10),
          Validators.maxLength(10),
          Validators.pattern("^[0-9]*$"),
        ],
      ],
      website: null,
      address: this._fb.group({
        street: null,
        city: null,
        state: null,
        zip: null,
      }),
    });
  }

  patchForm(client) {
    this.clientForm.patchValue(client);
  }

  save() {
    this.dialogRef.close(this.clientForm.value);
  }

  close() {
    this.dialogRef.close();
  }

  // Form getters
  get name() {
    return this.clientForm.get("name");
  }

  get email() {
    return this.clientForm.get("email");
  }

  get phone() {
    return this.clientForm.get("phone");
  }

  get website() {
    return this.clientForm.get("website");
  }

  get address() {
    return this.clientForm.get("address");
  }
}

</code>```

答:
I think the problem is that the dialog is opening before you retrieve the client data. You should open the dialog after retrieving the data, something like this,</p>

```<code>this._clientService.getClient(id).subscribe((response) => {
    let client = response["client"];
    dialogConfig.data = client;

    // Open dialog and also create reference to use for returned data
    let dialogRef = this.dialog.open(ClientDialogComponent, dialogConfig);

    // Returned data from dialog
    dialogRef.afterClosed().subscribe((result) => {
        if (result == undefined) {
            return;
        }
        // ...
    });
});
</code>```

Body:
I'm trying to use the same MAT DIALOG for both create client and edit client. I can get the create side going fine but for some reason I'm losing my mind on something that should be very easy. In the EDIT open dialog method I'm calling a service to get the client by ID, then adding that to the dialogConfig object as the second parameter of the open function. If I console log that dialog Config in the component that calls the open method I can see data has been appended to it, but in the dialog component, when picking up that data, I get NULL. For the life of me I can get data into that component.

I've used

dialogConfig.data = client
--and--
dialogConfig.data = {
  client: client
}

both return NULL

----- CALLING COMPONENT

editClientDialog(id: string) {
    // Create a dialog config object
    const dialogConfig = new MatDialogConfig();

    // Stop user from closing dialog by clicking elsewhere
    dialogConfig.disableClose = true;

    // Get client information from API
    this._clientService.getClient(id).subscribe((response) => {
      let client = response["client"];
      dialogConfig.data = client;
    });

    // Open dialog and also create reference to use for returned data
    let dialogRef = this.dialog.open(ClientDialogComponent, dialogConfig);

    // Returned data from dialog
    dialogRef.afterClosed().subscribe((result) => {
      if (result == undefined) {
        return;
      }
      console.log("AFTER CLOSED", result);
      // this._clientService.addClient(result).subscribe((response) => {
      //   console.log("Response", response);
      //   this.getClients();
      // });
    });
  }

--- DIALOG COMPONENT

import { Component, OnInit, Inject, AfterViewInit } from "@angular/core";
import { ClientService } from "../../../core/services/client.service";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl,
} from "@angular/forms";
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog";
import { Client } from "src/app/core/models/client.interface";

@Component({
  templateUrl: "./client-dialog.component.html",
  styleUrls: ["./client-dialog.component.css"],
})
export class ClientDialogComponent implements OnInit {
  // Properties
  clientForm: FormGroup;
  submitted = false;
  client;

  constructor(
    public clientService: ClientService,
    private _fb: FormBuilder,
    private dialogRef: MatDialogRef<ClientDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    console.log("IN CONSTRUCTOR", data);   <------- this value of data is NULL
  }

  ngOnInit() {
    this.buildClientForm();
    if (this.client !== undefined) {
      this.patchForm(this.client);
    }
  }

  buildClientForm() {
    this.clientForm = this._fb.group({
      individualAsBusiness: new FormControl(false),
      name: [null, [Validators.required]],
      email: [null, Validators.email],
      phone: [
        null,
        [
          Validators.minLength(10),
          Validators.maxLength(10),
          Validators.pattern("^[0-9]*$"),
        ],
      ],
      website: null,
      address: this._fb.group({
        street: null,
        city: null,
        state: null,
        zip: null,
      }),
    });
  }

  patchForm(client) {
    this.clientForm.patchValue(client);
  }

  save() {
    this.dialogRef.close(this.clientForm.value);
  }

  close() {
    this.dialogRef.close();
  }

  // Form getters
  get name() {
    return this.clientForm.get("name");
  }

  get email() {
    return this.clientForm.get("email");
  }

  get phone() {
    return this.clientForm.get("phone");
  }

  get website() {
    return this.clientForm.get("website");
  }

  get address() {
    return this.clientForm.get("address");
  }
}

Body:
I think the problem is that the dialog is opening before you retrieve the client data. You should open the dialog after retrieving the data, something like this,

this._clientService.getClient(id).subscribe((response) => {
    let client = response["client"];
    dialogConfig.data = client;

    // Open dialog and also create reference to use for returned data
    let dialogRef = this.dialog.open(ClientDialogComponent, dialogConfig);

    // Returned data from dialog
    dialogRef.afterClosed().subscribe((result) => {
        if (result == undefined) {
            return;
        }
        // ...
    });
});


答:
You can use regexp_substr():

```<code>select regexp_substr(INTERNAL_ADDRESS_LINE, '[0-9]+', 1, 3),
       regexp_substr(INTERNAL_ADDRESS_LINE, '[0-9]+', 1, 4)
</code>```

Here is a db<>fiddle.

Note that this assumes that all the non-dash characters are numbers.  A more general version just uses the delimiters:

```<code>select regexp_substr(INTERNAL_ADDRESS_LINE, '[^-]+', 1, 3),
       regexp_substr(INTERNAL_ADDRESS_LINE, '[^-]+', 1, 4)
</code>```

Title: How to retrieve a particular number from the string XXXX-XXXX-XXX-XXXX through SQL

Body:
I have a column that gets value in the format "100-02-000-020-000-99801-000-000000-000000"

INTERNAL_ADDRESS_LINE
-------------------------------------------
100-02-010-020-000-99801-000-000000-000000
150-01-020-000-210-99802-000-000000-000000
150-01-030-000-230-99802-000-000000-000000

I want to retrieve the 3rd value (after the second -) and 4th value (after third -), for example:

OUTPUT_COL    COL2
------------------
010           020
020           000
030           000

How can this be achieved?

Body:
You can use regexp_substr():

select regexp_substr(INTERNAL_ADDRESS_LINE, '[0-9]+', 1, 3),
       regexp_substr(INTERNAL_ADDRESS_LINE, '[0-9]+', 1, 4)

Here is a db<>fiddle.

Note that this assumes that all the non-dash characters are numbers.  A more general version just uses the delimiters:

select regexp_substr(INTERNAL_ADDRESS_LINE, '[^-]+', 1, 3),
       regexp_substr(INTERNAL_ADDRESS_LINE, '[^-]+', 1, 4)


问:
Deep Cache? Changes I make on filezilla are successful but does not appear on my devices?
I have recently changed web host providers, (from 123-reg to SiteGround) and have a HTML website. Now when I make a change via FTP through Filezilla, it says upload successful however I cannot see the change on my computer. The changes are there however, as when I test it via kproxy.com I can see the changes. I have tried clearing my browser cache several times and this has not fixed the issue. The changes can not be seen on my ipad/ phone, and also cannot be seen on another friends laptop and phone either.

Does anyone know what the issue is here? I have been using Filezilla for a couple years now and the changes have always been instant and seen just via a page refresh.
Any help would be greatly appreciated!

答:
Open up the dev console to the network tab.  look at the request to see where the data is coming from.   it could be stuck in your disk cache and to clear it

On your computer, open Chrome.

At the top right, click More

Click More tools. Clear browsing data.

At the top, choose a time range. To delete everything, select All time.

Next to "Cookies and other site data" and "Cached images and files," check the boxes.

Click Clear data


答:
It throws it KeyError: 'b' the second index of list (second dict) does not contain b.

You can use try-except for "operation conditional on the key existing":

dict_list = [{'a' : 1, 'b' : 2}, {'a' :4}]

for i in dict_list:
    try:
        # this will print `b` when it founds
        print(i['b'])
    except KeyError:
        # this will be printed when it could not found b
        print('b not found')
```

Title: loop over list of dictionaries conditional on the key existing


问:
Why does allowing for recursion make C slower/inefficient on 8-bit CPUs
Answers to this question about compiler efficiency for 8-bit CPUs seem to imply that allowing for recursion makes the C language inefficient on these architectures.  I don't understand how recursive function calling (of the same function) is different from just repeated function calling of various functions.

I would like to understand why this is so (or why seemingly learned people think it is).  I could guess that maybe these architectures just don't have the stack-space, or perhaps the push/pop is inefficient - but these are just guesses.

答:
Because to efficiently implement the C stack, you need the ability to efficiently load and store to arbitrary offsets within the current frame. For example, the 8086 processor provided the indexed and based address modes, that allowed loading a stack variable within a single instruction. With the 6502, you can only do this with the X or Y register, and since those are the only general purpose registers, reserving one for a data stack pointer is extremely costly. The Z80 can do this with its IX or IY registers, but not the stack pointer register. However, indexed load instructions on the Z80 take a long time to execute, so it is still costly, along with the fact you either reserve a second register for the stack pointer, or have to load the stack pointer from the SP register any time you want to access variables.

By comparison, if recursive calls are not supported, then a second instance of the function can not start inside a call whilst an existing is still in progress. This means only a single set of variables is needed at a time and you can just allocate each function its own static piece of memory to use for variables. Since the memory has a fixed location, you can then use fixed address loads. Some implementations of fortran used this approach.


问:
How to list all projects on computer (C, Java, Python, C++, etc...)
I want to write a program to list all projects I've got on my hard drive, whatever languages. So for example if I have something like user/projects/C/decompressor/src/... I want the program to ouput decompressor, which is the project root, as it contains src folders and so on. But there are too many case where the parent folder of src is not the real root folder:
projects/C/my-app/release1/src/... or projects/C/another-project-in-c/master/src/...

So before coding I wanted to know what would be the best way to do so ? I have a piece of code that doesn't works as I want:

```<code>    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(name)))
      return;

    while ((entry = readdir(dir)) != NULL) {
      if (entry->d_type == DT_DIR) {
          char path[1024];
          if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
              continue;
          snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
          //printf("%*s[%s]\n", indent, "", entry->d_name);
          listdir(path, indent + 2);
      } else {
        if (strcmp(get_file_extension(entry->d_name), ".c") == 0) {
          char buffer[1024];
          realpath(name, buffer);

          printf("possible root folder = \"%s\" \n", get_parent(buffer));
        }
      }
    }
    closedir(dir);
</code>```

and:

```<code>char* get_parent(char* filename) {
    return (dirname(filename));
}

const char* get_file_extension(const char* filename) {
    assert(filename != NULL);

    char buffer[1024];
    char* tmp = strcpy(buffer, filename);
    char *ext = strrchr(tmp, '.');

    if (ext == NULL)
        return (char*) tmp + strlen(tmp);

    for (char *iter = ext + 1; *iter != '\0'; iter++) {
        if (!isalnum((unsigned char)*iter))
            return (char*) tmp + strlen(tmp);
    }

    return ext;
}
</code>```

I didn't mention it, but there's also the java project structure (projects/JAVA/MyApp/com/lorem/ipsum/concrete-package) to take in count.

Is this even possible with all the particular cases?

答:
Let projects be the overall projects' root, then you first want to scan all directories inside projects by using a readdir loop (given that each directory inside projects stands for a certain language and contains actual project directories).
While iterating, you want to scan each language folder itself for all d_names that are contained.

To clarify what I'm talking about, I got some pseudo code for you:

```<code>dirp = opendir("/user/projects");
while (entp = readdir(dirp)) {
    inner_dirp = opendir(entp->d_name);
    while (inner_entp = readdir(inner_dirp)) {
        print(inner_entp->d_name)
    }
}
</code>```

Note that if your folder structure is prone to change, you might want to go by a recursive approach.

Body:
I want to write a program to list all projects I've got on my hard drive, whatever languages. So for example if I have something like user/projects/C/decompressor/src/... I want the program to ouput decompressor, which is the project root, as it contains src folders and so on. But there are too many case where the parent folder of src is not the real root folder:
projects/C/my-app/release1/src/... or projects/C/another-project-in-c/master/src/...

So before coding I wanted to know what would be the best way to do so ? I have a piece of code that doesn't works as I want:

    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(name)))
      return;

    while ((entry = readdir(dir)) != NULL) {
      if (entry->d_type == DT_DIR) {
          char path[1024];
          if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
              continue;
          snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
          //printf("%*s[%s]\n", indent, "", entry->d_name);
          listdir(path, indent + 2);
      } else {
        if (strcmp(get_file_extension(entry->d_name), ".c") == 0) {
          char buffer[1024];
          realpath(name, buffer);

          printf("possible root folder = \"%s\" \n", get_parent(buffer));
        }
      }
    }
    closedir(dir);

and:

char* get_parent(char* filename) {
    return (dirname(filename));
}

const char* get_file_extension(const char* filename) {
    assert(filename != NULL);

    char buffer[1024];
    char* tmp = strcpy(buffer, filename);
    char *ext = strrchr(tmp, '.');

    if (ext == NULL)
        return (char*) tmp + strlen(tmp);

    for (char *iter = ext + 1; *iter != '\0'; iter++) {
        if (!isalnum((unsigned char)*iter))
            return (char*) tmp + strlen(tmp);
    }

    return ext;
}

I didn't mention it, but there's also the java project structure (projects/JAVA/MyApp/com/lorem/ipsum/concrete-package) to take in count.

Is this even possible with all the particular cases?

Body:
Let projects be the overall projects' root, then you first want to scan all directories inside projects by using a readdir loop (given that each directory inside projects stands for a certain language and contains actual project directories).
While iterating, you want to scan each language folder itself for all d_names that are contained.

To clarify what I'm talking about, I got some pseudo code for you:

dirp = opendir("/user/projects");
while (entp = readdir(dirp)) {
    inner_dirp = opendir(entp->d_name);
    while (inner_entp = readdir(inner_dirp)) {
        print(inner_entp->d_name)
    }
}

Note that if your folder structure is prone to change, you might want to go by a recursive approach.


问:
Detect cycles in a genealogy graph during a Depth-first search
I'm loading horse genealogical data recursively.
For some wrong sets of data my recursion never stops... and that is because  there are cycles in the data.

How can I detect those cycles to stop recurring?

I thought of while recurring maintain a hashTable with all "visited" horses.
But that will find some false positives, because a horse CAN be twice in a tree.

What cannot happen is that a horse appear as a father or grandfather or great grandfather of ITSELF.

答: Your hash table solution should work if you keep track of nodes instead of horses. Just make sure every time you read a new horse you create a new node even if the value/horse is the same as a previous node's value/horse. </p>

OwnerDisplayName: Romias

OwnerDisplayName: C. Dragon 76

ContentLicense: CC BY-SA 2.5


答:
Since your strings have a fixed format, I would recommend string functions, since they can get the job done, and are more efficient than regexes:

```<code>select
    substr(INTERNAL_ADDRESS_LINE, 8, 3) output_col,
    substr(INTERNAL_ADDRESS_LINE, 12, 3) col2
from mytable
</code>```

Demo on DB Fiddle:

```<code>with mytable as (
    select '100-02-010-020-000-99801-000-000000-000000' INTERNAL_ADDRESS_LINE from dual
    union all select '150-01-020-000-210-99802-000-000000-000000' from dual
    union all select '150-01-030-000-230-99802-000-000000-000000' from dual
)
select
    substr(INTERNAL_ADDRESS_LINE, 8, 3) output_col,
    substr(INTERNAL_ADDRESS_LINE, 12, 3) col2
from mytable
</code>```

```
OUTPUT_COL | COL2
:--------- | :---
010        | 020
020        | 000
030        | 000
```

Body:
Since your strings have a fixed format, I would recommend string functions, since they can get the job done, and are more efficient than regexes:

select
    substr(INTERNAL_ADDRESS_LINE, 8, 3) output_col,
    substr(INTERNAL_ADDRESS_LINE, 12, 3) col2
from mytable

Demo on DB Fiddle:

with mytable as (
    select '100-02-010-020-000-99801-000-000000-000000' INTERNAL_ADDRESS_LINE from dual
    union all select '150-01-020-000-210-99802-000-000000-000000' from dual
    union all select '150-01-030-000-230-99802-000-000000-000000' from dual
)
select
    substr(INTERNAL_ADDRESS_LINE, 8, 3) output_col,
    substr(INTERNAL_ADDRESS_LINE, 12, 3) col2
from mytable

OUTPUT_COL | COL2
:--------- | :---
010        | 020
020        | 000
030        | 000


问:
How to print an IFRAME containing multipe pages?
I would like to know if it is possible to print an HTML page containing an IFRAME that spans multiple pages. For some reason the browser keeps truncating the IFRAME after the first page. Here is a minimalistic example that demonstrates the issue outlined above. At first, here is a simple HTML page containing an IFRAME that should be optimized for printing:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>TEST</title>

    <style>
        html, body {
            height: 100%;
        }

        iframe {
            width: 100%;
            height: 100%;
        }
    </style>

  </head>
  <body>
    <iframe src="iframe-content.html">
    </iframe>
  </body>
</html>
</code>```

And here is the page I want to embed:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>TEST-CONTENT</title>

  </head>
  <body>
    <p>
      Some very, very long text spawning multiple pages.
    </p>
  </body>
</html>
</code>```

Using JavaScript is not an option. I'm looking for a solution that uses CSS only. Any help would be greatly appreciated.

答:
My solution uses javascript to manipulate the DOM.

Also, your iframe needs an id attribute as shown below  -- id='iframe1'

```<code><body>
  <iframe id='iframe1' src="iframe-content.html">
  </iframe>
</body>
</code>```

here is the javascript code:

```<code><script>

 pages =[] // initiate an empty list here

function printPage() {

// get the iframe and push its innerHTML into the list

var frame_content = document.getElementById('iframe1');
pages.push(frame_content.contentWindow.document.body.innerHTML);

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// Then we now set the parent window to be equal to pages

window.content.document.body.innerHTML = pages;
// then we print this new window that contains the iframe's innerHTML
window.print();
}
else {
// do nothing
}

}
</code>```

With this solution, the print will not truncate your pages.

Also, in case you have multiple iframes, it generates only one print dialogue box.

Someone may wonder why i am pushing to a list. This caters for cases where you have more than one iframe hence you can easily push and concatenate all their innerHTML.

Remember that in your parent page HTML you will have the code below to call the printPage function.

```<code><input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />
</code>```

Body:
I would like to know if it is possible to print an HTML page containing an IFRAME that spans multiple pages. For some reason the browser keeps truncating the IFRAME after the first page. Here is a minimalistic example that demonstrates the issue outlined above. At first, here is a simple HTML page containing an IFRAME that should be optimized for printing:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>TEST</title>

And here is the page I want to embed:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>TEST-CONTENT</title>

      Some very, very long text spawning multiple pages.

Using JavaScript is not an option. I'm looking for a solution that uses CSS only. Any help would be greatly appreciated.

Body:
My solution uses javascript to manipulate the DOM.

Also, your iframe needs an id attribute as shown below  -- id='iframe1'

<body>
  <iframe id='iframe1' src="iframe-content.html">
  </iframe>
</body>

here is the javascript code:

<script>

 pages =[] // initiate an empty list here

function printPage() {

// get the iframe and push its innerHTML into the list

var frame_content = document.getElementById('iframe1');
pages.push(frame_content.contentWindow.document.body.innerHTML);

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// Then we now set the parent window to be equal to pages

window.content.document.body.innerHTML = pages;
// then we print this new window that contains the iframe's innerHTML
window.print();
}
else {
// do nothing
}

}

With this solution, the print will not truncate your pages.

Also, in case you have multiple iframes, it generates only one print dialogue box.

Someone may wonder why i am pushing to a list. This caters for cases where you have more than one iframe hence you can easily push and concatenate all their innerHTML.

Remember that in your parent page HTML you will have the code below to call the printPage function.

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />


问:
peewee IntegrityError: UNIQUE constraint failed: userpost.user_id, userpost.post_id
I have got the following models: Post, Tag, User, UserPost and PostTag

I want a Post to have multiple Tags and Users to have multiple Posts

I am trying to update a post by hitting this endpoint/edit/<post-slug-here>/ but get this error IntegrityError: UNIQUE constraint failed: userpost.user_id, userpost.post_id I thought peewee would increment the primary key id,I'm not sure why this is occuring or if I am not understanding something correctly, any help is appreciated

models.py

```<code>from datetime import datetime
from app import database, app
from playhouse.sqlite_ext import CharField, DateTimeField, BooleanField, TextField, ForeignKeyField, FTSModel, SearchField
from peewee import Model

class BaseModel(Model):
    class Meta:
        database = database

class Tag(BaseModel):
    name = CharField()

class Post(BaseModel):
    title = CharField()
    slug = CharField(unique=True)
    content = TextField()
    published = BooleanField(index=True)
    timestamp = DateTimeField(default=datetime.now, index=True)

    @property
    def get_tags(self):
        """
        Returns string array of all tags for a post
        """
        tag_list  = []
        query = Tag.select().join(PostTag).where(PostTag.post == self)
        for newtag in query:
            tag_list.append(newtag.name)
        return ','.join(tag_list)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = re.sub('[^\w]+', '-', str(self.title).lower()).strip('-')
        ret = super(Post, self).save(*args, **kwargs)
        return ret

class User(BaseModel):
    username = CharField()
    email = CharField(unique=True)
    password = CharField(unique=True)
    timestamp = DateTimeField(default=datetime.now, index=True)

class UserPost(BaseModel):
    user = ForeignKeyField(User, backref='userposts' )
    post = ForeignKeyField(Post, backref='userposts' )
    class Meta:
        indexes = (
            (('user', 'post'), True),
        )

class PostTag(BaseModel):
    post = ForeignKeyField(Post, backref='posttags')
    tag = ForeignKeyField(Tag, backref='posttags')

    class Meta:
        indexes = (
            (('post', 'tag'), True),
        )

</code>```

routes.py

```<code>from flask import render_template, flash, redirect, url_for, session
from sqlalchemy.exc import IntegrityError
from app.models import *
from peewee import *

# get the user from the session
def get_current_user():
    if session.get('logged_in'):
        return User.get(User.id == session['user_id'])

@app.route('/edit/<string:slug>/', methods=['GET', 'POST'])
@login_required
def edit(slug):
    post = get_object_or_404(Post, Post.slug == slug)
    return _create_or_edit(post, 'edit.html')

def _create_or_edit(post, template):
    if request.method == 'POST':
        post.title = request.form.get('title') or ''
        post.content = request.form.get('content') or ''
        post.tags = post.get_tags or ''
        post.published = request.form.get('published') or False
        if not (post.title and post.content):
            flash('Title and Content are required.', 'danger')
        else:
            try:
                with database.atomic()
                    if post.tags != '':
                        tag_names = post.get_tags.split(',')
                        for name in tag_names:
                            tag = Tag.create(name=name)
                            tag.save()
                            post_tag = PostTag.create(
                                post = post,
                                tag = tag
                            )
                            post_tag.save()
                    UserPost.create(
                        user = get_current_user(),
                        post= post
                    )
                    post.save()
            except IntegrityError:
                flash('Error: this title is already in use.', 'danger')
                raise
            else:
                flash('Post saved successfully.', 'success')
                if post.published:
                    return redirect(url_for('detail', slug=post.slug))
                else:
                    return redirect(url_for('edit', slug=post.slug))
    return render_template(template, post=post)
</code>```

答: It looks like you're trying to save the same user + post combination. In other words, you're inserting a User <-> Post link, but that user is already linked to the post so the constraint is failing.</p>

Body:
I have got the following models: Post, Tag, User, UserPost and PostTag

I want a Post to have multiple Tags and Users to have multiple Posts

I am trying to update a post by hitting this endpoint/edit/<post-slug-here>/ but get this error IntegrityError: UNIQUE constraint failed: userpost.user_id, userpost.post_id I thought peewee would increment the primary key id,I'm not sure why this is occuring or if I am not understanding something correctly, any help is appreciated

models.py

from datetime import datetime
from app import database, app
from playhouse.sqlite_ext import CharField, DateTimeField, BooleanField, TextField, ForeignKeyField, FTSModel, SearchField
from peewee import Model

class BaseModel(Model):
    class Meta:
        database = database

class Tag(BaseModel):
    name = CharField()

class Post(BaseModel):
    title = CharField()
    slug = CharField(unique=True)
    content = TextField()
    published = BooleanField(index=True)
    timestamp = DateTimeField(default=datetime.now, index=True)

    @property
    def get_tags(self):
        """
        Returns string array of all tags for a post
        """
        tag_list  = []
        query = Tag.select().join(PostTag).where(PostTag.post == self)
        for newtag in query:
            tag_list.append(newtag.name)
        return ','.join(tag_list)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = re.sub('[^\w]+', '-', str(self.title).lower()).strip('-')
        ret = super(Post, self).save(*args, **kwargs)
        return ret

class User(BaseModel):
    username = CharField()
    email = CharField(unique=True)
    password = CharField(unique=True)
    timestamp = DateTimeField(default=datetime.now, index=True)

class UserPost(BaseModel):
    user = ForeignKeyField(User, backref='userposts' )
    post = ForeignKeyField(Post, backref='userposts' )
    class Meta:
        indexes = (
            (('user', 'post'), True),
        )

class PostTag(BaseModel):
    post = ForeignKeyField(Post, backref='posttags')
    tag = ForeignKeyField(Tag, backref='posttags')

    class Meta:
        indexes = (
            (('post', 'tag'), True),
        )

routes.py

from flask import render_template, flash, redirect, url_for, session
from sqlalchemy.exc import IntegrityError
from app.models import *
from peewee import *

# get the user from the session
def get_current_user():
    if session.get('logged_in'):
        return User.get(User.id == session['user_id'])

@app.route('/edit/<string:slug>/', methods=['GET', 'POST'])
@login_required
def edit(slug):
    post = get_object_or_404(Post, Post.slug == slug)
    return _create_or_edit(post, 'edit.html')

def _create_or_edit(post, template):
    if request.method == 'POST':
        post.title = request.form.get('title') or ''
        post.content = request.form.get('content') or ''
        post.tags = post.get_tags or ''
        post.published = request.form.get('published') or False
        if not (post.title and post.content):
            flash('Title and Content are required.', 'danger')
        else:
            try:
                with database.atomic()
                    if post.tags != '':
                        tag_names = post.get_tags.split(',')
                        for name in tag_names:
                            tag = Tag.create(name=name)
                            tag.save()
                            post_tag = PostTag.create(
                                post = post,
                                tag = tag
                            )
                            post_tag.save()
                    UserPost.create(
                        user = get_current_user(),
                        post= post
                    )
                    post.save()
            except IntegrityError:
                flash('Error: this title is already in use.', 'danger')
                raise
            else:
                flash('Post saved successfully.', 'success')
                if post.published:
                    return redirect(url_for('detail', slug=post.slug))
                else:
                    return redirect(url_for('edit', slug=post.slug))
    return render_template(template, post=post)


问:
PyCharm Python Threading
I am running a program which is attempting to open 1000 threads using Python's ThreadPoolExecutor, which I have configured to allow a maximum of 1000 threads. On a Windows machine with 4GB of memory, I am able to start ~870 threads before I get a runtime error: can't start new thread. With 16GB of memory, I am able to start ~870 threads as well, though the runtime error, can't start new thread, occurs two minutes later. All threads are running a while loop, which means that they will never complete their tasks. This is the intention.

Why is PyCharm/Windows/Python, whichever may be the culprit, failing to start more than 870 out of the 1000 threads which I am attempting to start, with that number being invariable despite a significant change in the RAM? This leaves me to conclude that hardware limitations are not the problem, which also leaves me completely and utterly confused.

What could be causing this, and how do I fix it?

答:
It is very hard to say without all the details of your configuration and your code, but my guess is that it's windows being starved for certain kinds of memory. I suggest looking into the details in this article:

I attempted to duplicate your issue with Pycharm and python3.8 on my linux box and I was able to make 10000 threads with the code below. Note that I have every thread sleep for quite a while upon creation otherwise the thread creation process slows way down as the main thread of execution, which is trying to make the threads, becomes CPU starved. I have 32GB of RAM but I am able to make 10000 threads with a ThreadPoolExecutor on linux.

```<code>from concurrent.futures import ThreadPoolExecutor
import time

def runForever():
    time.sleep(10)
    while True:
        for i in range(100):
            a = 10

t = ThreadPoolExecutor(max_workers=10000)

for i in range(10000):
    t.submit(runForever)
    print(len(t._threads))

print(len(t._threads))
</code>```

Title: PyCharm Python Threading

Body:
It is very hard to say without all the details of your configuration and your code, but my guess is that it's windows being starved for certain kinds of memory. I suggest looking into the details in this article:

I attempted to duplicate your issue with Pycharm and python3.8 on my linux box and I was able to make 10000 threads with the code below. Note that I have every thread sleep for quite a while upon creation otherwise the thread creation process slows way down as the main thread of execution, which is trying to make the threads, becomes CPU starved. I have 32GB of RAM but I am able to make 10000 threads with a ThreadPoolExecutor on linux.

from concurrent.futures import ThreadPoolExecutor
import time

def runForever():
    time.sleep(10)
    while True:
        for i in range(100):
            a = 10

t = ThreadPoolExecutor(max_workers=10000)

for i in range(10000):
    t.submit(runForever)
    print(len(t._threads))

print(len(t._threads))


问:
How can I compare two time strings in the format HH:MM:SS?
I have two time strings in HH:MM:SS format. For example, str1 contains 10:20:45,  str2 contains 5:10:10.

How can I compare the above values?

答:
As Felix Kling said in the comments, provided your times are based on a 24 hour clock (and they should be if there's no AM/PM) and provided they are always in the format HH:MM:SS you can do a direct string comparison:

```<code>var str1 = "10:20:45",
    str2 = "05:10:10";

if (str1 > str2)
    alert("Time 1 is later than time 2");
else
    alert("Time 2 is later than time 1");
</code>```

Body:
As Felix Kling said in the comments, provided your times are based on a 24 hour clock (and they should be if there's no AM/PM) and provided they are always in the format HH:MM:SS you can do a direct string comparison:

var str1 = "10:20:45",
    str2 = "05:10:10";

if (str1 > str2)
    alert("Time 1 is later than time 2");
else
    alert("Time 2 is later than time 1");


问:
Is there a possibility to refresh a certain frame in Selenium
I would like to refresh a certain IFrame using Selenium.
Only approach that came to my mind was to use a Key for an f5 on certain WebElement.

driver.switchTo().parentFrame();
driver.findElement(By.id("main")).sendKeys("\\uE035");
```

But it does reload entire page and this is not what i need.
There is and option to reload it using right mouse button on a chosen frame then you can pick "reload a frame" option but chrome does not provide shortcut for this one which makes it impossible to use SendKeys() on a certain WebElement.

答:
It looks like you're ivoking the refresh on the parentElement rather than the actual iFrame element.

Try something like below. If you have multiple iframe elements, you'll need to use a different selector.

```<code>        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("document.getElementsByTagName('iframe')[0].contentWindow.location.reload();");
</code>```

Body:
I would like to refresh a certain IFrame using Selenium.
Only approach that came to my mind was to use a Key for an f5 on certain WebElement.

driver.switchTo().parentFrame();
driver.findElement(By.id("main")).sendKeys("\\uE035");

But it does reload entire page and this is not what i need.
There is and option to reload it using right mouse button on a chosen frame then you can pick "reload a frame" option but chrome does not provide shortcut for this one which makes it impossible to use SendKeys() on a certain WebElement.

Body:
It looks like you're ivoking the refresh on the parentElement rather than the actual iFrame element.

Try something like below. If you have multiple iframe elements, you'll need to use a different selector.

        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("document.getElementsByTagName('iframe')[0].contentWindow.location.reload();");


问:
How can I make data, methods and computed globally in vue?
My code like this :

<template>
  <v-layout
    column
    justify-center
    align-center
  >
    <v-flex
      xs12
      sm8
      md6
    >
      ...
    </v-flex>
  </v-layout>
</template>
```

<pre class="lang-js prettyprint-override"><code>export default {
  data () {
    return {
      currentDate: this.$moment().format('YYYY-MM-DD')
    }
  },
  computed: {
    birthdayFormatted () {
      return this.formatBirthday(this.birthday)
    },
  },
  methods: {
    formatBirthday (date) {
      if (!date) {
        return null
      }
      const d = this.$moment(date).format('DD MMM YYYY')
      return d
    }
  }
}
</code>```

```

For example, I have component A like that

Where do I put currentDate data, formatBirthday method and birthdayFormatted computed? So it can be read in other components

Did I put them in vuex store?

答:
You can declare a Global Mixin on your vue app:

Vue.mixin({
    data () {
        return {
            currentDate: this.$moment().format('YYYY-MM-DD')
        }
    },
    computed: {
        birthdayFormatted () {
            return this.formatBirthday(this.birthday)
        },
    },
    methods: {
        formatBirthday (date) {
            if (!date) {
              return null
            }
            const d = this.$moment(date).format('DD MMM YYYY')
            return d
        }
    }
})
```

Then you can access to data, computed and method declared on each Vue component.

Body:
My code like this :

<template>
  <v-layout
    column
    justify-center
    align-center
  >
    <v-flex
      xs12
      sm8
      md6
    >
      ...
    </v-flex>
  </v-layout>
</template>

export default {
  data () {
    return {
      currentDate: this.$moment().format('YYYY-MM-DD')
    }
  },
  computed: {
    birthdayFormatted () {
      return this.formatBirthday(this.birthday)
    },
  },
  methods: {
    formatBirthday (date) {
      if (!date) {
        return null
      }
      const d = this.$moment(date).format('DD MMM YYYY')
      return d
    }
  }
}

For example, I have component A like that

Where do I put currentDate data, formatBirthday method and birthdayFormatted computed? So it can be read in other components

Did I put them in vuex store?

Body:
You can declare a Global Mixin on your vue app:

Vue.mixin({
    data () {
        return {
            currentDate: this.$moment().format('YYYY-MM-DD')
        }
    },
    computed: {
        birthdayFormatted () {
            return this.formatBirthday(this.birthday)
        },
    },
    methods: {
        formatBirthday (date) {
            if (!date) {
              return null
            }
            const d = this.$moment(date).format('DD MMM YYYY')
            return d
        }
    }
})

Then you can access to data, computed and method declared on each Vue component.


问:
Finding a element with a fake attribute that was added
I added a fake attribute to all my elements on the page, for example myId=100, each element has a different fake id.

Now i need to find an element according to the fake id, is this possible?

I tried doing

```<code>$("#myFrame").contents().find('a').each(function () {
    if ($(this).attr['myid'] === 100) {
        $(this).hide();
    }
});
</code>```

Any better ideas?

thank you

答:
$(this).attr['myid'] should be $(this).attr('myid') (attr is a function).

You can also use the attribute selector:

```<code>$("#myFrame").contents().find('a[myId="100"]').hide();
</code>```

You should avoid adding custom attributes to HTML elements. If you explain the problem we might be able to suggest a better way.

Body:
I added a fake attribute to all my elements on the page, for example myId=100, each element has a different fake id.

Now i need to find an element according to the fake id, is this possible?

I tried doing

$("#myFrame").contents().find('a').each(function () {
    if ($(this).attr['myid'] === 100) {
        $(this).hide();
    }
});

Any better ideas?

thank you

Body:
$(this).attr['myid'] should be $(this).attr('myid') (attr is a function).

You can also use the attribute selector:

$("#myFrame").contents().find('a[myId="100"]').hide();

You should avoid adding custom attributes to HTML elements. If you explain the problem we might be able to suggest a better way.


问:
Jenkins: Gerrit event trigger plugin
Need some help.
 Do we have any option to filter specific users for Gerrit event plugin.
currently its triggering for all which i don't want to  trigger for every one in the team. </p>

答:
You can't configure the Gerrit Trigger plugin to trigger only for some specific users but you can use a workaround to accomplish something like this.

When the job is triggered by Gerrit Trigger plugin some environment variables are automatically set. The more useful in your case are:

GERRIT_CHANGE_OWNER_NAME

GERRIT_CHANGE_OWNER_EMAIL

GERRIT_PATCHSET_UPLOADER_NAME

GERRIT_PATCHSET_UPLOADER_EMAIL

GERRIT_EVENT_ACCOUNT_NAME

GERRIT_EVENT_ACCOUNT_EMAIL

You can check some of these variables and abort the build if he/she isn't one of the specific users.

Title: Jenkins: Gerrit event trigger plugin


问:
Missing Argument for Parameter JSONDecoder URLSession with SwiftUI MVVM
I'm trying to learn how to use an API with SwiftUI using Combine and MVVM. I'm super new to this so this may seem like a dumb question but I've got my WebService and it seems to check out but my ViewModel is asking for stuff that I don't know if it should.

I'd like to be able to search for a game by it's name and it pull from the API.

Here's my Game.swift Model:

```<code>struct Game: Codable, Identifiable {
    let id: Int
    let name: String
}
</code>```

Simple enough.

Here's my handy WebService: GameService.swift

```<code>class GameService {
    func getGames(name: String, completion: @escaping (Game?) -> ()) {
        guard let url = URL(string: "https://api-v3.igdb.com/games/") else { return }

        var request = URLRequest(url: url)
        request.setValue("HIDDEN SO YOU CAN'T GET ME IN TROUBLE", forHTTPHeaderField: "user-key")
        request.httpBody = "fields id,name".data(using: .utf8, allowLossyConversion: false)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        URLSession.shared.dataTask(with: request) { data, response, error in

            guard let data = data, error == nil else {
                print("No data in response: \(error?.localizedDescription ?? "Unknown Error").")
                return
            }

            if let gameResponse = try? JSONDecoder().decode(Game.self, from: data) {
                print("Yay")
            } else {print("Shit")}

        }.resume()
    }
}

</code>```

I'm getting a yellow warning of Value 'gameResponse' was defined but never used... on if let gameResponse = try? JSON decoder blah blah blah.

Ok now the messy boy, I present GameViewModel.swift to you:

```<code>class GameViewModel: ObservableObject {

    private var gameService: GameService!

    @Published var game = Game()

    init() {
        self.gameService = GameService()
    }

    var gameName: String = ""

    func searchGames() {
        if let game = self.gameName.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
            getGames(by: name)
        }
    }

    private func getGames(by name: String) {
        self.gameService.getGames(name: name) { game in
            if let game = game {
                DispatchQueue.main.async {
                    self.game = game
                }
            }
        }
    }
}

</code>```

BIG QUESTION: The @Published var game = Game() is saying that there are is a missing parameter 'from' in call. I haven't implemented from anywhere.

The find searchGames() function is giving me an unresolved identifier error with getGames(by: name). Any ideas?

答:
Your call to Game() in GameViewModel references a constructor that does not exist since your struct does not have any default values.

To correctly initialize game, you must call the initializer with parameters:

```<code>Game(id: 1, name: "fred")
</code>```

The reference to the missing parameter "from" is due to the Codable protocol defining another constructor function:

```<code>init(from decoder: Decoder)
</code>```

and XCode is using this constructor as the default and being helpful by telling you that you need to supply the missing info.

getGames(by: name) requires a parameter called "name" which does not appear to be defined anywhere in the example you give.

Body:
I'm trying to learn how to use an API with SwiftUI using Combine and MVVM. I'm super new to this so this may seem like a dumb question but I've got my WebService and it seems to check out but my ViewModel is asking for stuff that I don't know if it should.

I'd like to be able to search for a game by it's name and it pull from the API.

Here's my Game.swift Model:

struct Game: Codable, Identifiable {
    let id: Int
    let name: String
}

Simple enough.

Here's my handy WebService: GameService.swift

class GameService {
    func getGames(name: String, completion: @escaping (Game?) -> ()) {
        guard let url = URL(string: "https://api-v3.igdb.com/games/") else { return }

        var request = URLRequest(url: url)
        request.setValue("HIDDEN SO YOU CAN'T GET ME IN TROUBLE", forHTTPHeaderField: "user-key")
        request.httpBody = "fields id,name".data(using: .utf8, allowLossyConversion: false)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        URLSession.shared.dataTask(with: request) { data, response, error in

            guard let data = data, error == nil else {
                print("No data in response: \(error?.localizedDescription ?? "Unknown Error").")
                return
            }

            if let gameResponse = try? JSONDecoder().decode(Game.self, from: data) {
                print("Yay")
            } else {print("Shit")}

        }.resume()
    }
}

I'm getting a yellow warning of Value 'gameResponse' was defined but never used... on if let gameResponse = try? JSON decoder blah blah blah.

Ok now the messy boy, I present GameViewModel.swift to you:

class GameViewModel: ObservableObject {

    private var gameService: GameService!

    @Published var game = Game()

    init() {
        self.gameService = GameService()
    }

    var gameName: String = ""

    func searchGames() {
        if let game = self.gameName.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
            getGames(by: name)
        }
    }

    private func getGames(by name: String) {
        self.gameService.getGames(name: name) { game in
            if let game = game {
                DispatchQueue.main.async {
                    self.game = game
                }
            }
        }
    }
}

BIG QUESTION: The @Published var game = Game() is saying that there are is a missing parameter 'from' in call. I haven't implemented from anywhere.

The find searchGames() function is giving me an unresolved identifier error with getGames(by: name). Any ideas?

Body:
Your call to Game() in GameViewModel references a constructor that does not exist since your struct does not have any default values.

To correctly initialize game, you must call the initializer with parameters:

Game(id: 1, name: "fred")

The reference to the missing parameter "from" is due to the Codable protocol defining another constructor function:

init(from decoder: Decoder)

and XCode is using this constructor as the default and being helpful by telling you that you need to supply the missing info.

getGames(by: name) requires a parameter called "name" which does not appear to be defined anywhere in the example you give.


问:
Should every part of a web app be a react component?
I haven't touched React in over 2 years, and a bit confused looking back at my old code. For example, if I were to build an instagram clone, would I utilize html templates and inject javascript as such as

```<code><div id="reactEntry">
    Loading ...
</div>
</code>```

for the login page, profile page, etc.
and use react components for main logic? for example, dynamically rendering posts and comments?

Or would it be smarter to make everything a react component-- login page, profile page, etc.

答:
would it be smarter to make everything a react component-- login page, profile page, etc. - yes. As you don't need to rely much on other libraries and can use routing between pages. Also, there is performance benefit for a fully react app.
Having other components along with react component would not cause any harm as long as you don't dom manipulate the react component.</p>

Body:
I haven't touched React in over 2 years, and a bit confused looking back at my old code. For example, if I were to build an instagram clone, would I utilize html templates and inject javascript as such as

    Loading ...

for the login page, profile page, etc.
and use react components for main logic? for example, dynamically rendering posts and comments?

Or would it be smarter to make everything a react component-- login page, profile page, etc.


问:
I want to combine a list of tuples in python
I have a list of tuples of x and y coordinates such as:
[(1,2), (3,4), (5,6)]
and I want to manipulate the list to become a 2xN matrix(depending on how many numbers) so that I have a list of just the x coordinates and then the y coordinates. Basically I want to output:
[(1,3,5), (2,4,6)]
through a function, but am not exactly sure how to do so.</p>

答:
list(zip(*[(1, 2), (3, 4), (5, 6)]))
```

<p>will output:</p>

```[(1, 3, 5), (2, 4, 6)]
```

<hr>

<pre class="lang-py prettyprint-override"><code>>>> a = [(1, 2), (3, 4), (5, 6)]

>>> zip(*a) # Returns a zipped object.
<zip object at 0x10c9f5540>

>>> print(*a) # "Star a" unpacks the list.
(1, 2) (3, 4) (5, 6)

>>> print(a[0], a[1], a[2]) # Above is equivalent to:
(1, 2) (3, 4) (5, 6)

>>> b, c = [1, 2], [3, 4]

>>> list(zip(b, c))
[(1, 3), (2, 4)] # Zips the inputs of both lists in the pattern (b1, c1) and (b2, c2). list() converts the "zip" generator to a list.

>>> list(zip(*a))
[(1, 3, 5), (2, 4, 6)] # Zips the wanted ints with the logic above.
</code>```

Body:
list(zip(*[(1, 2), (3, 4), (5, 6)]))

will output:

[(1, 3, 5), (2, 4, 6)]

>>> a = [(1, 2), (3, 4), (5, 6)]

>>> zip(*a) # Returns a zipped object.
<zip object at 0x10c9f5540>

>>> print(*a) # "Star a" unpacks the list.
(1, 2) (3, 4) (5, 6)

>>> print(a[0], a[1], a[2]) # Above is equivalent to:
(1, 2) (3, 4) (5, 6)

>>> b, c = [1, 2], [3, 4]

>>> list(zip(b, c))
[(1, 3), (2, 4)] # Zips the inputs of both lists in the pattern (b1, c1) and (b2, c2). list() converts the "zip" generator to a list.

>>> list(zip(*a))
[(1, 3, 5), (2, 4, 6)] # Zips the wanted ints with the logic above.


问:
Take input from user between 1-10 five times and store them in an array, if wrong input given then prompt for correct input
I am looping five times and taking user inputs using util.Scanner, I am stuck with the part where I have to prompt user for correct input, and when the correct input is given and is to be stored in the array. Then the loop continues.</p>

```<code>while(a<5){
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter the value: ");
        int x = input.nextInt();
        //what code should be added here to prompt user if input is not in 1-10
        //and after checking only, the value should be stored in the array
        userInputs[a] = x;

        a++;
    }
</code>```

答:
First, ask the user for an input and based on that you loop and take input using scanner.

```<code>Scanner input= new Scanner(System.in);
System.out.println("Enter Five Numbers");
</code>```

The looping part:

```<code>    int num;
    int [] arr= new int[5];
    for(int i=0; i<arr.length(); i++)
    {
        System.out.println("Enter Input "+i);
        number=input.nextInt();
        TakeInput ti= new TakeInput();
        if(ti.validate_input(number)==true) arr[i]=number;
        else{
            System.out.println("Enter Number "+i+" Again");
            number=input.nextInt();
        }
    }
</code>```

Body:
I am looping five times and taking user inputs using util.Scanner, I am stuck with the part where I have to prompt user for correct input, and when the correct input is given and is to be stored in the array. Then the loop continues.

while(a<5){
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter the value: ");
        int x = input.nextInt();
        //what code should be added here to prompt user if input is not in 1-10
        //and after checking only, the value should be stored in the array
        userInputs[a] = x;

        a++;
    }

Body:
First, ask the user for an input and based on that you loop and take input using scanner.

Scanner input= new Scanner(System.in);
System.out.println("Enter Five Numbers");

The looping part:

    int num;
    int [] arr= new int[5];
    for(int i=0; i<arr.length(); i++)
    {
        System.out.println("Enter Input "+i);
        number=input.nextInt();
        TakeInput ti= new TakeInput();
        if(ti.validate_input(number)==true) arr[i]=number;
        else{
            System.out.println("Enter Number "+i+" Again");
            number=input.nextInt();
        }
    }


问:
How to stop centered changing text from moving
Recently I have downloaded a text rotator plugin. Works great but there is a small issue with it. Every time it changes text the whole heading moves becuse it's centered.

A simple example here: (Don't mind the js code, It's just a simplified example of the plugin)

HTML

```<code><h1>
Heading <span class="change">Change</span>
</h1>
</code>```

CSS

```<code>h1 {
  text-align: center;
}
</code>```

JS

```<code>var itr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var  interval = 1000; //one second
itr.forEach((itr, index) => {
setTimeout(() => {
    $('.change').text('Car');
            setTimeout(() => {
            $('.change').text('Boat');
                    setTimeout(() => {
                    $('.change').text('Helicopter');
                    }, index * interval
                   );
          }, index * interval
         );
  }, index * interval
 );
})
</code>```

You can try it here: https://jsfiddle.net/teku3a0w/1/

Is there a way to stop the heading from moving when it changes?

Permanent margin would definitely be an answer but i want it to be responsive.

答:
here are the changes I made to the HTML and CSS:

HTML:

```<code><h1>
  <span>Heading</span>
  <span style = 'padding-left: 6px' class="change">Change</span>
</h1>
</code>```

CSS:

```<code>h1 {
  display: flex;
  justify-content: center;
  width: 400px;
  margin: 0 auto;
  flex-direction: column;
  align-items: center;
}

@media screen and (min-width: 768px) {
  h1 {
    flex-direction: row;
    justify-content: center;
  }

  span.change {
    width: 150px
  }
}
</code>```

These are fixed widths, so this solution isn't really that flexible. But you might have a better time putting the longest word to be displayed first, grabbing that width, and setting the width of span.change to be a little bigger than that.

I set my media query to 768px since that's a good size to start considering tablet-sized screens and above.

This approach might not be the best solution, but it's still something :)

Body:
Recently I have downloaded a text rotator plugin. Works great but there is a small issue with it. Every time it changes text the whole heading moves becuse it's centered.

A simple example here: (Don't mind the js code, It's just a simplified example of the plugin)

HTML

Heading Change

CSS

h1 {
  text-align: center;
}

JS

var itr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var  interval = 1000; //one second
itr.forEach((itr, index) => {
setTimeout(() => {
    $('.change').text('Car');
            setTimeout(() => {
            $('.change').text('Boat');
                    setTimeout(() => {
                    $('.change').text('Helicopter');
                    }, index * interval
                   );
          }, index * interval
         );
  }, index * interval
 );
})

You can try it here: https://jsfiddle.net/teku3a0w/1/

Is there a way to stop the heading from moving when it changes?

Permanent margin would definitely be an answer but i want it to be responsive.

Body:
here are the changes I made to the HTML and CSS:

HTML:

<h1>
  <span>Heading</span>
  <span style = 'padding-left: 6px' class="change">Change</span>
</h1>

CSS:

h1 {
  display: flex;
  justify-content: center;
  width: 400px;
  margin: 0 auto;
  flex-direction: column;
  align-items: center;
}

@media screen and (min-width: 768px) {
  h1 {
    flex-direction: row;
    justify-content: center;
  }

  span.change {
    width: 150px
  }
}

These are fixed widths, so this solution isn't really that flexible. But you might have a better time putting the longest word to be displayed first, grabbing that width, and setting the width of span.change to be a little bigger than that.

I set my media query to 768px since that's a good size to start considering tablet-sized screens and above.

This approach might not be the best solution, but it's still something :)