问:
How to install tool in alpine docker
I want to install some tools from linux in dockerfile

```<code>FROM python:2.7

COPY . /app

WORKDIR /app

RUN pip install --no-cache-dir -r requirements.txt

RUN apt-get update

RUN apt-get install -y dnsutils

CMD ["python","test.py"]
</code>```

I want to use python2.7-alpine in docker file.

I have used this code to install dnsutils but the result show failed

```<code>RUN apk update && \
    apk add --virtual build-deps gcc python-dev musl-dev && \
    apk add postgresql-dev
</code>```

I want to install dnsutils tool and python2.7-alpine

答:
you can change the Dockerfile as follows

```<code>FROM alpine:3.9

RUN apk add --no-cache python && \
    python -m ensurepip && \
    rm -r /usr/lib/python*/ensurepip && \
    pip install --upgrade pip setuptools && \
    rm -r /root/.cache
</code>```

For more information on the image you can follow: https://hub.docker.com/r/frolvlad/alpine-python2/dockerfile

To install dnsutils install bind-tools. Use the below code

```<code>FROM alpine:3.9

MAINTAINER QuangVu

COPY . /app

WORKDIR /app

RUN apk add --no-cache python && \
    python -m ensurepip && \
    rm -r /usr/lib/python*/ensurepip && \
    pip install --upgrade pip setuptools && \
    rm -r /root/.cache

#RUN pip install --no-cache-dir -r requirements.txt

RUN apk add --update --no-cache bind-tools

CMD ["python","test.py"]
</code>```

Title: How to install tool in alpine docker

Body:
I want to install some tools from linux in dockerfile

FROM python:2.7

COPY . /app

WORKDIR /app

RUN pip install --no-cache-dir -r requirements.txt

RUN apt-get update

RUN apt-get install -y dnsutils

CMD ["python","test.py"]

I want to use python2.7-alpine in docker file.

I have used this code to install dnsutils but the result show failed

RUN apk update && \
    apk add --virtual build-deps gcc python-dev musl-dev && \
    apk add postgresql-dev

I want to install dnsutils tool and python2.7-alpine

Body:
you can change the Dockerfile as follows

FROM alpine:3.9

RUN apk add --no-cache python && \
    python -m ensurepip && \
    rm -r /usr/lib/python*/ensurepip && \
    pip install --upgrade pip setuptools && \
    rm -r /root/.cache

For more information on the image you can follow: https://hub.docker.com/r/frolvlad/alpine-python2/dockerfile

To install dnsutils install bind-tools. Use the below code

FROM alpine:3.9

MAINTAINER QuangVu

COPY . /app

WORKDIR /app

RUN apk add --no-cache python && \
    python -m ensurepip && \
    rm -r /usr/lib/python*/ensurepip && \
    pip install --upgrade pip setuptools && \
    rm -r /root/.cache

#RUN pip install --no-cache-dir -r requirements.txt

RUN apk add --update --no-cache bind-tools

CMD ["python","test.py"]


来源: stackexchange

问:
How can I create a struct in julia?
I am trying to create a structure, txn:

a)

struct txn
    txn_id::Int64
    bank::Char[20]
    branch::Char[20]
    teller::Char[20]
    customer::Char[20]
    account::Char[34]
    timestamp::DateTime
    dr_cr::Char[2]
    amount::Int64
end
```
<p>gives</p>
<blockquote>
<p>Error: TypeError: in txn, in type definition, expected Type, got  Array{Char, 1}</p>
</blockquote>
<p>b)</p>
<pre class="lang-none prettyprint-override"><code>struct txn
    txn_id::Int64
    bank::Char(20)
    branch::Char(20)
    teller::Char(20)
    customer::Char(20)
    account::Char(34)
    timestamp::DateTime
    dr_cr::Char(2)
    amount::Int64
end
</code>```

gives

Error: TypeError: in txn, in type definition, expected Type, got Char

How can I create the struct in Julia?

答:
In Julia, an array of Chars is not equivalent to a String. The syntax Char(80) creates a single character:

```<code>julia> Char(80)
'P': ASCII/Unicode U+0050 (category Lu: Letter, uppercase)
</code>```

And the syntax Char[80, 81, 82] creates an array of Chars:

```<code>julia> Char[80, 81, 82]
3-element Array{Char,1}:
 'P'
 'Q'
 'R'
</code>```

We can see that an array of characters is not equivalent to a string (note that characters can also be represented using single quotes):

```<code>julia> ['a', 'b', 'c'] == "abc"
false
</code>```

Try defining the string fields in your struct using the String type:

```<code>julia> struct Person
           name::String
       end

julia> p = Person("Bob")
Person("Bob")
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can I create a struct in julia?

Body:
I am trying to create a structure, txn:

a)

struct txn
    txn_id::Int64
    bank::Char[20]
    branch::Char[20]
    teller::Char[20]
    customer::Char[20]
    account::Char[34]
    timestamp::DateTime
    dr_cr::Char[2]
    amount::Int64
end

gives

Error: TypeError: in txn, in type definition, expected Type, got  Array{Char, 1}

b)

struct txn
    txn_id::Int64
    bank::Char(20)
    branch::Char(20)
    teller::Char(20)
    customer::Char(20)
    account::Char(34)
    timestamp::DateTime
    dr_cr::Char(2)
    amount::Int64
end

gives

Error: TypeError: in txn, in type definition, expected Type, got Char

How can I create the struct in Julia?

Body:
In Julia, an array of Chars is not equivalent to a String. The syntax Char(80) creates a single character:

julia> Char(80)
'P': ASCII/Unicode U+0050 (category Lu: Letter, uppercase)

And the syntax Char[80, 81, 82] creates an array of Chars:

julia> Char[80, 81, 82]
3-element Array{Char,1}:
 'P'
 'Q'
 'R'

We can see that an array of characters is not equivalent to a string (note that characters can also be represented using single quotes):

julia> ['a', 'b', 'c'] == "abc"
false

Try defining the string fields in your struct using the String type:

julia> struct Person
           name::String
       end

julia> p = Person("Bob")
Person("Bob")


问:
In Java how do I initialize elements in array in several lines, not one?
Hello this is a very simple question but I don't know the answer.
I just want to know how to initialize every element of an array in several lines, because I know how to do it in one line.

My code of initializing them on one line is this way:

```<code>String input = scanner.nextLine();

String[] array = input.split("\\s+");
</code>```

答:
Using an ArrayList</p>

```<code>String s = "Too Many\nLines Here\nNo its only three";
Scanner scanner = new Scanner(s);
List<String> array = new ArrayList<>(Arrays.asList(scanner.nextLine().split("\\s+")));
//to add next line
array.addAll(Arrays.asList(scanner.nextLine().split("\\s+")));
//.. and so on
</code>```

Body:
Hello this is a very simple question but I don't know the answer.
I just want to know how to initialize every element of an array in several lines, because I know how to do it in one line.

My code of initializing them on one line is this way:

String input = scanner.nextLine();

String[] array = input.split("\\s+");

Body:
Using an ArrayList

String s = "Too Many\nLines Here\nNo its only three";
Scanner scanner = new Scanner(s);
List<String> array = new ArrayList<>(Arrays.asList(scanner.nextLine().split("\\s+")));
//to add next line
array.addAll(Arrays.asList(scanner.nextLine().split("\\s+")));
//.. and so on


问:
how to reset a div to its original style with javascript
I am trying to "reset" box after several changes to its original state in javascript. I have used several addEventListener methods to change the appearance of a box in HTML, but am having trouble using a "reset" button to revert the box to its original appearance.</p>

```<code>document.getElementById('button1').addEventListener('click', function(){

  document.getElementById('box').style.height = '250px';

});

document.getElementById('button2').addEventListener('click', function(){

  document.getElementById('box').style.background = 'blue';

});

document.getElementById('button3').addEventListener('click', function(){

  document.getElementById('box').style.opacity = '0.1';

});

// This is where i need to reset the box

document.getElementById('button4').addEventListener('click', function(){
</code>```

答:
If all your styles are going to be appended inline as above, I would just use setAttribute on the element in question to remove all the styles:

document.getElementById('box').setAttribute('style', '');

Though, as another user has mentioned, adding and removing classes is probably a preferable way to do this for maintainability and readability.

Body:
I am trying to "reset" box after several changes to its original state in javascript. I have used several addEventListener methods to change the appearance of a box in HTML, but am having trouble using a "reset" button to revert the box to its original appearance.

document.getElementById('button1').addEventListener('click', function(){

  document.getElementById('box').style.height = '250px';

});

document.getElementById('button2').addEventListener('click', function(){

  document.getElementById('box').style.background = 'blue';

});

document.getElementById('button3').addEventListener('click', function(){

  document.getElementById('box').style.opacity = '0.1';

});

// This is where i need to reset the box

document.getElementById('button4').addEventListener('click', function(){


问:
MYSQL How to grant all privileges to user only to the databases which he created?
im creating a few users:
user1
user2
user3
i want to give them ALL PRIVILEGES to the bases(creating/removing) inside their account
i want them to see and affect databases only inside their account...
how should i do this with shell ?</p>

答:
Do you allow users to run CREATE DATABASE ...?

Don't allow a user to run that SQL.  Instead, provide a STORED PROCEDURE to create the database for him and provide permissions to him.  The trick is to be root when you define the SP and use SQL SECURITY DEFINER.  And have GRANT ALL PRIVILEGES ON dbname.* TO user@...  (with the pieces suitably filled in).


问:
PHP/MySQL If FROM Statements
sorry for the extremely basic question!! I'm very new to PHP/MySQL

How would it be possible to do an if statement referencing wherever or not data was from a certain table.

Would this work?

```<code>if ( $search FROM "table2" )
{
function for table2.. etc
}
</code>```

TABLE:INSTRUMENTS

COLUMNS:

```<code> id   instrument    grade   standard    comments
      instrument2   grade2  standard2   comments2
      instrument3   grade3  standard3   comments3
      instrument4   grade4  standard4   comments4
      instrument5   grade5  standard5   comments5
</code>```

TABLE: PEOPLE

COLUMNS:

```<code>id  first  last  snumber  course  email  graduate  inumber
</code>```

Basically a person from the PEOPLE table is linked via ID to instruments in the INSTRUMENTS table, I have an e-mail search function that I need to send out the relative data to the relative instruments.

I want to get the comments[i] , grade[i], standard[i] of the matching instrument[i]

答:
Hmm,

The tables need a redesign IMHO.

I would change table instruments to.

```<code>id, people_id, instrument, grade, standard, comments
</code>```

This query:

```<code>SELECT
  people.email
  ,instruments.instrument
  ,instruments.grade
  ,instruments.standard
  ,instruments.comment
FROM people
INNER JOIN instruments ON (instruments.people_id = people.id)
WHERE people.id = 10
</code>```

Will give you all instruments for person number 10.
You can change the where clause to where people.snumber = x or whatever you feel like.

Or add extra clauses to limit the number of instruments by adding something like : AND instrument.grade > 7 at the end

With this setup people can have any number of instruments.

It feels a bit odd to -reverse link- the instruments to people like this, but believe me... it works.

I recommend reading up on joins (google 'mysql join') and always use explicit joins using the join keyword, it makes understanding your queries much easier.

If this is the result you where looking for, then you can drop the inumber field from the people table, since we moved the link between people and instruments to the instrument table.

On an 1-to-many link the linking field should always be on the 'many'-table.

ContentLicense: CC BY-SA 3.0

Title: PHP/MySQL If FROM Statements

Body:
sorry for the extremely basic question!! I'm very new to PHP/MySQL

How would it be possible to do an if statement referencing wherever or not data was from a certain table.

Would this work?

if ( $search FROM "table2" )
{
function for table2.. etc
}

TABLE:INSTRUMENTS

COLUMNS:

 id   instrument    grade   standard    comments
      instrument2   grade2  standard2   comments2
      instrument3   grade3  standard3   comments3
      instrument4   grade4  standard4   comments4
      instrument5   grade5  standard5   comments5

TABLE: PEOPLE

COLUMNS:

id  first  last  snumber  course  email  graduate  inumber

Basically a person from the PEOPLE table is linked via ID to instruments in the INSTRUMENTS table, I have an e-mail search function that I need to send out the relative data to the relative instruments.

I want to get the comments[i] , grade[i], standard[i] of the matching instrument[i]

Body:
Hmm,

The tables need a redesign IMHO.

I would change table instruments to.

id, people_id, instrument, grade, standard, comments

This query:

SELECT
  people.email
  ,instruments.instrument
  ,instruments.grade
  ,instruments.standard
  ,instruments.comment
FROM people
INNER JOIN instruments ON (instruments.people_id = people.id)
WHERE people.id = 10

Will give you all instruments for person number 10.
You can change the where clause to where people.snumber = x or whatever you feel like.

Or add extra clauses to limit the number of instruments by adding something like : AND instrument.grade > 7 at the end

With this setup people can have any number of instruments.

It feels a bit odd to -reverse link- the instruments to people like this, but believe me... it works.

I recommend reading up on joins (google 'mysql join') and always use explicit joins using the join keyword, it makes understanding your queries much easier.

If this is the result you where looking for, then you can drop the inumber field from the people table, since we moved the link between people and instruments to the instrument table.

On an 1-to-many link the linking field should always be on the 'many'-table.


问:
How do I stop partial-refresh from removing paragraph breaks in the Wordpress Customizer live preview?
I have added my own settings to the Wordpress customizer and set it up so that it live previews using the "postMessage" method. It is working almost perfectly apart from when I edit a field linked to paragraph text, the preview doesn't show line breaks in the paragraphs. However this is temporary, once the customizer is closed or the page is refreshed the paragraph gaps come back.

I am defining the Customizer sections in the customizer.php using the following code:

```<code>// About Section Text
$wp_customize->add_setting( 'about__text' , array(
    'default'   => 'Lorem ipsum dolor sit amet consectetur, adipisicing elit. Blanditiis, odit unde magnam dolores quasi voluptas, impedit a nam inventore atque eaque nobis possimus officiis deleniti quisquam animi deserunt ad ipsa sapiente illo?',
    'transport' => 'postMessage',
) );

// About Section Text (CONTROL)
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'about__text', array(
    'label'      => __( 'About Section Content:', 'mytheme' ),
    'section'    => 'edit__homepage--section',
    'settings'   => 'about__text',
    'priority'   => 3,
    'type'       => 'textarea'
) ) );
</code>```

I am displaying the above theme mod in my index.php file using the following code:

```<code>    <div class="about__text">
      <?php echo wpautop(get_theme_mod('about__text')); ?>
    </div>
</code>```

Here's my jquery:

```<code>( function( $ ) {
    wp.customize( 'about__text', function( value ) {
        value.bind( function( newVal ) {
            $( '.about__text' ).html( newVal );
        } );
    } );
} )( jQuery );
</code>```

I've tried experimenting with different jquery objects such as text() and contents() but these either have the same issue or don't work at all.

Doe anyone know if there's a way I can get the javascript preview to honour the paragraph styles? Maybe like a javascript version of wpautop()  ?

答:
You can use selective refresh like this. Values are rendered server side so no need to extra JS. And since only selected wrapper element is refresh, it is more efficient than full page reload in Customizer. In the following example content only in .about__text is refreshed. Since rendering is done server side, no need to look for JS alternative of wpautop function. I believe this would be one alternative for your problem mentioned in the question.

```<code>function wpso_customize_register( $wp_customize ) {
    $wp_customize->selective_refresh->add_partial(
        'about__text',
        array(
            'selector'        => '.about__text',
            'render_callback' => function(){
                echo wp_kses_post( wpautop( get_theme_mod('about__text') ) );
            },
        )
    );
}
add_action( 'customize_register', 'wpso_customize_register' );
</code>```

Body:
I have added my own settings to the Wordpress customizer and set it up so that it live previews using the "postMessage" method. It is working almost perfectly apart from when I edit a field linked to paragraph text, the preview doesn't show line breaks in the paragraphs. However this is temporary, once the customizer is closed or the page is refreshed the paragraph gaps come back.

I am defining the Customizer sections in the customizer.php using the following code:

// About Section Text
$wp_customize->add_setting( 'about__text' , array(
    'default'   => 'Lorem ipsum dolor sit amet consectetur, adipisicing elit. Blanditiis, odit unde magnam dolores quasi voluptas, impedit a nam inventore atque eaque nobis possimus officiis deleniti quisquam animi deserunt ad ipsa sapiente illo?',
    'transport' => 'postMessage',
) );

// About Section Text (CONTROL)
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'about__text', array(
    'label'      => __( 'About Section Content:', 'mytheme' ),
    'section'    => 'edit__homepage--section',
    'settings'   => 'about__text',
    'priority'   => 3,
    'type'       => 'textarea'
) ) );

I am displaying the above theme mod in my index.php file using the following code:

      <?php echo wpautop(get_theme_mod('about__text')); ?>

Here's my jquery:

( function( $ ) {
    wp.customize( 'about__text', function( value ) {
        value.bind( function( newVal ) {
            $( '.about__text' ).html( newVal );
        } );
    } );
} )( jQuery );

I've tried experimenting with different jquery objects such as text() and contents() but these either have the same issue or don't work at all.

Doe anyone know if there's a way I can get the javascript preview to honour the paragraph styles? Maybe like a javascript version of wpautop()  ?

Body:
You can use selective refresh like this. Values are rendered server side so no need to extra JS. And since only selected wrapper element is refresh, it is more efficient than full page reload in Customizer. In the following example content only in .about__text is refreshed. Since rendering is done server side, no need to look for JS alternative of wpautop function. I believe this would be one alternative for your problem mentioned in the question.

function wpso_customize_register( $wp_customize ) {
    $wp_customize->selective_refresh->add_partial(
        'about__text',
        array(
            'selector'        => '.about__text',
            'render_callback' => function(){
                echo wp_kses_post( wpautop( get_theme_mod('about__text') ) );
            },
        )
    );
}
add_action( 'customize_register', 'wpso_customize_register' );


问:
Getting XML value from attribute dispatchState with python and request
I'm doing a request to splunk for jobs using:

```<code> response = requests.post('https://xxxx.net:8089/services/search/jobs/' + job_id, auth=(splunk_user, splunk_pass), verify=False)
</code>```

Now i look at the output using print(response.text). I want to be able to print just the value of <s:key name="dispatchState">DONE</s:key> and see if it's "DONE" or whatever the value is.

答:
Solution 1

Since the output format is in xml you can parse the xml using python's lxml module as shown below.

```<code>import lxml.etree as et
root = et.fromstring(response.text)
done_state = root.xpath("//s:key[@name='dispatchState']/text()", root.nsmap)[0]
</code>```

You can install lxml using pip

```<code>pip install lxml
</code>```

You can find the further documentation and tutorials here.

Solution 2

If the structure is constant you can use simple regular expression to get the required information:

```<code>import re
match = re.search('<s:key name\="dispatchState">(.*?)</s:key>', response.text)
result = match.group(1)
</code>```

You can get more information about regular expressions here.

Body:
I'm doing a request to splunk for jobs using:

 response = requests.post('https://xxxx.net:8089/services/search/jobs/' + job_id, auth=(splunk_user, splunk_pass), verify=False)

Now i look at the output using print(response.text). I want to be able to print just the value of <s:key name="dispatchState">DONE</s:key> and see if it's "DONE" or whatever the value is.

Body:
Solution 1

Since the output format is in xml you can parse the xml using python's lxml module as shown below.

import lxml.etree as et
root = et.fromstring(response.text)
done_state = root.xpath("//s:key[@name='dispatchState']/text()", root.nsmap)[0]

You can install lxml using pip

pip install lxml

You can find the further documentation and tutorials here.

Solution 2

If the structure is constant you can use simple regular expression to get the required information:

import re
match = re.search('<s:key name\="dispatchState">(.*?)</s:key>', response.text)
result = match.group(1)

You can get more information about regular expressions here.


问:
How to make C++ client trust all X.509 certificates without any verification (like in Java)
What is the grpc C++ equivalent of Java's InsecureTrustManagerFactory ?

GrpcSslContexts.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()

an insecure TrustManagerFactory that trusts all X.509 certificates without any verification.

In other words - in Java I create a server (private.key + certificate.pem signed by rootCA) and a client that creates SSL-encrypted channel with the server accepting server's certificate without verification (rootCA.pem is not available for the client). Technically it's not recommended but I use it for testing purposes only. I need to do the same for my C++ version of server-client pair. So far my C++ client needs rootCA.pem either through SslCredentialsOptions:

```<code>    grpc::SslCredentialsOptions sslChannelOptions;
    sslChannelOptions.pem_root_certs  = "rootCA.pem";
    sslChannelOptions.pem_cert_chain  = "";
    sslChannelOptions.pem_private_key = "";
    return grpc::SslCredentials( sslChannelOptions );
</code>```

or through

gpr_setenv("GRPC_DEFAULT_SSL_ROOTS_FILE_PATH", "roots.pem")

Otherwise I get:

ssl_transport_security.c:921] Handshake failed with fatal error SSL_ERROR_SSL: error:0400006b:RSA routines:OPENSSL_internal:BLOCK_TYPE_IS_NOT_01.

答:
Unfortunately, gRPC C++ does not support this feature. gRPC C++ only has options to not verify client's certificate but not server's certificate.

Your use case does not seem strong enough for us to support this feature.

Body:
What is the grpc C++ equivalent of Java's InsecureTrustManagerFactory ?

GrpcSslContexts.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()

an insecure TrustManagerFactory that trusts all X.509 certificates without any verification.

In other words - in Java I create a server (private.key + certificate.pem signed by rootCA) and a client that creates SSL-encrypted channel with the server accepting server's certificate without verification (rootCA.pem is not available for the client). Technically it's not recommended but I use it for testing purposes only. I need to do the same for my C++ version of server-client pair. So far my C++ client needs rootCA.pem either through SslCredentialsOptions:

    grpc::SslCredentialsOptions sslChannelOptions;
    sslChannelOptions.pem_root_certs  = "rootCA.pem";
    sslChannelOptions.pem_cert_chain  = "";
    sslChannelOptions.pem_private_key = "";
    return grpc::SslCredentials( sslChannelOptions );

or through

gpr_setenv("GRPC_DEFAULT_SSL_ROOTS_FILE_PATH", "roots.pem")

Otherwise I get:

ssl_transport_security.c:921] Handshake failed with fatal error SSL_ERROR_SSL: error:0400006b:RSA routines:OPENSSL_internal:BLOCK_TYPE_IS_NOT_01.


问:
Why won't matplotlib draw work in pycharm?
I want to refresh a plot each time a long loop cycles. From my googling the best option seems to be using plt.draw() in the loop, rather than the animation module of matplotlib, because I only want it to update when new data becomes available.

However plt.draw() won't work in pycharm, even though it does work in the same interpreter when I run via an external shell. I don't even get an empty matplotlib window. I've tried with and without interactive mode.

Matplotlib version 3.1.0

Python version 3.6.5

Pycharm 2018.1.1

Below is some code from another post that works as expected outside of pycharm, but in pycharm I just get exit code 0, not even an error.

import matplotlib.pyplot as plt
import numpy as np
# import matplotlib
#
# print(matplotlib.get_backend())

for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()
```

Expect a sequence of random graphs, get nothing but exit code 0

答:
You can use show() with blocking set to false.

```<code>for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    if i <1:
        plt.show(block=False)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()
</code>```

Body:
I want to refresh a plot each time a long loop cycles. From my googling the best option seems to be using plt.draw() in the loop, rather than the animation module of matplotlib, because I only want it to update when new data becomes available.

However plt.draw() won't work in pycharm, even though it does work in the same interpreter when I run via an external shell. I don't even get an empty matplotlib window. I've tried with and without interactive mode.

Matplotlib version 3.1.0

Python version 3.6.5

Pycharm 2018.1.1

Below is some code from another post that works as expected outside of pycharm, but in pycharm I just get exit code 0, not even an error.

import matplotlib.pyplot as plt
import numpy as np
# import matplotlib
#
# print(matplotlib.get_backend())

for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()

Expect a sequence of random graphs, get nothing but exit code 0

Body:
You can use show() with blocking set to false.

for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    if i <1:
        plt.show(block=False)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()


问:
Unable to connect JIRA Cloud
I installed JIRA Cloud for sheet add-on. While connecting with JIRA instead of connecting using Atlassian account I used the google account and thus not get authenticated and got this error message.

Now the problem is, even if I try the the same again and wants to use Atlassian account, its still throwing the same error and not allowng me use Atlassian account. Cleared cache, reinstall JIRA Cloud for sheet add-on but no luck.

Any idea?

答:
I doubt you are still logged in with your google account into the Atlassian cloud Jira.
Wonder how? Can you try opening id.atlassian.com? At the very left bottom corner, click on your profile pic and logout. Login again with your correct id and password and you should be able to use your Jira cloud as usual.

Remember, when you login into any Atlassian Cloud instance you actually login into id.atlassian.com account which is used for authentication by all other atlassian cloud sites. To logout completely, change account login you need to go to id.atlassian.com.

I hope this helps you.

Title: Unable to connect JIRA Cloud


问:
What method of checking than setting a value is most optimal?
This is my first post on stack overflow after being a programmer for 7 years... and I have a pretty stupid question. What is more efficient between these two? Does the C++ or C# compiler automatically optimize it and if so what does it change to?

if(a) b=a

if(a) b=true
```

答:
In C# in Release Mode, they both compile to the same IL

```<code>.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig
        instance void M (
            bool a
        ) cil managed
    {
        // Method begins at RVA 0x2050
        // Code size 3 (0x3)
        .maxstack 8

        IL_0000: ldarg.1
        IL_0001: pop
        IL_0002: ret
    } // end of method C::M

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Method begins at RVA 0x2054
        // Code size 7 (0x7)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [mscorlib]System.Object::.ctor()
        IL_0006: ret
    } // end of method C::.ctor

} // end of class C
</code>```

In Debug Configuration, you have a minor difference between b==a one (removing the noise); see IL_0006 line.

```<code>// Methods
.method public hidebysig
    instance void M (
        bool a
    ) cil managed
{
    // Method begins at RVA 0x2050
    // Code size 9 (0x9)
    .maxstack 1
    .locals init (
        [0] bool,
        [1] bool
    )

    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: stloc.1
    // sequence point: hidden
    IL_0003: ldloc.1
    IL_0004: brfalse.s IL_0008

    IL_0006: ldarg.1
    IL_0007: stloc.0

    IL_0008: ret
} // end of method C::M
</code>```

and the b==true version

```<code>// Methods
.method public hidebysig
    instance void M (
        bool a
    ) cil managed
{
    // Method begins at RVA 0x2050
    // Code size 9 (0x9)
    .maxstack 1
    .locals init (
        [0] bool,
        [1] bool
    )

    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: stloc.1
    // sequence point: hidden
    IL_0003: ldloc.1
    IL_0004: brfalse.s IL_0008

    IL_0006: ldc.i4.1
    IL_0007: stloc.0

    IL_0008: ret
} // end of method C::M
</code>```

In practice, I would want to have benchmarked your exact usagebefore worrying about this sort of micro-optimisation. It is unlikely to be the best value for your time spent in optimisation efforts.

Body:
In C# in Release Mode, they both compile to the same IL

.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig
        instance void M (
            bool a
        ) cil managed
    {
        // Method begins at RVA 0x2050
        // Code size 3 (0x3)
        .maxstack 8

        IL_0000: ldarg.1
        IL_0001: pop
        IL_0002: ret
    } // end of method C::M

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Method begins at RVA 0x2054
        // Code size 7 (0x7)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [mscorlib]System.Object::.ctor()
        IL_0006: ret
    } // end of method C::.ctor

} // end of class C

In Debug Configuration, you have a minor difference between b==a one (removing the noise); see IL_0006 line.

// Methods
.method public hidebysig
    instance void M (
        bool a
    ) cil managed
{
    // Method begins at RVA 0x2050
    // Code size 9 (0x9)
    .maxstack 1
    .locals init (
        [0] bool,
        [1] bool
    )

    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: stloc.1
    // sequence point: hidden
    IL_0003: ldloc.1
    IL_0004: brfalse.s IL_0008

    IL_0006: ldarg.1
    IL_0007: stloc.0

    IL_0008: ret
} // end of method C::M

and the b==true version

// Methods
.method public hidebysig
    instance void M (
        bool a
    ) cil managed
{
    // Method begins at RVA 0x2050
    // Code size 9 (0x9)
    .maxstack 1
    .locals init (
        [0] bool,
        [1] bool
    )

    IL_0000: nop
    IL_0001: ldarg.1
    IL_0002: stloc.1
    // sequence point: hidden
    IL_0003: ldloc.1
    IL_0004: brfalse.s IL_0008

    IL_0006: ldc.i4.1
    IL_0007: stloc.0

    IL_0008: ret
} // end of method C::M

In practice, I would want to have benchmarked your exact usagebefore worrying about this sort of micro-optimisation. It is unlikely to be the best value for your time spent in optimisation efforts.


问:
Check for value changes in variable
I have 2 components in my angular app. Component A is a header and component B sets a value that I need in component A. The problem is that component A is getting set before B so the value that I need is not being displayed when I need it. If I refresh my browser then it shows. My code will explain better.

Component A

```<code>  offerExpiry: any;

  constructor(
    public expiry: ExploreOfferService
  ) {

  }
  ngOnChanges() {
    this.expiry.event.subscribe((data) => {
      this.offerExpiry = data;
    });
  }

  <div class="col-5 right">
    <div>
      <span *ngIf="offerExpiry">{{offerExpiry?.data}} days left to respond</span>
      <img src="../../../../assets/icons/calendar(old).png">
    </div>
  </div>
</code>```

Component B

```<code>offerExpiry: any;

...

  async ngOnInit() {
    if (this._exploreService.offer) {
      ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      const date1 = new Date(offer.expiryDate);
      const date2 = new Date(offer.startDate);
      const diffTime = Math.abs(date2.getTime() - date1.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      this.offerExpiry = diffDays;
      this._exploreService.publishExpiryDate({data: this.offerExpiry});
    }
  }
</code>```

service file

```<code>  public publishExpiryDate(data: any) {
    this._subject.next(data);
  }
</code>```

答: Create a variable of type any in your service file then need to assign it in behaviroural subscriber that will listen when your component B loaded and subscribe the variable in onInit() in component A.</p>

Title: Check for value changes in variable

Body:
I have 2 components in my angular app. Component A is a header and component B sets a value that I need in component A. The problem is that component A is getting set before B so the value that I need is not being displayed when I need it. If I refresh my browser then it shows. My code will explain better.

Component A

  offerExpiry: any;

  constructor(
    public expiry: ExploreOfferService
  ) {

  }
  ngOnChanges() {
    this.expiry.event.subscribe((data) => {
      this.offerExpiry = data;
    });
  }

      {{offerExpiry?.data}} days left to respond

Component B

offerExpiry: any;

...

  async ngOnInit() {
    if (this._exploreService.offer) {
      ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      const date1 = new Date(offer.expiryDate);
      const date2 = new Date(offer.startDate);
      const diffTime = Math.abs(date2.getTime() - date1.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      this.offerExpiry = diffDays;
      this._exploreService.publishExpiryDate({data: this.offerExpiry});
    }
  }

service file

  public publishExpiryDate(data: any) {
    this._subject.next(data);
  }


答:
Straight from MDN:

A style declaration is reset by setting it to null or an empty string

So given your current code, this should do the trick. You will just need to keep track of what specific styles you changed so you can make sure you reset it.

```<code>document.getElementById('button4').addEventListener('click', function(){
    document.getElementById('box').style.height = null;
    document.getElementById('box').style.background = null;
    document.getElementById('box').style.opacity = null;
}
</code>```

Edit: Kirbee's answer is probably better unless there are other inline styles that you want to be preserved because using their solution you don't have to keep track of all the styles you need to reset. Additionally, if the original styles are defined as inline styles and not in a CSS file, my solution will not work. If that is the case, you would need to do something where you store the original values in a global variable and then use that variable when resetting the styles.

Title: how to reset a div to its original style with javascript

Body:
Straight from MDN:

A style declaration is reset by setting it to null or an empty string

So given your current code, this should do the trick. You will just need to keep track of what specific styles you changed so you can make sure you reset it.

document.getElementById('button4').addEventListener('click', function(){
    document.getElementById('box').style.height = null;
    document.getElementById('box').style.background = null;
    document.getElementById('box').style.opacity = null;
}

Edit: Kirbee's answer is probably better unless there are other inline styles that you want to be preserved because using their solution you don't have to keep track of all the styles you need to reset. Additionally, if the original styles are defined as inline styles and not in a CSS file, my solution will not work. If that is the case, you would need to do something where you store the original values in a global variable and then use that variable when resetting the styles.


问:
Unique constraint on multiple fields in Access 2003
I have not found any answer regarding my question, all unique constraint questions did not involve MS Access.

The question is how to make a unique constraint on multpile fields in MS Access 2003 database?

If my table consists of columns id, A, B, C, D, E, F. I have an index on column id, but I would like to have a unique constraint set on both columns A and B. Hence, I may have a duplicate value in column A, provided the value in column B are different.

I want to stress that I am not interested in a workaround like creating new column with concatenated values from columns A and B, and creating a constraint on this column.

答:
In ANSI-92 Query Mode, execute this SQL DDL:

```<code>ALTER TABLE MyTable ADD
   CONSTRAINT MyTable__key
      UNIQUE (A, B);
</code>```

Using VBA in Access:

```<code>CurrentProject.Connection.Execute _
    "ALTER TABLE MyTable ADD CONSTRAINT MyTable__key UNIQUE (A, B);"
</code>```

Body:
In ANSI-92 Query Mode, execute this SQL DDL:

ALTER TABLE MyTable ADD
   CONSTRAINT MyTable__key
      UNIQUE (A, B);

Using VBA in Access:

CurrentProject.Connection.Execute _
    "ALTER TABLE MyTable ADD CONSTRAINT MyTable__key UNIQUE (A, B);"


答:
```<code>var naturalHeight = document.getElementById('box').style.height;
</code>```

Use var like this from beginning and load this value when you press the button.

Body:
var naturalHeight = document.getElementById('box').style.height;

Use var like this from beginning and load this value when you press the button.


问:
How to use Jquery to update textarea value in react app
I'm building a Chrome extension that layers over a 3rd party react website. I am attempting to update the value of a textarea within that app using the following code:

```<code>$('textarea').val("Text to go in textarea.");
</code>```

The code successfully updates the textarea however once the user clicks on the textarea, the DOM seems to regenerate and the value becomes blank.

What is the best way to update the value within the textarea so that it remains even once the user clicks and DOM regenerates? I am not a react expert however my guess is that the textarea is tied to the state. Is there any way to update that from my own jquery within my chrome extension?

Just to be clear, the textarea belongs to a 3rd party website/react app that I have no control over. I'm trying to manipulate it from my own google chrome extension. I thought the easiest way would be to somehow simulate actual typing in order to make the react app think the user typed my input however I searched around and could not find a way to do that.

答:
Expanding on @Panther's suggestion, you can set the value as you have done above and then trigger the onChange or keypress event etc to save the changes in either state or props. Now since React uses synthetic events , you need to trigger then as shown.</p>

```<code>$('textarea').val("Text to go in textarea.");

$.each(document.getElementsByTagName("textarea"),(index,Element)=>{
    let event = new Event("change"); // repeat for keypressup,down,input etc.
    Element.dispatchEvent(event);
});
</code>```

Body:
I'm building a Chrome extension that layers over a 3rd party react website. I am attempting to update the value of a textarea within that app using the following code:

$('textarea').val("Text to go in textarea.");

The code successfully updates the textarea however once the user clicks on the textarea, the DOM seems to regenerate and the value becomes blank.

What is the best way to update the value within the textarea so that it remains even once the user clicks and DOM regenerates? I am not a react expert however my guess is that the textarea is tied to the state. Is there any way to update that from my own jquery within my chrome extension?

Just to be clear, the textarea belongs to a 3rd party website/react app that I have no control over. I'm trying to manipulate it from my own google chrome extension. I thought the easiest way would be to somehow simulate actual typing in order to make the react app think the user typed my input however I searched around and could not find a way to do that.

Body:
Expanding on @Panther's suggestion, you can set the value as you have done above and then trigger the onChange or keypress event etc to save the changes in either state or props. Now since React uses synthetic events , you need to trigger then as shown.

$('textarea').val("Text to go in textarea.");

$.each(document.getElementsByTagName("textarea"),(index,Element)=>{
    let event = new Event("change"); // repeat for keypressup,down,input etc.
    Element.dispatchEvent(event);
});


问:
Check If the Worksheets Name in a Workbook is a Months Name
I need help with the code below. I found the code online @ StackOverflow I added some lines but the code does not work and I get an error message.

What I'm trying to do is to loop through each worksheet in workbook A. And check if the name of the worksheet is equals to a Month Name. If it does then insert a column in Column A and write the sheets Month Name in Column A cells.
There is data already  in column B:H and each existing month worksheets has dynamic rows. So after the column has been inserted and the sheets name is place in Cells(r,1) then copy the Month Sheets data to Workbook "Consolidated Data". TIA

```<code>Dim ws As Worksheet
    Dim i As Long

    For i = 1 To 12
        If IsError(MonthName(i, False)) = True Then
        Else
        Set ws = wbYTD.Sheets(MonthName(i, False))
        End If

        With ws
            .Columns(1).Insert
            .Range("A3").Value = (MonthName(i, False))
        End With
    Next i
</code>```

答:
This function returns TRUE when st contains a valid month name:

```<code>Function isMonthName(st As String) As Boolean
  Dim test
  On Error Resume Next
  test = DateValue(st & " 1, 1999")
  isMonthName = IIf(Err, False, True)
End Function
</code>```

Examples:

isMonthName("july") returns TRUE.

isMonthName("julyy") returns FALSE.

I'm not sure if it will work is all regions but it tests fine for me.

The function simply plugs the string into a string with a day and year ("____ 1, 1999") and checks whether it's a valid date using the DateValue function.  If it doesn't work in your region, just change that you probably just need to change the string to represent your area' "long date".

Body:
I need help with the code below. I found the code online @ StackOverflow I added some lines but the code does not work and I get an error message.

What I'm trying to do is to loop through each worksheet in workbook A. And check if the name of the worksheet is equals to a Month Name. If it does then insert a column in Column A and write the sheets Month Name in Column A cells.
There is data already  in column B:H and each existing month worksheets has dynamic rows. So after the column has been inserted and the sheets name is place in Cells(r,1) then copy the Month Sheets data to Workbook "Consolidated Data". TIA

Dim ws As Worksheet
    Dim i As Long

    For i = 1 To 12
        If IsError(MonthName(i, False)) = True Then
        Else
        Set ws = wbYTD.Sheets(MonthName(i, False))
        End If

        With ws
            .Columns(1).Insert
            .Range("A3").Value = (MonthName(i, False))
        End With
    Next i

Body:
This function returns TRUE when st contains a valid month name:

Function isMonthName(st As String) As Boolean
  Dim test
  On Error Resume Next
  test = DateValue(st & " 1, 1999")
  isMonthName = IIf(Err, False, True)
End Function

Examples:

isMonthName("july") returns TRUE.

isMonthName("julyy") returns FALSE.

I'm not sure if it will work is all regions but it tests fine for me.

The function simply plugs the string into a string with a day and year ("____ 1, 1999") and checks whether it's a valid date using the DateValue function.  If it doesn't work in your region, just change that you probably just need to change the string to represent your area' "long date".


答:
Hello

    <button id="button1">1 height</button>
    <button id="button2">2 bg</button>
    <button id="button3">3 opacity</button>
    <button id="button4">4 reset</button>

    ```

Body:
I am trying to "reset" box after several changes to its original state in javascript. I have used several addEventListener methods to change the appearance of a box in HTML, but am having trouble using a "reset" button to revert the box to its original appearance.

document.getElementById('button1').addEventListener('click', function(){

  document.getElementById('box').style.height = '250px';

});

document.getElementById('button2').addEventListener('click', function(){

  document.getElementById('box').style.background = 'blue';

});

document.getElementById('button3').addEventListener('click', function(){

  document.getElementById('box').style.opacity = '0.1';

});

// This is where i need to reset the box

document.getElementById('button4').addEventListener('click', function(){

Body:
<html>
    <body>
    <div id='box'>Hello
    </div>
    <button id="button1">1 height</button>
    <button id="button2">2 bg</button>
    <button id="button3">3 opacity</button>
    <button id="button4">4 reset</button>
    <script type="text/javascript">

    box = document.getElementById('box');
    b1 = document.getElementById('button1');
    b2 = document.getElementById('button2');
    b3 = document.getElementById('button3');
    b4 = document.getElementById('button4');

    b1.addEventListener('click',
     function(){
        box.style.height = '100px';
     });

    b2.addEventListener('click',
     function(){
       box.style.background = 'blue';
     });

    b3.addEventListener('click',
     function(){
       box.style.opacity = '0.1';
    });

    // This is where i need to reset the box

    b4.addEventListener('click', function(){
     box.style = "";
    });
    </script>
    </body>
    </html>


问:
How to create a table with 4 columns using SQLite
I was working in android studio in an app that passes the user's info to a table using SQLite. It was working but I needed to add another data so according to me I convert the table to another of 4 columns but in the logcat appears this message

"E/SQLiteLog: (1) table STUDENTS has 3 columns but 4 values were supplied"

and this is what I have:

```<code>public class SQLiteDb extends SQLiteOpenHelper {

    private static final String TABLE_STUDENTS="CREATE TABLE STUDENTS(NAMES TEXT,
    LASTNAMES TEXT, ID TEXT, IMAGE TEXT)";

    public SQLiteDb(Context context) {
        super(context, "db_students", null, 1);
    }
}
</code>```

Does anyone know how can I fix it to accept 4 values?

答:
The typical reason why columns don't appear to exist is the mis-conception about the Database Helper's onCreate method and that it is assumed that it runs every time the App is run. In fact it will only run automatically once when the database is first created (once created the database remains).

Hence it is likely that you have changed the table to have an additional column after the database has been created.

The fix is simple either delete's the App's data or uninstall the App, after doing one then rerun the App and the new schema will be applied and you will have the four columns.

Body:
I was working in android studio in an app that passes the user's info to a table using SQLite. It was working but I needed to add another data so according to me I convert the table to another of 4 columns but in the logcat appears this message

"E/SQLiteLog: (1) table STUDENTS has 3 columns but 4 values were supplied"

and this is what I have:

public class SQLiteDb extends SQLiteOpenHelper {

    private static final String TABLE_STUDENTS="CREATE TABLE STUDENTS(NAMES TEXT,
    LASTNAMES TEXT, ID TEXT, IMAGE TEXT)";

    public SQLiteDb(Context context) {
        super(context, "db_students", null, 1);
    }
}

Does anyone know how can I fix it to accept 4 values?


问:
What is the correct way to pass data to a running thread
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

```<code>C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?
</code>```

So what is the correct way to pass data to a running thread in C# and Java?

答: You can use delegate pattern where child threads subscribes to an event and main thread raises an event, passing the parameters.</p>

Body:
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?

So what is the correct way to pass data to a running thread in C# and Java?


问:
how can i save received image or document file from sender whatsapp using twilio?
I have a scenario like user will send the image or pdf file to twilio whatsapp number so i need to save that image/pdf in folder which will be processed to next level.

How can i save the files? I am using Node SDK.

Thanks in advance.

答:
Assuming you've already configured your webhook on your sandbox page, so that messages containing media from Whatsapp are getting to your app.

As documentation says, you'll receive MediaContentType{N} and MediaUrl{N} as long as body and other parameters. The following snippet was translated-ish from a Python example from official documentation:

```<code>const Fs = require('fs')
const Path = require('path')
const Axios = require('axios')

const num_media = req.body.NumMedia;
const media_files = []
for (let i = 0; i <= num_media; i++) {
    const id = req.body.MessageSid
    const media_url = req.body[`MediaUrl{i}`];
    const mime_type = req.body[`MediaContentType{i}`);
    media_files.push({'media_url': media_url, 'mime_type': mime_type});

    download(media_url, id);
}

async function download(url, name) {
  const path = Path.resolve(__dirname, 'files', name)
  const writer = Fs.createWriteStream(path)

  const response = await Axios({
    url,
    method: 'GET',
    responseType: 'stream'
  })

  response.data.pipe(writer)

  return new Promise((resolve, reject) => {
    writer.on('finish', resolve)
    writer.on('error', reject)
  })
}

</code>```

Body:
Assuming you've already configured your webhook on your sandbox page, so that messages containing media from Whatsapp are getting to your app.

As documentation says, you'll receive MediaContentType{N} and MediaUrl{N} as long as body and other parameters. The following snippet was translated-ish from a Python example from official documentation:

const Fs = require('fs')
const Path = require('path')
const Axios = require('axios')

const num_media = req.body.NumMedia;
const media_files = []
for (let i = 0; i <= num_media; i++) {
    const id = req.body.MessageSid
    const media_url = req.body[`MediaUrl{i}`];
    const mime_type = req.body[`MediaContentType{i}`);
    media_files.push({'media_url': media_url, 'mime_type': mime_type});

    download(media_url, id);
}

async function download(url, name) {
  const path = Path.resolve(__dirname, 'files', name)
  const writer = Fs.createWriteStream(path)

  const response = await Axios({
    url,
    method: 'GET',
    responseType: 'stream'
  })

  response.data.pipe(writer)

  return new Promise((resolve, reject) => {
    writer.on('finish', resolve)
    writer.on('error', reject)
  })
}


问:
Sending ID input from submit to controller action
I have a view which I need to take a user input, and send it to a controller action. I have tried several things but what references I have found online have not seemed to be working for me. I have an input in a form, and I have the controller and action name listed, however it does not seem to be passing the value from the users input. In fact, unless I hardcode the value into the controllers parameters, when I get to the page I just get error:

```<code>The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'Namespace.Controllers.TerminalReceiptsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</code>```

Parameter name: parameters

Otherwise, when hard coded into the controller params, it works just fine.

Below is some code.

View import portion:

```<code>@using (Html.BeginForm("Index", "TerminalReceipts"))
 {

  <div>
    <input type="text" name="ID" />
     <input type="submit" value="Find Receipts">
  </div>

   string Id = Request.Form["ID"];
}
</code>```

View table portion:

```<code><div class="row">
<div class="col-md-12" style="overflow-y:scroll">
    <table class="table table-striped table-hover table-bordered" id="terminalReceipts">
        <thead>
            <tr>
                <th>Local Transaction Time</th>
                <th>Amount</th>
                <th>Receipt</th>
            </tr>
        </thead>
        <tbody>

            @foreach (var item in Model.TransactionsTests)
            {
                <tr>
                    <td>@item.TransactionTime</td>
                    @*<td>@Html.DisplayFor(modelItem => item.LocalTransactionTime)</td>*@
                    <td>@item.Amount</td>
                    <td>@Html.ActionLink("View Receipt", "Details", new { Key = 1 }, new { @class = "btn btn-primary btn-sm" }) <br /></td>
                </tr>
            }
        </tbody>
    </table>
</div>
</code>```

Controller action:

```<code>        // GET: TerminalReceipts
    public ActionResult Index(int id )
    {
         var model = TRBL.GetTransactionTestsData(id);
        //var model = new TerminalReceiptsVM();

        return View(model);
    }
</code>```

Where in my code (specifically the view import portion) am I going wrong?

答: You need to change string Id = Request.Form["ID"]; and <input type="text" name="ID" /> to string Id = Request.Form["id"]; and <input type="text" name="id" />   mapping it with the lower case perimeter name in the controller.

Body:
I have a view which I need to take a user input, and send it to a controller action. I have tried several things but what references I have found online have not seemed to be working for me. I have an input in a form, and I have the controller and action name listed, however it does not seem to be passing the value from the users input. In fact, unless I hardcode the value into the controllers parameters, when I get to the page I just get error:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'Namespace.Controllers.TerminalReceiptsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Parameter name: parameters

Otherwise, when hard coded into the controller params, it works just fine.

Below is some code.

View import portion:

@using (Html.BeginForm("Index", "TerminalReceipts"))
 {

    <input type="text" name="ID" />
     <input type="submit" value="Find Receipts">

   string Id = Request.Form["ID"];
}

View table portion:

                Local Transaction Time
                Amount
                Receipt

            @foreach (var item in Model.TransactionsTests)
            {

                    @item.TransactionTime
                    @*@Html.DisplayFor(modelItem => item.LocalTransactionTime)	*@
                    @item.Amount
                    @Html.ActionLink("View Receipt", "Details", new { Key = 1 }, new { @class = "btn btn-primary btn-sm" })

            }

Controller action:

        // GET: TerminalReceipts
    public ActionResult Index(int id )
    {
         var model = TRBL.GetTransactionTestsData(id);
        //var model = new TerminalReceiptsVM();

        return View(model);
    }

Where in my code (specifically the view import portion) am I going wrong?


问:
How to fix background image with drawable xml file on Android?
How do I make this picture in android drawable.xml format?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap android:src="@drawable/wallpaper"></bitmap>
    </item>
</layer-list>
</code>```

答:
You can defined the drawable directly as layer-list item:</p>

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <layer-list
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:opacity="opaque">

    <!-- The background color, preferably the same as your normal theme -->
    <item android:drawable="@drawable/wallpaper"/>

    </layer-list>
</code>```

Body:
How do I make this picture in android drawable.xml format?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap android:src="@drawable/wallpaper"></bitmap>
    </item>
</layer-list>

Body:
You can defined the drawable directly as layer-list item:

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:opacity="opaque">

    <!-- The background color, preferably the same as your normal theme -->
    <item android:drawable="@drawable/wallpaper"/>

    </layer-list>


问:
Extra bytes at the end of a DOS .COM file, compiled with GCC
I have the following C source file, with some asm blocks that implement a print and exit routine by calling DOS system calls.

```<code>__asm__(
    ".code16gcc;"
    "call dosmain;"
    "mov $0x4C, %AH;"
    "int $0x21;"
);

void print(char *str)
{
    __asm__(
        "mov $0x09, %%ah;"
        "int $0x21;"
        : // no output
        : "d"(str)
        : "ah"
    );
}

void dosmain()
{
    // DOS system call expects strings to be terminated by $.
    print("Hello world$");
}

</code>```

The linker script file and the build script file are as such,

```<code>OUTPUT_FORMAT(binary)
SECTIONS
{
    . = 0x0100;
    .text :
    {
        *(.text);
    }
    .data :
    {
        *(.data);
        *(.bss);
        *(.rodata);
    }
    _heap = ALIGN(4);
}
</code>```

```<code>gcc -fno-pie -Os -nostdlib -ffreestanding -m16 -march=i386 \
-Wl,--nmagic,--script=simple_dos.ld simple_dos.c -o simple_dos.com
</code>```

I am used to building .COM files in assembly, and I am aware of the structure of a dos file. However in case of the .COM file generated using GCC, I am getting some extra bytes at the end and I cannot figure out why. (The bytes that are inside the shaded area and the box below is what is expected everything else is unaccounted).

[]

My hunch is that these are some static storage used by GCC. I thought this could be due to the string in the program. I have thus commented the line print("Hello world$"); but the extra bytes still reside. It will be of great help if someone knows what is going on and tell how to prevent GCC inserting these bytes in the output.

Source code is available here: Github

PS: Object file also contains these extra bytes.

答:
The extra data is likely DWARF unwind information. You can stop GCC from generating it with the -fno-asynchronous-unwind-tables option.

You can also have the GNU linker discard the unwind information by adding the following to SECTIONS directive of your linker script:

```<code>/DISCARD/ :
{
     *(.eh_frame)
}
</code>```

Also note that generated COM file will be one byte bigger than you expect because of the null byte at the end of the string.

Body:
I have the following C source file, with some asm blocks that implement a print and exit routine by calling DOS system calls.

__asm__(
    ".code16gcc;"
    "call dosmain;"
    "mov $0x4C, %AH;"
    "int $0x21;"
);

void print(char *str)
{
    __asm__(
        "mov $0x09, %%ah;"
        "int $0x21;"
        : // no output
        : "d"(str)
        : "ah"
    );
}

void dosmain()
{
    // DOS system call expects strings to be terminated by $.
    print("Hello world$");
}

The linker script file and the build script file are as such,

OUTPUT_FORMAT(binary)
SECTIONS
{
    . = 0x0100;
    .text :
    {
        *(.text);
    }
    .data :
    {
        *(.data);
        *(.bss);
        *(.rodata);
    }
    _heap = ALIGN(4);
}

gcc -fno-pie -Os -nostdlib -ffreestanding -m16 -march=i386 \
-Wl,--nmagic,--script=simple_dos.ld simple_dos.c -o simple_dos.com

I am used to building .COM files in assembly, and I am aware of the structure of a dos file. However in case of the .COM file generated using GCC, I am getting some extra bytes at the end and I cannot figure out why. (The bytes that are inside the shaded area and the box below is what is expected everything else is unaccounted).

[]

My hunch is that these are some static storage used by GCC. I thought this could be due to the string in the program. I have thus commented the line print("Hello world$"); but the extra bytes still reside. It will be of great help if someone knows what is going on and tell how to prevent GCC inserting these bytes in the output.

Source code is available here: Github

PS: Object file also contains these extra bytes.

Body:
The extra data is likely DWARF unwind information. You can stop GCC from generating it with the -fno-asynchronous-unwind-tables option.

You can also have the GNU linker discard the unwind information by adding the following to SECTIONS directive of your linker script:

/DISCARD/ :
{
     *(.eh_frame)
}

Also note that generated COM file will be one byte bigger than you expect because of the null byte at the end of the string.


问:
*ngfor not display any data in Angular7
I 'm using angular7 , and here is my code :
in component.ts

import { Component, OnInit } from "@angular/core";
import { FocusAreasService } from "../../services/focus-areas.service";

@Component({
  selector: "app-about",
  templateUrl: "./about.component.html",
  styleUrls: ["./about.component.scss"]
})
export class AboutComponent implements OnInit {
  public canonical: string;
  public RsFocusArea: any[];
  constructor(public focusareaService: FocusAreasService) {}

  ngOnInit() {
    this.canonical = document.location.origin;

    this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe({
      next(response) {
        console.log("HttpClient handle data");
        console.dir(response);

        this.RsFocusArea = response["focusArea"];
       //I print this.RsFocusArea here , it has values
        console.log("this.RsFocusArea");
        console.dir(this.RsFocusArea);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }
}

}
```

<p>and in .html</p>

<pre class="lang-html prettyprint-override"><code> <ul class="col-xs-12 row">
        <li *ngFor="let area of RsFocusArea" class="col-xs-12 col-sm-6 col-md-4">{{area}}
        </li>
      </ul>
</code>```

and the li tage did not repeat and gave me this in tag structure:

```

Is there anything wrong with my code? I thought maybe I need to rerender the page when I assign new value to RsFocusArea in ngOnInit?

答:
Oh god!, I was writing the answer that Jojofoulk posted here. At least I am going to explain you why this happens in less words. Arrow functions keep the context where they were declared, in the other hand, the function declarations keep a local scope.

When you do this:

```<code>{
    ...
    this.RsFocusArea = response["focusArea"];
}
</code>```

You are assigning the reponse value in function local scope and the outer scope doesn't result affected and is for that reason when you print the value you see your response, but you are seeing a local result assigned in local scope.

Title: *ngfor not display any data in Angular7

Body:
I 'm using angular7 , and here is my code :
in component.ts

import { Component, OnInit } from "@angular/core";
import { FocusAreasService } from "../../services/focus-areas.service";

@Component({
  selector: "app-about",
  templateUrl: "./about.component.html",
  styleUrls: ["./about.component.scss"]
})
export class AboutComponent implements OnInit {
  public canonical: string;
  public RsFocusArea: any[];
  constructor(public focusareaService: FocusAreasService) {}

  ngOnInit() {
    this.canonical = document.location.origin;

    this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe({
      next(response) {
        console.log("HttpClient handle data");
        console.dir(response);

        this.RsFocusArea = response["focusArea"];
       //I print this.RsFocusArea here , it has values
        console.log("this.RsFocusArea");
        console.dir(this.RsFocusArea);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }
}

}

and in .html

{{area}}

and the li tage did not repeat and gave me this in tag structure:

Is there anything wrong with my code? I thought maybe I need to rerender the page when I assign new value to RsFocusArea in ngOnInit?

Body:
Oh god!, I was writing the answer that Jojofoulk posted here. At least I am going to explain you why this happens in less words. Arrow functions keep the context where they were declared, in the other hand, the function declarations keep a local scope.

When you do this:

{
    ...
    this.RsFocusArea = response["focusArea"];
}

You are assigning the reponse value in function local scope and the outer scope doesn't result affected and is for that reason when you print the value you see your response, but you are seeing a local result assigned in local scope.


问:
Maven: Need a way to change a property or URL value if the project is being released or not
We're using the JDeb maven plugin to build debian packages of our one-jar'd projects.

We have two APT repositories, one for pre-release builds, and one for releases.

We're using the Wagon plugin to upload the artifacts, but we cannot figure out how to only send releases to the release repository, and snapshots to the pre-release repo.

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>wagon-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>upload-to-nexus</id>
            <phase>deploy</phase>
            <goals>
                <goal>upload-single</goal>
            </goals>
            <configuration>
                <serverId>xxx-all</serverId>
                <fromFile>${project.build.directory}/${jdeb.name}</fromFile>
                <url>https://xxx.xxx.xxx/repository/xxx-apt-pre</url>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

We need to change xxx-apt-pre above to xxx-apt-dist when the release plugin runs. For the life of me, I cannot figure out a way to do this.

I initially tried using the build-helper plugin to regex the ${project.build.finalName} for the phrase SNAPSHOT, but it won't overwrite the existing property.

Any ideas are welcome.

答:
Well the solution wasn't pretty, but gets 'er done as we say in the midwest:

```<code><plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <executions>
        <execution>
            <id>add-dynamic-properties</id>
            <phase>package</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <source>
                <![CDATA[
                    if (project.version.contains('SNAPSHOT')) {
                        project.properties['aptRepoName'] = 'xxx-apt-pre'
                    } else {
                        project.properties['aptRepoName'] = 'xxx-apt-dist'
                    }
                ]]>
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>wagon-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>upload-to-nexus</id>
            <phase>deploy</phase>
            <goals>
                <goal>upload-single</goal>
            </goals>
            <configuration>
                <serverId>xxx-all</serverId>
                <fromFile>${project.build.directory}/${jdeb.name}</fromFile>
                <url>https://xxx.xxx.xxx/repository/${aptRepoName}</url>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

I hope this helps someone or someday someone posts a better way.

Body:
We're using the JDeb maven plugin to build debian packages of our one-jar'd projects.

We have two APT repositories, one for pre-release builds, and one for releases.

We're using the Wagon plugin to upload the artifacts, but we cannot figure out how to only send releases to the release repository, and snapshots to the pre-release repo.

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>wagon-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>upload-to-nexus</id>
            <phase>deploy</phase>
            <goals>
                <goal>upload-single</goal>
            </goals>
            <configuration>
                <serverId>xxx-all</serverId>
                <fromFile>${project.build.directory}/${jdeb.name}</fromFile>
                <url>https://xxx.xxx.xxx/repository/xxx-apt-pre</url>
            </configuration>
        </execution>
    </executions>
</plugin>

We need to change xxx-apt-pre above to xxx-apt-dist when the release plugin runs. For the life of me, I cannot figure out a way to do this.

I initially tried using the build-helper plugin to regex the ${project.build.finalName} for the phrase SNAPSHOT, but it won't overwrite the existing property.

Any ideas are welcome.

Body:
Well the solution wasn't pretty, but gets 'er done as we say in the midwest:

<plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <executions>
        <execution>
            <id>add-dynamic-properties</id>
            <phase>package</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <source>
                <![CDATA[
                    if (project.version.contains('SNAPSHOT')) {
                        project.properties['aptRepoName'] = 'xxx-apt-pre'
                    } else {
                        project.properties['aptRepoName'] = 'xxx-apt-dist'
                    }
                ]]>
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>wagon-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>upload-to-nexus</id>
            <phase>deploy</phase>
            <goals>
                <goal>upload-single</goal>
            </goals>
            <configuration>
                <serverId>xxx-all</serverId>
                <fromFile>${project.build.directory}/${jdeb.name}</fromFile>
                <url>https://xxx.xxx.xxx/repository/${aptRepoName}</url>
            </configuration>
        </execution>
    </executions>
</plugin>

I hope this helps someone or someday someone posts a better way.


问:
How can I pass data from an action to an input-view in Bixby?
There are two input fields in my Bixby capsule, that are, name and description. So, I want the name entered by the user in the name input to be displayed at the description input view.
For example:

Bixby: What's your name?
Me: XYZ
Bixby: Hi XYZ, tell me something about yourself?

I'm not able to display XYZ in description input. Is there any way to solve my problem?

答:
In your input-view</p>

```<code>input-view {
  match: description {
    to-input: [your-action] (action)
  }

  message {
    template ("Hi #{value(action.name)})
  }
}
</code>```

Body:
In your input-view

input-view {
  match: description {
    to-input: [your-action] (action)
  }

  message {
    template ("Hi #{value(action.name)})
  }
}


问:
is there a way i can treat a variable as maths in javascript
I need help this is really hard to explain I am making a calculator type program. And the main bit where it calculates it wont. it needs to calculate from multiple textboxs and combine them into one readable string. That needs to be run as math. but i can not run it as math, I can only manage to run it as a text. not as equation. is there any way i can change it so it treats it like math. I am a student I am still learning js.

I have tried changing the var name and changing the text function but have not been able to fix it here is the code so you can help:

```<code>function add() {
  var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    window.value=value;
    document.getElementById('number').value = window.value;
    var num = "v"+window.value;
    var node = document.createElement("a");
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("id", num);
    node.appendChild(x);
    document.getElementById("myList").appendChild(node);
  }

function equal() {
  var str = "";
  var ans = "";
for (var i = 1; i <= window.value; i++) {
  str = "v"+i;
</code>```

this is what i need to be treated as math:

```<code>  ans += document.getElementById(str).value;
</code>```

rest of javascript:

```<code>}
document.getElementById("demo3").innerHTML = ans;
}
</code>```

if it is any help here is the html:

<!DOCTYPE html>

        <link rel="stylesheet" href="style.css">

<input id="number" type="hidden"></input>

Click the button to create a Text Field.

<button onclick="add()">+</button>
<button onclick="equal()">=</button>

```

thankyou

答: Do a simple thing just get all the input as a String and try to split that string into given nos and operations then try to operate with an if else to do your things.You can do any operations.</p>

Body:
I need help this is really hard to explain I am making a calculator type program. And the main bit where it calculates it wont. it needs to calculate from multiple textboxs and combine them into one readable string. That needs to be run as math. but i can not run it as math, I can only manage to run it as a text. not as equation. is there any way i can change it so it treats it like math. I am a student I am still learning js.

I have tried changing the var name and changing the text function but have not been able to fix it here is the code so you can help:

function add() {
  var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    window.value=value;
    document.getElementById('number').value = window.value;
    var num = "v"+window.value;
    var node = document.createElement("a");
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("id", num);
    node.appendChild(x);
    document.getElementById("myList").appendChild(node);
  }

function equal() {
  var str = "";
  var ans = "";
for (var i = 1; i <= window.value; i++) {
  str = "v"+i;

this is what i need to be treated as math:

  ans += document.getElementById(str).value;

rest of javascript:

}
document.getElementById("demo3").innerHTML = ans;
}

if it is any help here is the html:

<!DOCTYPE html>

        <link rel="stylesheet" href="style.css">

<input id="number" type="hidden"></input>

Click the button to create a Text Field.

<button onclick="add()">+</button>
<button onclick="equal()">=</button>

thankyou


问:
iOS - NSJSONSerialization: Unable to convert data to string around character
I'm getting this error while parsing JSON:

```<code>NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unable to convert data to string around character 73053.) UserInfo=0x1d5d8250 {NSDebugDescription=Unable to convert data to string around character 73053.}
</code>```

Any suggestions how to fix this?

ADDED
As it says in error report, the parser can't go through the character at position 73053, which is "ø" in my JSON response. As far as I know characters like Ø,Å,Æ etc. shouldn't be a problem for json parsers?

答:
Swift 5:

Yes, i got the same error while parsing JSON data.

Solution : You have to first convert response data into String and then convert that Sting to Data using UTF8 encoding before decoding.

```<code>let utf8Data = String(decoding: responseData, as: UTF8.self).data(using: .utf8)
</code>```

Body:
I'm getting this error while parsing JSON:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unable to convert data to string around character 73053.) UserInfo=0x1d5d8250 {NSDebugDescription=Unable to convert data to string around character 73053.}

Any suggestions how to fix this?

ADDED
As it says in error report, the parser can't go through the character at position 73053, which is "ø" in my JSON response. As far as I know characters like Ø,Å,Æ etc. shouldn't be a problem for json parsers?

Body:
Swift 5:

Yes, i got the same error while parsing JSON data.

Solution : You have to first convert response data into String and then convert that Sting to Data using UTF8 encoding before decoding.

let utf8Data = String(decoding: responseData, as: UTF8.self).data(using: .utf8)


问:
Script to check if wifi is connected
In Max OS Mojave, is it possible to create a shell script or something similar that checks for an active wifi connection, and if not, disables wifi then re-enable?

A little background. Basically I need to make sure that I can connect to my computer at home from anywhere. Normally this is no problem, but we have been having power outages with current storms and when the power comes back on, my Mac does not always reconnect to my wifi network (may have something to do with router, it is old). It's not a common problem, but I'll be darned if it doesn't happen at the most inconvenient times. In order to fix this, I simply have to disable wifi, then re-enable. This fixes the issue and the wifi auto reconnects. But I can't do that if I'm not at home.

I've considered a script that runs every 20 minutes or so that disables wifi, then re-enables it using launchd which technically fixes my problem, however I don't want to have to keep disabling the script while using my Mac because if I don't disable it, I'll loose wifi every 20 minutes.

Any information would be greatly appreciated.

答:
networksetup is an amazing command such that I haven't even scratched the surface. Here's something that works:

```<code>if ! networksetup -getinfo Wi-Fi | grep Router
then
  networksetup -setairportnetwork en0 $routername $routerpassword
fi
</code>```

This will request data about the Wi-Fi network service, which is 5-10 lines of various info, including whether or not it is connected to a router, and which. If that line is missing, you are not connected.

In that case, you can explicitly request to be connected to a specific router (with a specific username and password). Or, alternately, you can do the same thing you did before, which you say works as well (and you don't need to write down your router's credentials).

(There may well be a smarter way. As I said, that command can do so many things.)

Title: Script to check if wifi is connected

Body:
networksetup is an amazing command such that I haven't even scratched the surface. Here's something that works:

if ! networksetup -getinfo Wi-Fi | grep Router
then
  networksetup -setairportnetwork en0 $routername $routerpassword
fi

This will request data about the Wi-Fi network service, which is 5-10 lines of various info, including whether or not it is connected to a router, and which. If that line is missing, you are not connected.

In that case, you can explicitly request to be connected to a specific router (with a specific username and password). Or, alternately, you can do the same thing you did before, which you say works as well (and you don't need to write down your router's credentials).

(There may well be a smarter way. As I said, that command can do so many things.)


问:
Why is Java 6 compiled class size larger than Java 5?
We are noticing that when we compile our classes on Java 6, they are consistently larger than Java 5.

I understand that there has not been a change to the byte code to date, so I assume the Java 6 compiler is throwing in more stuff. Is that all required, or is there any way to turn that off and still compile Java 6 source code?

答: Dump the contents of the files with the javap command to see if anything obvious stands out. There might be some extra attributes in Java 6 class files.


问:
How to setup my crontab in order to execute process_tasks in Django?
I decided to use a library for my Django project called django-background-tasks (link to the documentation: https://django-background-tasks.readthedocs.io/en/latest/). I want to deploy my Django application to a Linux server (Ubuntu 19.0.4). How should I write the crontab in order to call the command "process_tasks" every five seconds?

Here Running a cron every 30 seconds is a workaround to achieve the seconds part, but since I am new to this part of the job (deploying and automation of process), how should I create my crontab file in order to achieve my desired purpose?

I'll be using process_tasks for a lot of different functionalities like: do some analysis at night and send results in the morning, expire some codes, etc. So basically I'll need to be running it almost constantly.

Thank you in advance for any suggestion, if you need something more I would be happy to provide it to you.

答:
Since you know cron only allows for a minimum of one minute but you want to run it every 5 seconds.

how about writing a shell script (running as a service via supervisor) that runs your task in an infinite loop. This script will sleeps after every run for 5 seconds.

The only difference between this service and a cron is:
  A cron will fork a process every time it runs, a process runs your job and periodically check if the job is finished in order to clean it up, and this script (as service) will not work like cron but it'll do the job I believe.

```<code>#!/bin/bash
while true; do
    # your code here,
    # call your python file which initializes
    # django variables (or whatever you want) and do the needful.
    sleep 5;
done
</code>```

You can configure a file process_django_tasks.sh(this file contains above code) with supervisor as a service so it runs on boot time and you have a control to start and stop with quick commands.

To test quickly you can easily run sh process_django_tasks.sh

If you could tell us why exactly you want your script to run every 5 seconds. Maybe we all suggest a better way than running a script every 5 sec.

Body:
Since you know cron only allows for a minimum of one minute but you want to run it every 5 seconds.

how about writing a shell script (running as a service via supervisor) that runs your task in an infinite loop. This script will sleeps after every run for 5 seconds.

The only difference between this service and a cron is:
  A cron will fork a process every time it runs, a process runs your job and periodically check if the job is finished in order to clean it up, and this script (as service) will not work like cron but it'll do the job I believe.

#!/bin/bash
while true; do
    # your code here,
    # call your python file which initializes
    # django variables (or whatever you want) and do the needful.
    sleep 5;
done

You can configure a file process_django_tasks.sh(this file contains above code) with supervisor as a service so it runs on boot time and you have a control to start and stop with quick commands.

To test quickly you can easily run sh process_django_tasks.sh

If you could tell us why exactly you want your script to run every 5 seconds. Maybe we all suggest a better way than running a script every 5 sec.


问:
How can I select elements having specific siblings?
How can I prevent anchor () tag from doing nothing if li has ul according to the following code:

```<code><aside class="sidebar">
 <div id="leftside-navigation" class="nano">
  <ul class="nano-content">
   <li>
    <a href="index.html">
      <span>Home</span>
    </a>
   </li>
   <li class="sub-menu">
     <a href="javascript:void(0);">
       <span>Categories</span>
       <i class="arrow fa fa-angle-right pull-right"></i>
     </a>
     <ul>
       <li>
         <a href="index.html">
           <span>Home</span>
         </a>
       </li>
       <li>
         <a href="index.html">
           <span>Lifestyles</span>
         </a>
       </li>
       <li>
         <a href="index.html">
           <span>Technology</span>
         </a>
        </li>
      </ul>
    </li>
  </ul>
</div>
</code>```

I've tried to put javascript:void(0) - it works but I wanted to make it with if else statement or any other way.

I wanted to do that is:

if li.submenu has ul li.has-submenu a prevent default

答:
You can also try this. </p>

```<code>$("li").find("ul > a").click(function(e) {
    e.preventDefault();
});
</code>```

Body:
How can I prevent anchor () tag from doing nothing if li has ul according to the following code:

      Home

       Categories

           Home

           Lifestyles

           Technology

I've tried to put javascript:void(0) - it works but I wanted to make it with if else statement or any other way.

I wanted to do that is:

if li.submenu has ul li.has-submenu a prevent default

Body:
You can also try this.

$("li").find("ul > a").click(function(e) {
    e.preventDefault();
});


答:
I'd recommend using Supervisor (http://supervisord.org) to run python manage.py process_tasks, which will then monitor for the tasks you scheduled in your code and run them based on their repeat syntax:

To run your task every 5 seconds:

function_to_call(var, repeat=5, repeat_until=None)

I'd also recommend Supervisor to run your entire Django project.

Looking at the documentation the process_tasks command by default runs every 5 seconds checking for new tasks to run. Not sure if you just wanted to check every 5 seconds or actually run a specific task every 5 seconds.

Title: How to setup my crontab in order to execute process_tasks in Django?

Body:
I decided to use a library for my Django project called django-background-tasks (link to the documentation: https://django-background-tasks.readthedocs.io/en/latest/). I want to deploy my Django application to a Linux server (Ubuntu 19.0.4). How should I write the crontab in order to call the command "process_tasks" every five seconds?

Here Running a cron every 30 seconds is a workaround to achieve the seconds part, but since I am new to this part of the job (deploying and automation of process), how should I create my crontab file in order to achieve my desired purpose?

I'll be using process_tasks for a lot of different functionalities like: do some analysis at night and send results in the morning, expire some codes, etc. So basically I'll need to be running it almost constantly.

Thank you in advance for any suggestion, if you need something more I would be happy to provide it to you.


问:
Custom templates callInWindow
I am using the new custom template feature but I am still fairly new to the general concept and I was looking for opinions on the following code, I want to call a global function that sits on my application from GTM, will this code work for my custom tag?

```<code>const log = require('logToConsole'); // Console api
const query = require('queryPermission'); // Query api
const callInWindow = require('callInWindow'); // Call function in window api

if (query('access_globals', 'execute', 'OBJ.tracking.add')) { // Trying to access the method
    log('data =', data); // USE ONLY IN DEBUG
    callInWindow( 'OBJ.tracking.add' , [data.tagLabel, data.tagDetail]); // Send event
    data.gtmOnSuccess();
}
else {
  data.gtmOnFailure();
}
</code>```

Where OBJ.tracking.add has execute only permissions.
Thanks!

答:
I've just been through this. Your syntax is correct, but that does not guarantee that this will actually run - that depends on what "OBJ" is actually doing. If it modifies the prototype chain at some point the code will not run (one of the reasons being that GTM custom templates actually run on a copy of the global object, not the object itself).

So while your code is fine, but it might not run due to limitations of the sandboxed Javascript, and in that case there is nothing you can do.

Title: Custom templates callInWindow

Body:
I am using the new custom template feature but I am still fairly new to the general concept and I was looking for opinions on the following code, I want to call a global function that sits on my application from GTM, will this code work for my custom tag?

const log = require('logToConsole'); // Console api
const query = require('queryPermission'); // Query api
const callInWindow = require('callInWindow'); // Call function in window api

if (query('access_globals', 'execute', 'OBJ.tracking.add')) { // Trying to access the method
    log('data =', data); // USE ONLY IN DEBUG
    callInWindow( 'OBJ.tracking.add' , [data.tagLabel, data.tagDetail]); // Send event
    data.gtmOnSuccess();
}
else {
  data.gtmOnFailure();
}

Where OBJ.tracking.add has execute only permissions.
Thanks!


问:
Kubernetes: Affinity depending on Azure Availability Set
Requirement

Kubernetes in Azure uses Availability Sets as the default availability strategy.

I can specify the kubernetes nodeSelector attribute to select a specific node.

```<code>kind: Pod
...
spec:
  ...
  nodeSelector:
    ???
</code>```

Question

Can I specify the nodeSelector rule to use a node in a specific Availability Set?

I could label the pods manually after creation. But is there an automatic solution?

答:
first of all, this question makes no sense, as with availability sets you can only have 1 node pool with AKS (and your tags mention AKS) (at least supported). but still, nodes have labels that look like this:

```<code>agentpool=pool_name
</code>```

so your node selector would looks like this:

```<code>  nodeSelector:
    agentpool: pool_name
</code>```

Body:
Requirement

Kubernetes in Azure uses Availability Sets as the default availability strategy.

I can specify the kubernetes nodeSelector attribute to select a specific node.

kind: Pod
...
spec:
  ...
  nodeSelector:
    ???

Question

Can I specify the nodeSelector rule to use a node in a specific Availability Set?

I could label the pods manually after creation. But is there an automatic solution?

Body:
first of all, this question makes no sense, as with availability sets you can only have 1 node pool with AKS (and your tags mention AKS) (at least supported). but still, nodes have labels that look like this:

agentpool=pool_name

so your node selector would looks like this:

  nodeSelector:
    agentpool: pool_name


问:
Cucumber feature file does not identify the steps
I have written my firsy cucumber feature file. When I run the feature file as Cucumber Feature, I get below errors

"WARNING: Cucumber-JVM's --format option is deprecated. Please use --plugin instead." - I used "plugin" in my @CucumberOptions of runner class, but still getting the same error

2.It says I do not have any scenario and steps
Feature: Validate Modular GUI pages

Scenario: Validate Login Page # C:/Selenium/RegressionTest/ModularRegression/src/GUI/features/Validate.feature:3
    Given: Modular GUI is opened
    When: Validate the login page
    Then: Login to the Modular

0 Scenarios
0 Steps

I'm not getting snippets for my steps.

I have added following jars to the library
Jars

This is my runner class,
package GUI;

```<code>import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        format = {"pretty", "json:target/"},
        features = {"src/GUI/"}
        )
public class GUIRunner {

}
</code>```

This is my feature file,

```<code>Feature: Validate Modular GUI pages

  Scenario: Validate Login Page
    Given: Modular GUI is opened
    When: Validate the login page
    Then: Login to the Modular
</code>```

I would really appreciate if someone can point out what is missing in my code.

Thank you very much

[EDITED]
This is the actual error:

WARNING: Cucumber-JVM's --format option is deprecated. Please use
  --plugin instead. Feature: Validate Modular GUI pages

Scenario: Validate Login Page #
  C:/Selenium/RegressionTest/ModularRegression/src/GUI/features/Validate.feature:3
      Given: Modular GUI is opened
      When: Validate the login page
      Then: Login to the Modular

0 Scenarios 0 Steps 0m0.000s

答: Please add tags = {"@SmokeTest"} or tags = {"@RegresionTest"}

Body:
I have written my firsy cucumber feature file. When I run the feature file as Cucumber Feature, I get below errors

"WARNING: Cucumber-JVM's --format option is deprecated. Please use --plugin instead." - I used "plugin" in my @CucumberOptions of runner class, but still getting the same error

2.It says I do not have any scenario and steps
Feature: Validate Modular GUI pages

Scenario: Validate Login Page # C:/Selenium/RegressionTest/ModularRegression/src/GUI/features/Validate.feature:3
    Given: Modular GUI is opened
    When: Validate the login page
    Then: Login to the Modular

0 Scenarios
0 Steps

I'm not getting snippets for my steps.

I have added following jars to the library
Jars

This is my runner class,
package GUI;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        format = {"pretty", "json:target/"},
        features = {"src/GUI/"}
        )
public class GUIRunner {

}

This is my feature file,

Feature: Validate Modular GUI pages

  Scenario: Validate Login Page
    Given: Modular GUI is opened
    When: Validate the login page
    Then: Login to the Modular

I would really appreciate if someone can point out what is missing in my code.

Thank you very much

[EDITED]
This is the actual error:

WARNING: Cucumber-JVM's --format option is deprecated. Please use
  --plugin instead. Feature: Validate Modular GUI pages

Scenario: Validate Login Page #
  C:/Selenium/RegressionTest/ModularRegression/src/GUI/features/Validate.feature:3
      Given: Modular GUI is opened
      When: Validate the login page
      Then: Login to the Modular

0 Scenarios 0 Steps 0m0.000s


问:
'deploying' a ruby script with gems
i've written several Ruby scripts that work together to from a console application.
These scripts are written on an Ubuntu platform, but I want to be able to run them from a Windows platform as well.

The problem I'm currently facing is porting over all the gems. I've downloaded sources of most gems and made some bug fixes on them, but is it possible to package them for example with my scripts so they're available?
I'm thinking a bit DLL like here as Windows does.

I can probably add a readme file, stating which gems are required and where/how to obtain them, but it would be easier if I could package them.

答:
Maybe you could look at http://www.erikveen.dds.nl/rubyscript2exe/index.html which does some packaging for ruby application (including the ruby interpreter, too)

You could also build a gem with your script in it along with all needed gems directly inside the gem. Provided their licences allow you to do that, it could be a reasonable solution ( Gem supports platform flavoured gems http://docs.rubygems.org/read/chapter/20#platform )

Title: 'deploying' a ruby script with gems


问:
How to set custom executable icon using electron-packager?

I have successfully built an Electron app. Now I'm trying to change the icon of the .exe that is generated by electron-packager. However, the .exe gets the default Electron icon, not my own icon (see screenshot).

The command I run: npm run build

The corresponding script in package.json:

```<code>"build": "electron-packager --out winx64 --overwrite --platform win32 --appname clientlmcenter . --icon my_logo.ico"
</code>```

The file my_logo.ico is present in the root directory.

答:
You have to put icon argument like this

```<code>--icon=./my_logo.ico
</code>```

Also make sure the logo is in the current directory where you execute npm run build

Body:
I have successfully built an Electron app. Now I'm trying to change the icon of the .exe that is generated by electron-packager. However, the .exe gets the default Electron icon, not my own icon (see screenshot).

The command I run: npm run build

The corresponding script in package.json:

"build": "electron-packager --out winx64 --overwrite --platform win32 --appname clientlmcenter . --icon my_logo.ico"

The file my_logo.ico is present in the root directory.

Body:
You have to put icon argument like this

--icon=./my_logo.ico

Also make sure the logo is in the current directory where you execute npm run build