问:
Django Admin keeps returning 504 timeout ( nginx +uWSGI )
This is my nginx configuration:

```<code>server {
    listen 80;
    listen [::]:80;

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name www.nameOfSite.id nameOfSite.id;

    access_log  off;
    error_log  /var/www/log_nginx/error.log;
    gzip on;
    gzip_disable "msie6";

    client_header_timeout 180s;
    client_body_timeout 180s;
    client_max_body_size 100m;

    proxy_connect_timeout   120s;
    proxy_send_timeout      180s;
    proxy_read_timeout      180s;
    send_timeout            600s;

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    location /static {
        alias /var/www/django/static;
    }

    location /media {
       alias /var/www/django/media;
    }

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        include         uwsgi_params;
        uwsgi_read_timeout 500;
        uwsgi_send_timeout 500;
        uwsgi_pass      unix:/var/www/uwsgi_texas.sock;
    }

}
</code>```

This is my uWSGI ini file in /var/www/texas_uwsgi.ini:

```<code>[uwsgi]
socket = /var/www/uwsgi_texas.sock
chdir = /var/www/django/
wsgi-file = /var/www/django/django/wsgi.py
processes = 8
threads = 1
master = true
harakiri = 900
chmod-socket = 777
vacuum = true
</code>```

This is my service file in /etc/systemd/system/texas.service:

```<code>[Unit]
Description=TEXAS
After=syslog.target

[Service]
ExecStart=/usr/local/bin/uwsgi --ini /var/www/texas_uwsgi.ini
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=main

[Install]
WantedBy=multi-user.target
</code>```

The problem is when i enter the Django admin for one Model object that have a lot of inline objects and fields, it keeps returning 504 timeout because it takes more than 60 seconds to process. I checked my NGINX, uWSGI configurations, i cannot find the solution on how to increase this "60 seconds timeout". The rest of the pages works fine.

In my nginx configuration, i already tried:

```<code>proxy_connect_timeout   120s;
proxy_send_timeout      180s;
proxy_read_timeout      180s;
send_timeout            600s;
uwsgi_read_timeout 500;
uwsgi_send_timeout 500;
</code>```

This is the result when i try to open that Model Admin page:

答:
Maybe use raw_id fields(for the inline models) for loading the admin wherever necessary.

Refer: Django Admin raw_id_fields

by doing so you can bypass the 504 error

Body:
This is my nginx configuration:

server {
    listen 80;
    listen [::]:80;

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name www.nameOfSite.id nameOfSite.id;

    access_log  off;
    error_log  /var/www/log_nginx/error.log;
    gzip on;
    gzip_disable "msie6";

    client_header_timeout 180s;
    client_body_timeout 180s;
    client_max_body_size 100m;

    proxy_connect_timeout   120s;
    proxy_send_timeout      180s;
    proxy_read_timeout      180s;
    send_timeout            600s;

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    location /static {
        alias /var/www/django/static;
    }

    location /media {
       alias /var/www/django/media;
    }

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        include         uwsgi_params;
        uwsgi_read_timeout 500;
        uwsgi_send_timeout 500;
        uwsgi_pass      unix:/var/www/uwsgi_texas.sock;
    }

}

This is my uWSGI ini file in /var/www/texas_uwsgi.ini:

[uwsgi]
socket = /var/www/uwsgi_texas.sock
chdir = /var/www/django/
wsgi-file = /var/www/django/django/wsgi.py
processes = 8
threads = 1
master = true
harakiri = 900
chmod-socket = 777
vacuum = true

This is my service file in /etc/systemd/system/texas.service:

[Unit]
Description=TEXAS
After=syslog.target

[Service]
ExecStart=/usr/local/bin/uwsgi --ini /var/www/texas_uwsgi.ini
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=main

[Install]
WantedBy=multi-user.target

The problem is when i enter the Django admin for one Model object that have a lot of inline objects and fields, it keeps returning 504 timeout because it takes more than 60 seconds to process. I checked my NGINX, uWSGI configurations, i cannot find the solution on how to increase this "60 seconds timeout". The rest of the pages works fine.

In my nginx configuration, i already tried:

proxy_connect_timeout   120s;
proxy_send_timeout      180s;
proxy_read_timeout      180s;
send_timeout            600s;
uwsgi_read_timeout 500;
uwsgi_send_timeout 500;

This is the result when i try to open that Model Admin page:


来源: stackexchange

问:
How do i send a Firebase Push Notification via java instead of the FirebaseConsole?
I'm getting into Firebase Cloud Messaging, and i would like to know how to send a message in a Push Notification with java code, instead of manually writing it in the Firebase Console.

Thanks in advance.

答:
The only option at the moment is to call the REST API for Firebase Cloud Messaging from your Java code.

The REST API is covered here: https://firebase.google.com/docs/cloud-messaging/send-message. You'll also want to read about authenticating the request, which includes a Java sample.

If you can't get it working from those yet, also have a look at some of the previous questions about the topic.

ContentLicense: CC BY-SA 3.0


问:
jQuery is not defined error in karma tests
I am using jQuery in my angular 5 app which works perfectly but I have an issue with karma tests.

```<code>import { ElementRef } from '@angular/core';
declare var jQuery: any;

export class Item {

constructor(private element: ElementRef) {
    this.init();
}

private init() {
    this.$item = jQuery(this.element.nativeElement);
...
</code>```

error

ReferenceError: jQuery is not defined.

package.json

```<code>"dependencies": {
  "jquery": "3.1.1"
}
</code>```

I have added jquery to my karma.conf but that didn't help.

```<code>files: [
        'node_modules/core-js/client/shim.js',
        'node_modules/systemjs/dist/system.src.js',
        'node_modules/zone.js/dist/zone.js',
        'node_modules/zone.js/dist/proxy.js',
        'node_modules/zone.js/dist/sync-test.js',
        'node_modules/zone.js/dist/jasmine-patch.js',
        'node_modules/zone.js/dist/async-test.js',
        'node_modules/zone.js/dist/fake-async-test.js',
        'node_modules/tslib/tslib.js',
        'node_modules/jquery/dist/jquery.js',

        {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
        {pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
        {pattern: '../karma-test-shim.js', included: true, watched: true},
        {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},
        {pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false},
        {pattern: 'node_modules/@ng-idle/core/bundles/core.umd.js', included: false, watched: false},
        {pattern: 'node_modules/bowser/bowser.js', included: false, watched: false},
        {pattern: 'node_modules/bootstrap/dist/js/bootstrap.js', included: false, watched: false},
        {pattern: 'node_modules/tslib/tslib.js', included: false, watched: false},
        {pattern: 'node_modules/jquery/dist/jquery.js', included: false, watched: false}
    ],
    proxies: {
        "/node_modules/": "../../node_modules/"
    },
    autoWatch: true,
    browsers: ['PhantomJS', 'Chrome', 'HeadlessChrome'],
    singleRun: false
});
};
</code>```

can you someone please help?

Thanks in advance.

答:
Include the jQuery path in the karma.conf.js

```<code>module.exports = function(config) {
  config.set({
    files: [
      'path_to/jquery.js'
      ...
    ],
  });
};
</code>```

Body:
I am using jQuery in my angular 5 app which works perfectly but I have an issue with karma tests.

import { ElementRef } from '@angular/core';
declare var jQuery: any;

export class Item {

constructor(private element: ElementRef) {
    this.init();
}

private init() {
    this.$item = jQuery(this.element.nativeElement);
...

error

ReferenceError: jQuery is not defined.

package.json

"dependencies": {
  "jquery": "3.1.1"
}

I have added jquery to my karma.conf but that didn't help.

files: [
        'node_modules/core-js/client/shim.js',
        'node_modules/systemjs/dist/system.src.js',
        'node_modules/zone.js/dist/zone.js',
        'node_modules/zone.js/dist/proxy.js',
        'node_modules/zone.js/dist/sync-test.js',
        'node_modules/zone.js/dist/jasmine-patch.js',
        'node_modules/zone.js/dist/async-test.js',
        'node_modules/zone.js/dist/fake-async-test.js',
        'node_modules/tslib/tslib.js',
        'node_modules/jquery/dist/jquery.js',

        {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
        {pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
        {pattern: '../karma-test-shim.js', included: true, watched: true},
        {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},
        {pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false},
        {pattern: 'node_modules/@ng-idle/core/bundles/core.umd.js', included: false, watched: false},
        {pattern: 'node_modules/bowser/bowser.js', included: false, watched: false},
        {pattern: 'node_modules/bootstrap/dist/js/bootstrap.js', included: false, watched: false},
        {pattern: 'node_modules/tslib/tslib.js', included: false, watched: false},
        {pattern: 'node_modules/jquery/dist/jquery.js', included: false, watched: false}
    ],
    proxies: {
        "/node_modules/": "../../node_modules/"
    },
    autoWatch: true,
    browsers: ['PhantomJS', 'Chrome', 'HeadlessChrome'],
    singleRun: false
});
};

can you someone please help?

Thanks in advance.

Body:
Include the jQuery path in the karma.conf.js

module.exports = function(config) {
  config.set({
    files: [
      'path_to/jquery.js'
      ...
    ],
  });
};


问:
Creating new column with letters v from beginning to last row
How do I add a new empty column with the letters 'v' from beginning to the last row.

df1:

```<code>    AM
0   MA
1   Ming
2   Mo
</code>```

Desired output for df1:

```<code>    AM    C
0   MA    v
1   Ming  v
2   Mo    v
</code>```

I get error: AttributeError: 'DataFrame' object has no attribute 'Sample'

When  I try this:

```<code>df1["C"] = np.nan
df1
df1["C"] = df1.Sample.str['v']
</code>```

答:
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c'])}

dd = pd.DataFrame(d)

print dd

one

a    1

b    2

c    3

dd = pd.DataFrame(d)

dd['df'] = 'test'

print dd

one    df

a    1  test

b    2  test

c    3  test

Body:
How do I add a new empty column with the letters 'v' from beginning to the last row.

df1:

    AM
0   MA
1   Ming
2   Mo

Desired output for df1:

    AM    C
0   MA    v
1   Ming  v
2   Mo    v

I get error: AttributeError: 'DataFrame' object has no attribute 'Sample'

When  I try this:

df1["C"] = np.nan
df1
df1["C"] = df1.Sample.str['v']


问:
How to use curl in java and parse json response
I have a curl command that gives a JSON response. I want to use this curl command in java & parse the JSON response in java. Is it possible to do so??

With below Java code:

```<code>public static void main(String[] args) throws Throwable {

    try {
        InputStream stream = Runtime.getRuntime().exec("curl --globoff --insecure --silent -u username:password -X GET -H 'Content-Type: application/json' \"http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=Timetracking\"").getInputStream();

        BufferedReader input = new BufferedReader(new InputStreamReader(stream), 1);

        input.readLine();
        input.read();
        input.read();

        DataReader reader = new JsonReader(input)
                .addField("TimeSpent", "//array/object/timespent")
                .addRecordBreak("//array/object");

        /*reader = new TransformingReader(reader)
                .add(new BasicFieldTransformer("TimeSpent").stringToDouble());*/

        DataWriter writer = new StreamWriter(System.out);

        JobTemplate.DEFAULT.transfer(reader, writer);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

I get the following error:

```<code>Cannot run program "curl": CreateProcess error=2, The system cannot find the file specified
</code>```

答:
```<code>        Runtime rt = Runtime.getRuntime();
        Process p1;
        Process p2;
        try {
            String postSubmissionJSon = "{"data":"value"}";

            String[] stringPost = {"curl", "-X", "POST", "https://your-url.com/api/posts",
                "--cert", "test.crt.pem",
                "--key", "test.key.pem",
                "-H", "accept: application/json",
                "-H", "content-type: application/json",
                "-d", postSubmissionJSon};

            ProcessBuilder ps = new ProcessBuilder(stringPost);
            //ps.redirectErrorStream(true);
            Process pr = ps.start();
            pr.waitFor();

            BufferedReader reader2 = new BufferedReader(new InputStreamReader(pr.getInputStream()));

            String line2 = "";
            while ((line2 = reader2.readLine()) != null) {
                output.append(line2 + "\n");
            }

            System.out.println("\n\n\noutput====" + output + "===\n\n\n");

            String sbToString = output.toString();

            jSONObject = new JSONObject(sbToString);

            System.out.println(jSONObject.toString());

            p1 = Runtime.getRuntime().exec("pwd");
            p1.waitFor();
            BufferedReader reader1a
                    = new BufferedReader(new InputStreamReader(p1.getInputStream()));

            String line1a = "";
            while ((line1a = reader1a.readLine()) != null) {
                output.append(line1a + "\n");
                System.out.println("output====" + output + "===");
            }
        } catch (Exception e) {
            System.out.println("===============ERROR===============\n" + e.getMessage() + "\n\n\n");
        }
</code>```

<p>/*NOTE : Your Key (test.key.pem) and Cert (test.crt.pem) should be located on your proper directory. For glassfish it is on "~/glassfish4/glassfish/domains/domain1/config" or your can specify exact location by changing "--cert", "test.crt.pem" --> "/home/user/files/test.crt.pem".  Same with the key.
*/</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a curl command that gives a JSON response. I want to use this curl command in java & parse the JSON response in java. Is it possible to do so??

With below Java code:

public static void main(String[] args) throws Throwable {

    try {
        InputStream stream = Runtime.getRuntime().exec("curl --globoff --insecure --silent -u username:password -X GET -H 'Content-Type: application/json' \"http://ficcjira.xyz.com/rest/api/2/search?jql=project=ABC&fields=Timetracking\"").getInputStream();

        BufferedReader input = new BufferedReader(new InputStreamReader(stream), 1);

        input.readLine();
        input.read();
        input.read();

        DataReader reader = new JsonReader(input)
                .addField("TimeSpent", "//array/object/timespent")
                .addRecordBreak("//array/object");

        /*reader = new TransformingReader(reader)
                .add(new BasicFieldTransformer("TimeSpent").stringToDouble());*/

        DataWriter writer = new StreamWriter(System.out);

        JobTemplate.DEFAULT.transfer(reader, writer);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I get the following error:

Cannot run program "curl": CreateProcess error=2, The system cannot find the file specified

Body:
        Runtime rt = Runtime.getRuntime();
        Process p1;
        Process p2;
        try {
            String postSubmissionJSon = "{"data":"value"}";

            String[] stringPost = {"curl", "-X", "POST", "https://your-url.com/api/posts",
                "--cert", "test.crt.pem",
                "--key", "test.key.pem",
                "-H", "accept: application/json",
                "-H", "content-type: application/json",
                "-d", postSubmissionJSon};

            ProcessBuilder ps = new ProcessBuilder(stringPost);
            //ps.redirectErrorStream(true);
            Process pr = ps.start();
            pr.waitFor();

            BufferedReader reader2 = new BufferedReader(new InputStreamReader(pr.getInputStream()));

            String line2 = "";
            while ((line2 = reader2.readLine()) != null) {
                output.append(line2 + "\n");
            }

            System.out.println("\n\n\noutput====" + output + "===\n\n\n");

            String sbToString = output.toString();

            jSONObject = new JSONObject(sbToString);

            System.out.println(jSONObject.toString());

            p1 = Runtime.getRuntime().exec("pwd");
            p1.waitFor();
            BufferedReader reader1a
                    = new BufferedReader(new InputStreamReader(p1.getInputStream()));

            String line1a = "";
            while ((line1a = reader1a.readLine()) != null) {
                output.append(line1a + "\n");
                System.out.println("output====" + output + "===");
            }
        } catch (Exception e) {
            System.out.println("===============ERROR===============\n" + e.getMessage() + "\n\n\n");
        }

/*NOTE : Your Key (test.key.pem) and Cert (test.crt.pem) should be located on your proper directory. For glassfish it is on "~/glassfish4/glassfish/domains/domain1/config" or your can specify exact location by changing "--cert", "test.crt.pem" --> "/home/user/files/test.crt.pem".  Same with the key.
*/


问:
Difference between AOT and JIT compiler in the ART
In Marshmallow there was an AOT compiler added with ART. From Android N another compiler JIT was added in addition with AOT.

What are AOT compiler specific job/features and what areJIT compiler job/features?

答:
In Android Java classes converted into DEX bytecode.
The DEX bytecode format is translated to native machine code via either ART or the Dalvik runtimes.

Dalvik is a JIT (Just in time) compilation based engine. There were
  drawbacks to use Dalvik hence from Android 4.4 (kitkat) ART was
  introduced as a runtime and from Android 5.0 (Lollipop) it has
  completely replaced Dalvik. Android 7.0 adds a just-in-time (JIT)
  compiler with code profiling to Android runtime (ART) that constantly
  improves the performance of Android apps as they run.

(Dalvik used JIT (Just in time) compilation whereas ART uses AOT (Ahead of time) compilation.)

Just In Time (JIT):

With the Dalvik JIT compiler, each time when the app is run, it dynamically translates a part of the Dalvik bytecode into machine code. As the execution progresses, more bytecode is compiled and cached. Since JIT compiles only a part of the code, it has a smaller memory footprint and uses less physical space on the device.

Ahead Of Time (AOT):

ART is equipped with an Ahead-of-Time compiler. During the app’s installation phase, it statically translates the DEX bytecode into machine code and stores in the device’s storage. This is a one-time event which happens when the app is installed on the device.

Android N includes a hybrid runtime:

There won’t be any compilation during install, and applications can be started right away,
the bytecode being interpreted. There is a new, faster interpreter in ART and it is accompanied by a new JIT, but the JIT information is not persisted.
Instead, the code is profiled during execution and the resulted data is saved.

Benefits of ART:

Apps run faster as DEX bytecode translation done during installation.

Reduces startup time of applications as native code is directly executed.

Improves battery performance as power utilized to interpreted byte codes line by line is saved.

Improved garbage collector.

Drawbacks of ART:

App Installation takes more time because of DEX bytecodes conversion into machine code during installation.

As the native machine code generated on installation is stored in internal storage, more internal storage is required.


问:
Container preferred size Codename One
I seem to be getting confused with how Containers calculate their height compared to the components in the container.

I have a Container with a TableLayout that has 1 row and 2 columns. In both cells there are different TextAreas.

```<code>TableLayout tl = new TableLayout(1, 2);
Container container = new Container(tl);
TextArea ta1 = new TextArea("Some long text");
TextArea ta2 = new TextArea("Some other long text");
container.add(tl.createConstraint().widthPercentage(50), ta1);
container.add(tl.createConstraint().widthPercentage(50), ta2);
</code>```

The problem I am having is that the height of container is about double the height of the two TextAreas which leaves a big, unneeded, gap under the TextAreas.

I have tried overriding the calcPreferredSize method which seems to work with any Dimension I put in. The issue is I don't know what the height of the two TextAreas will be.

What am I doing wrong?

Thanks.

答:
This is an inherent reflow problem. Text area doesn't "know" how much space it will be given so it requests a specific preferred size from the parent layout.

The parent layout uses its own logic which has some relation to preferred size but also some relation to your requests (e.g. 50% width, 2 columns). It gives the text area the space it "thinks" would work. If it doesn't the text area tries to resize once but that can work our inaccurately.

Some frameworks e.g. HTML support a concept of reflow which constantly lays out everything. That's generally why HTML is slower than most native UI's. Reflow seems neat but it's often hard to detect when it's being taxed to "destroy your CPU".

A common trick to avoid this is to determine the rows/columns of a text area and disable the grow with content option of the text area. That makes the component more deterministic in size and also slightly boosts performance. However, it can lead to undesired effects such as text being cropped.

Title: Container preferred size Codename One

Body:
I seem to be getting confused with how Containers calculate their height compared to the components in the container.

I have a Container with a TableLayout that has 1 row and 2 columns. In both cells there are different TextAreas.

TableLayout tl = new TableLayout(1, 2);
Container container = new Container(tl);
TextArea ta1 = new TextArea("Some long text");
TextArea ta2 = new TextArea("Some other long text");
container.add(tl.createConstraint().widthPercentage(50), ta1);
container.add(tl.createConstraint().widthPercentage(50), ta2);

The problem I am having is that the height of container is about double the height of the two TextAreas which leaves a big, unneeded, gap under the TextAreas.

I have tried overriding the calcPreferredSize method which seems to work with any Dimension I put in. The issue is I don't know what the height of the two TextAreas will be.

What am I doing wrong?

Thanks.


问:
How to move or delete a specific element in std::forward_list?
I've been trying to work this out for more than an hour. I need to move an integer from middle of the list to the beginning. There is no option for moving an integer, it would be fine if I could insert one at the beginning and delete the old one from middle, but you can't do that either. (you can delete every entry of a specific integer, not a single one)

I read everything there was about std::forward_list on cplusplus.com and googled this for 15 minutes, no results.

答:
You can use Dobly Link list. ( i hope simple link list can also do your task)
Here is the link for doubly link list. https://www.hackerearth.com/practice/notes/doubly-linked-list-data-structure-in-c/
Follow these steps:
 1. Copy middle element.
 2. add that copied element to the start of list.
 3. remove the middle element.
If you are using some library of list that is restricting you, make your own class of list of which removal from any index is possible. </p>


问:
SQL intersect, union?
I have two tables EVENTS, and USER

EVENTS has fields "id", "name", "date"

USER has 1 field "id"

I want an SQL query to get all of the EVENT names of only the events that have the matching id's in USER. In other words, take all of the id's from USER, find the matching id's in EVENTS, display the name of the events that have those id's.

specifically, i want to display a list in html with all of these names

Thank you!

答:
U can use it directly using a WHERE Statement</p>

```<code>select u.id,e.name
from
USER u,EVENTS e
where u.id = e.id;
</code>```

Title: SQL intersect, union?

Body:
U can use it directly using a WHERE Statement

select u.id,e.name
from
USER u,EVENTS e
where u.id = e.id;


问:
How to i hide a password in web page
This is my html code for my login page. If I echo the password in the same page, the password is echoed as is. How do I hide the password string so the password is displayed like ******* instead?

```<code><div class="form">
    <div style="width:20%; float:left;"> </div>
        <div style="width:60%; padding:10px 10px 80px 10px; position:relative; margin-top: 6%; float: left;">
            <form action="login.php" method="post">
                <h2 style= color:orange; >Log In</h2>
                <h3 style=  color:orange;>User name:<input type="text" id="username" name="username" required></h3>
                <h3 style= color:orange; >User password:<input type="password" id="password" name="password" required></h3>
                <button type="submit" name="submit" value="Submit"  style= color:orange; >Login</button>
            </form>
        </div>

    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    include('session.php');

    echo $Name = $_POST['username'];
    echo $psw  = $_POST['password'];
    $_SESSION["username"]=$Name ;

    if(mysql_errno() != 0) {
        echo "Query Failed".mysql_errno();
    }

    $row = mysqli_fetch_array($login);
    $password = $row['Pass_word'];

    if($password==$psw) {
        header('location:menu.php');
        exit();
        echo $Name;
    } else {
        echo "<h6 style='text-align:center; color:Red'> USERNAME AND PASSWORD DOES NOT MATCH </h6>";
    }
}
mysqli_close($conn);
</code>```

答:
If you want to secure your password use any php encryption function for that. You could not completely hide the password characters.

You can use md5(), crypt(), password_hash(), etc. function and encrypt your password and store encrypted password in your database.

Title: How to i hide a password in web page

Body:
This is my html code for my login page. If I echo the password in the same page, the password is echoed as is. How do I hide the password string so the password is displayed like ******* instead?

            <form action="login.php" method="post">

Log In

User name:<input type="text" id="username" name="username" required>

User password:<input type="password" id="password" name="password" required>

                <button type="submit" name="submit" value="Submit"  style= color:orange; >Login</button>
            </form>

    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    include('session.php');

    echo $Name = $_POST['username'];
    echo $psw  = $_POST['password'];
    $_SESSION["username"]=$Name ;

    if(mysql_errno() != 0) {
        echo "Query Failed".mysql_errno();
    }

    $row = mysqli_fetch_array($login);
    $password = $row['Pass_word'];

    if($password==$psw) {
        header('location:menu.php');
        exit();
        echo $Name;
    } else {
        echo "
 USERNAME AND PASSWORD DOES NOT MATCH
";
    }
}
mysqli_close($conn);


问:
openWRT Makefile for python backports-abc
I'm attempting to build the backports-abc python module in to my OpenWRT build, and need a bit of help on the build/extraction process.

My issue seems to be that the downloaded backports-abc tar file extracts the content to backports_abc-0.5 due to the underlying tar file structure, but the build process is looking for the setup.py etc under backports-abc-0.5 (see below). I can manually copy the files over and rebuild, and that works fine, but that's not ideal. Also, though it builds OK, when I load the image to the device, the backports module is missing.

```<code>/home/ubuntu/build2/openwrt/staging_dir/host/bin/python2: can't open file './setup.py': [Errno 2] No such file or directory
Makefile:59: recipe for target '/home/ubuntu/build2/openwrt/build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/backports-abc-0.5//.built' failed
make[3]: *** [/home/ubuntu/build2/openwrt/build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/backports-abc-0.5//.built] Error 2
make[3]: Leaving directory '/home/ubuntu/build2/openwrt/feeds/linkit/python-backports-abc
</code>```

'

The openWRT documentation around Makefiles is a bit vague, and so is my understanding of the process.

How do I get the tar file extracted to the right folder, or where in the Makefile process should I just copy the files to a correct folder?

Here's my Makefile.

```<code>include $(TOPDIR)/rules.mk

PKG_NAME:=backports_abc
PKG_VERSION:=0.5
PKG_RELEASE:=1
PKG_SOURCE:=backports_abc-0.5.tar.gz
PKG_SOURCE_URL:=https://pypi.python.org/packages/68/3c/1317a9113c377d1e33711ca8de1e80afbaf4a3c950dd0edfaf61f9bfe6d8/
PKG_MD5SUM:=7d1936ec183a3586290adf60f6f96764
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)/

#PKG_BUILD_DEPENDS:=python-setuptools

include $(INCLUDE_DIR)/package.mk
$(call include_mk, python-package.mk)

define Package/backports_abc
        SECTION:=lang-python
        CATEGORY:=Languages
        SUBMENU:=Python
        TITLE:=backports_abc
        URL:=https://pypi.python.org/pypi/backports_abc/0.5
        DEPENDS:=+python
endef

define Package/backports_abc/description
        A backport of recent additions to the 'collections.abc' module.
endef

define Build/Compile
        $(call Build/Compile/PyMod,., \
                install --prefix="/usr" --root="$(PKG_INSTALL_DIR)" \
        )
endef

define Build/InstallDev
        $(INSTALL_DIR) $(STAGING_DIR)$(PYTHON_PKG_DIR)
        $(CP) \
                $(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
                $(STAGING_DIR)$(PYTHON_PKG_DIR)/
        [ ! -e $(PKG_INSTALL_DIR)/usr/include ] || $(CP) \
                $(PKG_INSTALL_DIR)/usr/include/* \
                $(STAGING_DIR)/usr/include/
endef

define Package/backportsabc/install
        $(INSTALL_DIR) $(1)$(PYTHON_PKG_DIR)/
        $(CP) \
                $(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
                $(1)$(PYTHON_PKG_DIR)/
endef

$(eval $(call BuildPackage,backports_abc))
</code>```

答:
I resolved this by fixing up some underscores and hyphens... ie: backports_abc and backports-abc
Basically..
This... PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)/
meant that it was looking for the files based on the PKG_NAME variable.

```<code>include $(TOPDIR)/rules.mk

PKG_NAME:=backports_abc
PKG_VERSION:=0.5
PKG_RELEASE:=1
PKG_SOURCE:=backports_abc-0.5.tar.gz
PKG_SOURCE_URL:=https://pypi.python.org/packages/68/3c/1317a9113c377d1e33711ca8de1e80afbaf4a3c950dd0edfaf61f9bfe6d8/
PKG_MD5SUM:=7d1936ec183a3586290adf60f6f96764
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)/

#PKG_BUILD_DEPENDS:=python-setuptools

include $(INCLUDE_DIR)/package.mk
$(call include_mk, python-package.mk)

define Package/backports-abc
    SECTION:=lang-python
    CATEGORY:=Languages
    SUBMENU:=Python
    TITLE:=backports-abc
    URL:=https://pypi.python.org/pypi/backports_abc/0.5
    DEPENDS:=+python
endef

define Package/backports-abc/description
    A backport of recent additions to the 'collections.abc' module.
endef

define Build/Compile
    $(call Build/Compile/PyMod,., \
        install --prefix="/usr" --root="$(PKG_INSTALL_DIR)" \
    )
endef

define Build/InstallDev
    $(INSTALL_DIR) $(STAGING_DIR)$(PYTHON_PKG_DIR)
    $(CP) \
        $(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
        $(STAGING_DIR)$(PYTHON_PKG_DIR)/
    [ ! -e $(PKG_INSTALL_DIR)/usr/include ] || $(CP) \
        $(PKG_INSTALL_DIR)/usr/include/* \
        $(STAGING_DIR)/usr/include/
endef

define Package/backports-abc/install
    $(INSTALL_DIR) $(1)$(PYTHON_PKG_DIR)/
    $(CP) \
        $(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
        $(1)$(PYTHON_PKG_DIR)/
endef

$(eval $(call BuildPackage,backports-abc))
</code>```

Body:
I'm attempting to build the backports-abc python module in to my OpenWRT build, and need a bit of help on the build/extraction process.

My issue seems to be that the downloaded backports-abc tar file extracts the content to backports_abc-0.5 due to the underlying tar file structure, but the build process is looking for the setup.py etc under backports-abc-0.5 (see below). I can manually copy the files over and rebuild, and that works fine, but that's not ideal. Also, though it builds OK, when I load the image to the device, the backports module is missing.

/home/ubuntu/build2/openwrt/staging_dir/host/bin/python2: can't open file './setup.py': [Errno 2] No such file or directory
Makefile:59: recipe for target '/home/ubuntu/build2/openwrt/build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/backports-abc-0.5//.built' failed
make[3]: *** [/home/ubuntu/build2/openwrt/build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/backports-abc-0.5//.built] Error 2
make[3]: Leaving directory '/home/ubuntu/build2/openwrt/feeds/linkit/python-backports-abc

'

The openWRT documentation around Makefiles is a bit vague, and so is my understanding of the process.

How do I get the tar file extracted to the right folder, or where in the Makefile process should I just copy the files to a correct folder?

Here's my Makefile.

include $(TOPDIR)/rules.mk

PKG_NAME:=backports_abc
PKG_VERSION:=0.5
PKG_RELEASE:=1
PKG_SOURCE:=backports_abc-0.5.tar.gz
PKG_SOURCE_URL:=https://pypi.python.org/packages/68/3c/1317a9113c377d1e33711ca8de1e80afbaf4a3c950dd0edfaf61f9bfe6d8/
PKG_MD5SUM:=7d1936ec183a3586290adf60f6f96764
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)/

#PKG_BUILD_DEPENDS:=python-setuptools

include $(INCLUDE_DIR)/package.mk
$(call include_mk, python-package.mk)

define Package/backports_abc
        SECTION:=lang-python
        CATEGORY:=Languages
        SUBMENU:=Python
        TITLE:=backports_abc
        URL:=https://pypi.python.org/pypi/backports_abc/0.5
        DEPENDS:=+python
endef

define Package/backports_abc/description
        A backport of recent additions to the 'collections.abc' module.
endef

define Build/Compile
        $(call Build/Compile/PyMod,., \
                install --prefix="/usr" --root="$(PKG_INSTALL_DIR)" \
        )
endef

define Build/InstallDev
        $(INSTALL_DIR) $(STAGING_DIR)$(PYTHON_PKG_DIR)
        $(CP) \
                $(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
                $(STAGING_DIR)$(PYTHON_PKG_DIR)/
        [ ! -e $(PKG_INSTALL_DIR)/usr/include ] || $(CP) \
                $(PKG_INSTALL_DIR)/usr/include/* \
                $(STAGING_DIR)/usr/include/
endef

define Package/backportsabc/install
        $(INSTALL_DIR) $(1)$(PYTHON_PKG_DIR)/
        $(CP) \
                $(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
                $(1)$(PYTHON_PKG_DIR)/
endef

$(eval $(call BuildPackage,backports_abc))

Body:
I resolved this by fixing up some underscores and hyphens... ie: backports_abc and backports-abc
Basically..
This... PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)/
meant that it was looking for the files based on the PKG_NAME variable.

include $(TOPDIR)/rules.mk

PKG_NAME:=backports_abc
PKG_VERSION:=0.5
PKG_RELEASE:=1
PKG_SOURCE:=backports_abc-0.5.tar.gz
PKG_SOURCE_URL:=https://pypi.python.org/packages/68/3c/1317a9113c377d1e33711ca8de1e80afbaf4a3c950dd0edfaf61f9bfe6d8/
PKG_MD5SUM:=7d1936ec183a3586290adf60f6f96764
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)/

#PKG_BUILD_DEPENDS:=python-setuptools

include $(INCLUDE_DIR)/package.mk
$(call include_mk, python-package.mk)

define Package/backports-abc
    SECTION:=lang-python
    CATEGORY:=Languages
    SUBMENU:=Python
    TITLE:=backports-abc
    URL:=https://pypi.python.org/pypi/backports_abc/0.5
    DEPENDS:=+python
endef

define Package/backports-abc/description
    A backport of recent additions to the 'collections.abc' module.
endef

define Build/Compile
    $(call Build/Compile/PyMod,., \
        install --prefix="/usr" --root="$(PKG_INSTALL_DIR)" \
    )
endef

define Build/InstallDev
    $(INSTALL_DIR) $(STAGING_DIR)$(PYTHON_PKG_DIR)
    $(CP) \
        $(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
        $(STAGING_DIR)$(PYTHON_PKG_DIR)/
    [ ! -e $(PKG_INSTALL_DIR)/usr/include ] || $(CP) \
        $(PKG_INSTALL_DIR)/usr/include/* \
        $(STAGING_DIR)/usr/include/
endef

define Package/backports-abc/install
    $(INSTALL_DIR) $(1)$(PYTHON_PKG_DIR)/
    $(CP) \
        $(PKG_INSTALL_DIR)$(PYTHON_PKG_DIR)/* \
        $(1)$(PYTHON_PKG_DIR)/
endef

$(eval $(call BuildPackage,backports-abc))


问:
Django error creating object with many to many field
There are a few questions already mentioning this error but I couldn't find an answer in any of them.

```<code>  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
  File "/home/joao/Code/projects/courty/courty-django/apps/matching/serializers.py", line 19, in create
return MatchFinder.objects.create(**validated_data)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/query.py", line 392, in create
obj = self.model(**kwargs)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/base.py", line 568, in __init__
_setattr(self, prop, kwargs[prop])
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 536, in __set__
manager = self.__get__(instance)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
return self.related_manager_cls(instance)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
(instance, self.pk_field_names[self.source_field_name]))
 ValueError: "<MatchFinder: MatchFinder object>" needs to have a value for field "id" before this many-to-many relationship can be used.
</code>```

Model

```<code>class MatchFinder(models.Model):
    player = models.ForeignKey(Player)
    start_datetime = models.DateTimeField(null=False)
    venues = models.ManyToManyField(Venue, help_text='Pitches preferred by this player', blank=True)
</code>```

View

```<code>class MatchFinderView(views.APIView):

    def post(self, request, format=None):
        serializer = MatchFinderSerialzer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

Serializer

```<code>class MatchFinderSerialzer(BaseModelSerializer):

    class Meta:
        model = MatchFinder
        fields = ('start_datetime', 'venues')

    def create(self, validated_data):
        return MatchFinder.objects.create(**validated_data)
</code>```

Request

```<code> c = Client()
 data = {
        'start_datetime': now,
        }
 response = c.post('/matches/findmatch/', data)
</code>```

Passing a list of 2 Venue objects in the venues on the post request results in the same error.

答:
There are multiple issues,

Firstly, 'player' is a non nullable field - so you need to add it in the fields.

Secondly, For nested relationships you need to explicitly specify how the child relationships should be saved. I have modified the Serializer accordingly,

```<code>class MatchFinderSerialzer(BaseModelSerializer):

     class Meta:
         model = MatchFinder
         fields = ('player', 'start_datetime', 'venues')

     def create(self, validated_data):
         venues_data = validated_data.pop('venues')
         match_finder = MatchFinder.objects.create(**validated_data)
         for venue_data in venues_data:
             Venue.objects.create(match_finder=match_finder, **venue_data)
         return match_finder
</code>```

Also make sure you provide 'player id' in your post request.

Body:
There are a few questions already mentioning this error but I couldn't find an answer in any of them.

  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
  File "/home/joao/Code/projects/courty/courty-django/apps/matching/serializers.py", line 19, in create
return MatchFinder.objects.create(**validated_data)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/query.py", line 392, in create
obj = self.model(**kwargs)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/base.py", line 568, in __init__
_setattr(self, prop, kwargs[prop])
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 536, in __set__
manager = self.__get__(instance)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
return self.related_manager_cls(instance)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
(instance, self.pk_field_names[self.source_field_name]))
 ValueError: "<MatchFinder: MatchFinder object>" needs to have a value for field "id" before this many-to-many relationship can be used.

Model

class MatchFinder(models.Model):
    player = models.ForeignKey(Player)
    start_datetime = models.DateTimeField(null=False)
    venues = models.ManyToManyField(Venue, help_text='Pitches preferred by this player', blank=True)

View

class MatchFinderView(views.APIView):

    def post(self, request, format=None):
        serializer = MatchFinderSerialzer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Serializer

class MatchFinderSerialzer(BaseModelSerializer):

    class Meta:
        model = MatchFinder
        fields = ('start_datetime', 'venues')

    def create(self, validated_data):
        return MatchFinder.objects.create(**validated_data)

Request

 c = Client()
 data = {
        'start_datetime': now,
        }
 response = c.post('/matches/findmatch/', data)

Passing a list of 2 Venue objects in the venues on the post request results in the same error.

Body:
There are multiple issues,

Firstly, 'player' is a non nullable field - so you need to add it in the fields.

Secondly, For nested relationships you need to explicitly specify how the child relationships should be saved. I have modified the Serializer accordingly,

class MatchFinderSerialzer(BaseModelSerializer):

     class Meta:
         model = MatchFinder
         fields = ('player', 'start_datetime', 'venues')

     def create(self, validated_data):
         venues_data = validated_data.pop('venues')
         match_finder = MatchFinder.objects.create(**validated_data)
         for venue_data in venues_data:
             Venue.objects.create(match_finder=match_finder, **venue_data)
         return match_finder

Also make sure you provide 'player id' in your post request.


问:
Xampp Access Forbidden php
I'm a windows user. I've been using xampp for quite a while but suddenly none of my .php files are working now!
I get this error message:

Access forbidden!

You don't have permission to access the requested object. It is either read-protected or not readable by the server.

If you think this is a server error, please contact the webmaster.

Error 403

localhost
Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16

I can see the list of my .php files in localhost/Practice (Practice is the folder where I've saved my files)
The file even opens whenever I click on it.
But when I click on any 'submit' button inside any of my files, it gives this error.
Please help! I updated xampp from 1.8.1 to 1.8.2 but still the same problem persists!

答:
```<code>A. #LoadModule vhost_alias_module modules/mod_vhost_alias.so
B. <Directory />
    AllowOverride none
    Require all denied
</Directory>
</code>```

Replace with:

```<code>A. LoadModule vhost_alias_module modules/mod_vhost_alias.so
B:
<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>
</code>```

From E:\xamp**apache\conf/httpd.conf**

Title: Xampp Access Forbidden php

Body:
A. #LoadModule vhost_alias_module modules/mod_vhost_alias.so
B. <Directory />
    AllowOverride none
    Require all denied
</Directory>

Replace with:

A. LoadModule vhost_alias_module modules/mod_vhost_alias.so
B:
<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

From E:\xamp**apache\conf/httpd.conf**


答:
I did it in python using the api key and the mobile token.
In java, I believe you can do something like this

```<code>public final static String AUTH_KEY_FCM = "xyxyxyxxyxyxyxyxyxyxyxy";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

// userDeviceIdKey is the device id you will query from your database

public static void pushFCMNotification(String userDeviceIdKey) throws Exception{

   String authKey = AUTH_KEY_FCM; // You FCM AUTH key
   String FMCurl = API_URL_FCM;

   URL url = new URL(FMCurl);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();

   conn.setUseCaches(false);
   conn.setDoInput(true);
   conn.setDoOutput(true);

   conn.setRequestMethod("POST");
   conn.setRequestProperty("Authorization","key="+authKey);
   conn.setRequestProperty("Content-Type","application/json");

   JSONObject json = new JSONObject();
   json.put("to",userDeviceIdKey.trim());
   JSONObject info = new JSONObject();
   info.put("title", "Notificatoin Title"); // Notification title
   info.put("body", "Hello Test notification"); // Notification body
   json.put("notification", info);

   OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
   wr.write(json.toString());
   wr.flush();
   conn.getInputStream();
}
</code>```

See

For my python implementation i used from pyfcm import FCMNotification library.
See

Title: How do i send a Firebase Push Notification via java instead of the FirebaseConsole?

Body:
I'm getting into Firebase Cloud Messaging, and i would like to know how to send a message in a Push Notification with java code, instead of manually writing it in the Firebase Console.

Thanks in advance.

Body:
I did it in python using the api key and the mobile token.
In java, I believe you can do something like this

public final static String AUTH_KEY_FCM = "xyxyxyxxyxyxyxyxyxyxyxy";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

// userDeviceIdKey is the device id you will query from your database

public static void pushFCMNotification(String userDeviceIdKey) throws Exception{

   String authKey = AUTH_KEY_FCM; // You FCM AUTH key
   String FMCurl = API_URL_FCM;

   URL url = new URL(FMCurl);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();

   conn.setUseCaches(false);
   conn.setDoInput(true);
   conn.setDoOutput(true);

   conn.setRequestMethod("POST");
   conn.setRequestProperty("Authorization","key="+authKey);
   conn.setRequestProperty("Content-Type","application/json");

   JSONObject json = new JSONObject();
   json.put("to",userDeviceIdKey.trim());
   JSONObject info = new JSONObject();
   info.put("title", "Notificatoin Title"); // Notification title
   info.put("body", "Hello Test notification"); // Notification body
   json.put("notification", info);

   OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
   wr.write(json.toString());
   wr.flush();
   conn.getInputStream();
}

See

For my python implementation i used from pyfcm import FCMNotification library.
See


答:
<input type="password" value="my unsecure password">```

Please read on HASH function for php to encrypt your password. But what you need is an input that have a password type so the browser will show ********. But there is no point hiding it if its not encrypted. I do not know the password of my site's user.

Title: How to i hide a password in web page

Body:
<input type="password" value="my unsecure password">

Please read on HASH function for php to encrypt your password. But what you need is an input that have a password type so the browser will show ********. But there is no point hiding it if its not encrypted. I do not know the password of my site's user.


问:
ArangoDB How to get all neighbours with fulldepth matching the pattern with AQL?
We have ~300k document and ~3m edge in our ArangoDB v3.2
I want to get all neighbors of start document and neighbor's neighbours as long as neighbor's rate > 0.5.. It will give me the community has rate > 0.5 and related with start doc.

Now i m doing it with multiple requests but data and project is going to be bigger and i need better performance so i need a AQL query to get all neigbours with one request..

I have tried to get neighbours with depth 1..10 so it will enought to get all neigbours but it is very ver slow so i cant give absolute depth..

```<code>for vertex, edge, path in 1..10 any 'docs/10' doc_relations
    filter edge.rate > 0.5
return distinct edge
</code>```

I need some thing like while loop but there is no query function like this.

答:
It seems to me that you should be able to achieve what you want using AQL.

Fine-tuning the AQL query

It looks like you could fine-tune the definitional AQL query. Specifically, I would propose using an AQL query along the following lines:

```<code>for vertex, edge, path in 1..100000 OUTBOUND 'docs/10' doc_relations
   OPTIONS {uniqueVertices: "global", bfs: true }
   FILTER path.edges[*].rate ALL > 0.5
   return vertex
</code>```

That is:

if possible, use OUTBOUND rather than ALL;

use the OPTIONS as shown since you don't care how many admissible paths there are to an admissible vertex;

your requirements seem to impose the "rate > 0.5" restriction on every edge along an admissible path to a "neighbor", hence ALL;

since you want the vertices, simply return vertex; there is no need for DISTINCT because of the aforementioned OPTIONS.

Add a "skip-list index" on .rate

Cacheing the neighbours in the database

i need a AQL query to get all neigbours with one request

In terms of performance, there is obviously a time/space tradeoff here, and it might make sense to pre-compute the neighbours of all the vertices, or to compute-and-cache them on demand.

Body:
We have ~300k document and ~3m edge in our ArangoDB v3.2
I want to get all neighbors of start document and neighbor's neighbours as long as neighbor's rate > 0.5.. It will give me the community has rate > 0.5 and related with start doc.

Now i m doing it with multiple requests but data and project is going to be bigger and i need better performance so i need a AQL query to get all neigbours with one request..

I have tried to get neighbours with depth 1..10 so it will enought to get all neigbours but it is very ver slow so i cant give absolute depth..

for vertex, edge, path in 1..10 any 'docs/10' doc_relations
    filter edge.rate > 0.5
return distinct edge

I need some thing like while loop but there is no query function like this.

Body:
It seems to me that you should be able to achieve what you want using AQL.

Fine-tuning the AQL query

It looks like you could fine-tune the definitional AQL query. Specifically, I would propose using an AQL query along the following lines:

for vertex, edge, path in 1..100000 OUTBOUND 'docs/10' doc_relations
   OPTIONS {uniqueVertices: "global", bfs: true }
   FILTER path.edges[*].rate ALL > 0.5
   return vertex

That is:

if possible, use OUTBOUND rather than ALL;

use the OPTIONS as shown since you don't care how many admissible paths there are to an admissible vertex;

your requirements seem to impose the "rate > 0.5" restriction on every edge along an admissible path to a "neighbor", hence ALL;

since you want the vertices, simply return vertex; there is no need for DISTINCT because of the aforementioned OPTIONS.

Add a "skip-list index" on .rate

Cacheing the neighbours in the database

i need a AQL query to get all neigbours with one request

In terms of performance, there is obviously a time/space tradeoff here, and it might make sense to pre-compute the neighbours of all the vertices, or to compute-and-cache them on demand.


问:
Has anyone noticed an odd AJAX bug in WebKit whereby it ignores readyState 3?
I'm seeing an odd behavior in WebKit (on Android) where my server process is sending it a response that it needs to handle immediately (rather than wait for readyState 4).  In Firefox and Safari this works as expected, but on webkit, not only does it not respond to the readyState but instead it appears to fire off a repeat request to the server!

This only seems to happen when the server takes a little while to react to the request. I'm still poking around to see what the exact circumstances are that bring this about, but am curious if this is a known bug and what, if anything, is a workaround.

[EDIT] This is just getting weirder and weirder.  As long as the server responds within about 10 seconds, everything is fine. But if it takes longer than that, then the request is resubmitted. However, the browser appears to not be aware of this re-submission, or if it is, it's not reporting it in any way.  I attached a unique ID to the request and when it arrives for the second time on the server the id is the same. But it's definitely spawning off an additional call to the server.  I'm sort of at a loss as to how to debug this further.

答:
No one has piped in, so. I have fixed the problem by killing the connection from the server side.

So, my solution:

a) client makes call to server (which is a perl.cgi)

b) server code:

print (some JSON for the broswer);
close(STDOUT); #this sends a readyState 4 to the browser and closes the connection.
&methodThatTakesAWhile();

This doesn't explain WHY the browser is misbehaving, but it does get around this particular bug.

ContentLicense: CC BY-SA 2.5


问:
ionic 3 input field rounded corner and icon
I am working on an ionic 3 mobile app in which I had to design a login page with input fields which have an icon in the left and with rounded corners. But someone in ionic decided that people don't need borders for input elements anymore and they made all the input styles as underlined.

I tried so many ways to accomplish it but I couldn't pull it off. If I use custom elements instead of ionic ones I can get the layout but it messes with responsive design and especially with the keyboard, keyboards don't come up.

Can anyone help me on this? is my markup.

```<code> <ion-content padding>
      <div text-center class="logo-container">
      <img class="login-logo" src="./assets/imgs/clean_connect.png" alt="Logo of clean connect">
        <h4>Sign in to your account</h4>
      </div>
      <form [formGroup]="signInForm" (submit) = "login(signInForm.value)" novalidate>
        <ion-list>

          <ion-item>
            <ion-label><ion-icon name="ios-person-outline" item-left></ion-icon></ion-label>
            <ion-input type="text" value="agira" placeholder="Username" formControlName="username"></ion-input>
          </ion-item>
          <ion-item no-lines  *ngIf="!signInForm.controls.username.valid && (signInForm.controls.username.dirty)">
          <div>
            Please enter valid Username
          </div>
          </ion-item>
          <ion-item>
            <ion-label><ion-icon name="ios-lock-outline" item-left></ion-icon></ion-label>
            <ion-input type="password" value="Agira1" placeholder="Password" formControlName="password"></ion-input>
          </ion-item>
          <ion-item no-lines *ngIf="!signInForm.controls.password.valid && (signInForm.controls.password.dirty)">
          <div>
            Please enter Password
          </div>
          </ion-item>
        </ion-list>
        <button class="sign-in" type="submit" ion-button full favourite [disabled]="!signInForm.valid">Sign In</button>
      </form>
    </ion-content>
</code>```

答:
Here's how I made it:

```<code>ion-item:first-child {
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  ion-item:last-child {
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
  }
  ion-item.item {
    background-color: rgba(255, 255, 255, 0.4);
    margin-bottom: 1px;
    .label {
      width: 10%;
      color: rgba(0, 0, 0, 0.6);
      font-size: 1.2em;
    }
  }
</code>```

You can get something like this:

Probably you'll need to use class names instead of the ion-item directly...

Body:
I am working on an ionic 3 mobile app in which I had to design a login page with input fields which have an icon in the left and with rounded corners. But someone in ionic decided that people don't need borders for input elements anymore and they made all the input styles as underlined.

I tried so many ways to accomplish it but I couldn't pull it off. If I use custom elements instead of ionic ones I can get the layout but it messes with responsive design and especially with the keyboard, keyboards don't come up.

Can anyone help me on this? is my markup.

 <ion-content padding>

Sign in to your account

      <form [formGroup]="signInForm" (submit) = "login(signInForm.value)" novalidate>
        <ion-list>

          <ion-item>
            <ion-label><ion-icon name="ios-person-outline" item-left></ion-icon></ion-label>
            <ion-input type="text" value="agira" placeholder="Username" formControlName="username"></ion-input>
          </ion-item>
          <ion-item no-lines  *ngIf="!signInForm.controls.username.valid && (signInForm.controls.username.dirty)">

            Please enter valid Username

          </ion-item>
          <ion-item>
            <ion-label><ion-icon name="ios-lock-outline" item-left></ion-icon></ion-label>
            <ion-input type="password" value="Agira1" placeholder="Password" formControlName="password"></ion-input>
          </ion-item>
          <ion-item no-lines *ngIf="!signInForm.controls.password.valid && (signInForm.controls.password.dirty)">

            Please enter Password

          </ion-item>
        </ion-list>
        <button class="sign-in" type="submit" ion-button full favourite [disabled]="!signInForm.valid">Sign In</button>
      </form>
    </ion-content>

Body:
Here's how I made it:

ion-item:first-child {
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  ion-item:last-child {
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
  }
  ion-item.item {
    background-color: rgba(255, 255, 255, 0.4);
    margin-bottom: 1px;
    .label {
      width: 10%;
      color: rgba(0, 0, 0, 0.6);
      font-size: 1.2em;
    }
  }

You can get something like this:

Probably you'll need to use class names instead of the ion-item directly...


问:
Why does this if and elif statement not fully execute?
Based on reading the 2.7 documentation, the following code should step through correctly from what I can tell. I call raw_input(text) to get an input for variable age, but it always returns You can see rated R movies.

```<code>import sys

age = raw_input("What is your age? ")

if age >= 17:
    print "You can see rated R movies."

elif age < 17 and age > 12:
    print "You can see a rated PG-13 movies."

else:
    print "You can only see PG movies!"
</code>```

Based on my logic, if the value passed to age is not greater than or equal to 17, it should move onto the next statement. That is not the result I get though. It always returns the Rated R line. For example I input 3 and it still gives me the rated R response. If I flip the > to < then it always returns the "You can only see PG movies!" line.

Thoughts?

答:
When you use the raw_input method you are asking to enter a value by keyboard, everything that is entered will be read as a string not as an integer even if you are asking for an integer value.

Your solution:

```<code>age = int(raw_input("What is your age? ")).
</code>```

Parse to int no matter what introduced.

Body:
Based on reading the 2.7 documentation, the following code should step through correctly from what I can tell. I call raw_input(text) to get an input for variable age, but it always returns You can see rated R movies.

import sys

age = raw_input("What is your age? ")

if age >= 17:
    print "You can see rated R movies."

elif age < 17 and age > 12:
    print "You can see a rated PG-13 movies."

else:
    print "You can only see PG movies!"

Based on my logic, if the value passed to age is not greater than or equal to 17, it should move onto the next statement. That is not the result I get though. It always returns the Rated R line. For example I input 3 and it still gives me the rated R response. If I flip the > to < then it always returns the "You can only see PG movies!" line.

Thoughts?

Body:
When you use the raw_input method you are asking to enter a value by keyboard, everything that is entered will be read as a string not as an integer even if you are asking for an integer value.

Your solution:

age = int(raw_input("What is your age? ")).

Parse to int no matter what introduced.


问:
R compare data.table elements by elements
Have two data.tables:

```<code>> aDT <- data.table(colA = "apple", colB = "banana", colC = "4")
> aDT
    colA   colB colC
1: apple banana    4

> bDT <- data.table(colA = c("purple","apple"), colB = c("pear","banana"), colC = c("4","2"))
> bDT
     colA   colB colC
1: purple   pear    4
2:  apple banana    2
</code>```

I would like to compare the only row in aDT with every row in bDT, element by element. The resulting data.table looks like:

```<code>> resultDT <- data.table(colA = c(FALSE,TRUE), colB = c(FALSE,TRUE), colC = c(TRUE,FALSE))
> resultDT
    colA  colB  colC
1: FALSE FALSE  TRUE
2:  TRUE  TRUE FALSE
</code>```

How to achieve it?

答:
Another option is Map to compare the corresponding columns of both dataset

```<code>aDT[, Map(`==`, .SD, bDT)]
#   colA  colB  colC
#1: FALSE FALSE  TRUE
#2:  TRUE  TRUE FALSE
</code>```

Body:
Have two data.tables:

> aDT <- data.table(colA = "apple", colB = "banana", colC = "4")
> aDT
    colA   colB colC
1: apple banana    4

> bDT <- data.table(colA = c("purple","apple"), colB = c("pear","banana"), colC = c("4","2"))
> bDT
     colA   colB colC
1: purple   pear    4
2:  apple banana    2

I would like to compare the only row in aDT with every row in bDT, element by element. The resulting data.table looks like:

> resultDT <- data.table(colA = c(FALSE,TRUE), colB = c(FALSE,TRUE), colC = c(TRUE,FALSE))
> resultDT
    colA  colB  colC
1: FALSE FALSE  TRUE
2:  TRUE  TRUE FALSE

How to achieve it?

Body:
Another option is Map to compare the corresponding columns of both dataset

aDT[, Map(`==`, .SD, bDT)]
#   colA  colB  colC
#1: FALSE FALSE  TRUE
#2:  TRUE  TRUE FALSE


问:
How to fetch google contacts into an iOS application
I read the below link and now I understood that I need to make an api call to fetch the contacts. As I am new to Swift3 could someone guide me how to do this. I read somewhere that Almofire and Swifty json would help and I also read GData also will help. I am little confused. Please guide me.

Google Contacts API

答:
I was actually stuck on this too and couldn't find a solution but I ended up figuring it out. You first need to authenticate with Google Sign In and then pass the accessToken into this endpoint:</p>

```<code>let urlString = ("https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=5000&access_token=\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken!)")

        guard let url = URL(string: urlString) else { return }
        URLSession.shared.dataTask(with: url, completionHandler: {
            (data, response, error) in

            if(error != nil){
                print("error")
            }else{
                do{
                    let json = try JSONSerialization.jsonObject(with: data!, options:[]) as! [String : AnyObject]
                    //parse JSON

                }catch let error as NSError{
                    print(error)
                }
            }
        }).resume()
</code>```

Body:
I was actually stuck on this too and couldn't find a solution but I ended up figuring it out. You first need to authenticate with Google Sign In and then pass the accessToken into this endpoint:

let urlString = ("https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=5000&access_token=\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken!)")

        guard let url = URL(string: urlString) else { return }
        URLSession.shared.dataTask(with: url, completionHandler: {
            (data, response, error) in

            if(error != nil){
                print("error")
            }else{
                do{
                    let json = try JSONSerialization.jsonObject(with: data!, options:[]) as! [String : AnyObject]
                    //parse JSON

                }catch let error as NSError{
                    print(error)
                }
            }
        }).resume()


问:
R - Changing Values and Scales for Axes
Using an inverse transform method to simulate a pareto distribution. I made the density histogram of the sample with the Pareto(2, 2) density
superimposed for comparison. The graph doesn't look like what I wanted it to though.

I'd like for my y-axis to go from (0.00,0.08) with a scale of .02

I'd like for my x-axis to go from (0,120) with a scale of 20.

I tried using a few commands such as xticks, yticks, but couldn't get the result I wanted. Any suggestions?

```<code>x <- runif(100, min = 0, max = 1)

a <- 2
b <- 2

gen_pareto <- b/(1-x)^(1/a)

plot(x, gen_pareto)

hist(gen_pareto, prob = TRUE)

lines(density(gen_pareto), # density plot
      lwd = 3, # thickness of line
      col = "blue")
</code>```

答:
Here is one approach to your solution :

```<code>par(mfrow=c(1,2))
hist(gen_pareto, prob=T,xlim = c(0,120), ylim = c(0,.8))
lines(density(gen_pareto),
      lwd = 3,
      col = "red")
</code>```

However, I feel the below solution is much better but it doesn't qualify the boundary conditions you have said.

```<code>hist(gen_pareto, prob=T,xlim = c(0, max(density(gen_pareto)$x)), ylim = c(0, max(density(gen_pareto)$y)))
lines(density(gen_pareto),
      lwd = 3,
      col = "red")
</code>```

Title: R - Changing Values and Scales for Axes

Body:
Using an inverse transform method to simulate a pareto distribution. I made the density histogram of the sample with the Pareto(2, 2) density
superimposed for comparison. The graph doesn't look like what I wanted it to though.

I'd like for my y-axis to go from (0.00,0.08) with a scale of .02

I'd like for my x-axis to go from (0,120) with a scale of 20.

I tried using a few commands such as xticks, yticks, but couldn't get the result I wanted. Any suggestions?

x <- runif(100, min = 0, max = 1)

a <- 2
b <- 2

gen_pareto <- b/(1-x)^(1/a)

plot(x, gen_pareto)

hist(gen_pareto, prob = TRUE)

lines(density(gen_pareto), # density plot
      lwd = 3, # thickness of line
      col = "blue")

Body:
Here is one approach to your solution :

par(mfrow=c(1,2))
hist(gen_pareto, prob=T,xlim = c(0,120), ylim = c(0,.8))
lines(density(gen_pareto),
      lwd = 3,
      col = "red")

However, I feel the below solution is much better but it doesn't qualify the boundary conditions you have said.

hist(gen_pareto, prob=T,xlim = c(0, max(density(gen_pareto)$x)), ylim = c(0, max(density(gen_pareto)$y)))
lines(density(gen_pareto),
      lwd = 3,
      col = "red")


问:
NumPy array is not JSON serializable
After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage:

```<code>array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64) is not JSON serializable
</code>```

What does this mean?

答:
Store as JSON a numpy.ndarray or any nested-list composition.

```<code>class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
json_dump = json.dumps({'a': a, 'aa': [2, (2, 3, 4), a], 'bb': [2]},
                       cls=NumpyEncoder)
print(json_dump)
</code>```

Will output:

```<code>(2, 3)
{"a": [[1, 2, 3], [4, 5, 6]], "aa": [2, [2, 3, 4], [[1, 2, 3], [4, 5, 6]]], "bb": [2]}
</code>```

To restore from JSON:

```<code>json_load = json.loads(json_dump)
a_restored = np.asarray(json_load["a"])
print(a_restored)
print(a_restored.shape)
</code>```

Will output:

```<code>[[1 2 3]
 [4 5 6]]
(2, 3)
</code>```

Title: NumPy array is not JSON serializable

Body:
After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage:

array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64) is not JSON serializable

What does this mean?

Body:
Store as JSON a numpy.ndarray or any nested-list composition.

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
json_dump = json.dumps({'a': a, 'aa': [2, (2, 3, 4), a], 'bb': [2]},
                       cls=NumpyEncoder)
print(json_dump)

Will output:

(2, 3)
{"a": [[1, 2, 3], [4, 5, 6]], "aa": [2, [2, 3, 4], [[1, 2, 3], [4, 5, 6]]], "bb": [2]}

To restore from JSON:

json_load = json.loads(json_dump)
a_restored = np.asarray(json_load["a"])
print(a_restored)
print(a_restored.shape)

Will output:

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


问:
Is This Relational Database Sound or Can it be Improved?
I am trying to create a database for an online instrumental shop. I designed this database and added a cart table but I don't know if this is a good implementation for a online shop with cart.

答:
The database sounds ohk and can be improved in many ways to make it even perfect one.
The following links gives u more detail in depth
https://www.ntu.edu.sg/home/ehchua/programming/sql/Relational_Database_Design.html</p>


问:
.NET version of TNonblockingServer
Is there any known .NET versions of async servers and protocols for Thrift? Especially I'm looking for  TThreadedSelectorServer version written in C#.

I just checked out the git repository, but the CSharp version is missing a lot of stuff in comparison with Java version.

答:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, which is very helpful for cross-platform and it uses DotNetty (windows is iocp, linux is nio)

```<code>[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

[ThriftService("scribe")]
public interface IScribe
{
    [ThriftMethod("getMessages")]
    List<LogEntry> GetMessages();

    [ThriftMethod]
    ResultCode Log(List<LogEntry> messages);
}

public class Scribe : IScribe
{
    public List<LogEntry> GetMessages()
    {
        return new List<LogEntry>
        {
            new LogEntry { Category = "c1", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c2", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c3", Message = Guid.NewGuid().ToString() }
        };
    }

    public ResultCode Log(List<LogEntry> messages)
    {
        return ResultCode.TRY_LATER;
    }
}
</code>```

C#: https://github.com/endink/Thrifty
Similar Java can use Swift: https://github.com/facebook/swift

Title: .NET version of TNonblockingServer

Body:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, which is very helpful for cross-platform and it uses DotNetty (windows is iocp, linux is nio)

[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

[ThriftService("scribe")]
public interface IScribe
{
    [ThriftMethod("getMessages")]
    List<LogEntry> GetMessages();

    [ThriftMethod]
    ResultCode Log(List<LogEntry> messages);
}

public class Scribe : IScribe
{
    public List<LogEntry> GetMessages()
    {
        return new List<LogEntry>
        {
            new LogEntry { Category = "c1", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c2", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c3", Message = Guid.NewGuid().ToString() }
        };
    }

    public ResultCode Log(List<LogEntry> messages)
    {
        return ResultCode.TRY_LATER;
    }
}

C#: https://github.com/endink/Thrifty
Similar Java can use Swift: https://github.com/facebook/swift


问:
Invoke function from another function in fishshell
I have created two function in .fish file

```<code>function mysqlstart
    cd ~/Projects/mysql
    docker-compose up -d
end

function projstart
    cd ~/Projects/projectName/
    php artisan serve
end
</code>```

I want to invoke those two functions with a single function so that I don't have to type two alias on fish shell.

```<code>function startdev
    mysqlstart()
    projstart()
end
</code>```

How to call functions from another function in .fish file?

I know I can run all four commands inside stardev function itself. But if I can call other functions, I can do other things as well and keep the .fish file DRY.

答:
Functions are just like any other command:

```<code>function startdev
    mysqlstart
    projstart
end
</code>```

Easy!

Body:
I have created two function in .fish file

function mysqlstart
    cd ~/Projects/mysql
    docker-compose up -d
end

function projstart
    cd ~/Projects/projectName/
    php artisan serve
end

I want to invoke those two functions with a single function so that I don't have to type two alias on fish shell.

function startdev
    mysqlstart()
    projstart()
end

How to call functions from another function in .fish file?

I know I can run all four commands inside stardev function itself. But if I can call other functions, I can do other things as well and keep the .fish file DRY.

Body:
Functions are just like any other command:

function startdev
    mysqlstart
    projstart
end

Easy!


问:
Javascript arrays merge
`

I have two arrays

```<code>a = [a0,a1,a2,..]
b = [b0,b1,b2,..]
</code>```

How to obtain the below array

```<code>c=[[a0,b0],[a1,b1],[a2.b2],[.,.]...]
</code>```

Any help is appreciated

Thanks in advance

答:
```<code>function merge(a, b) {
    var c = [];
  a.forEach((item, index) => {
    c[index] = [item];
  })
  b.forEach((item, index) => {
    c[index].push(item);
  })
  return c;
}
</code>```

Title: Javascript arrays merge

Body:
`

I have two arrays

a = [a0,a1,a2,..]
b = [b0,b1,b2,..]

How to obtain the below array

c=[[a0,b0],[a1,b1],[a2.b2],[.,.]...]

Any help is appreciated

Thanks in advance


问:
Java - How to use call a method from another class
For a class project I am trying to access a method from a different class but my code gives the error "non-static method printArrayList() cannot be referenced from a static context." I am a a beginner to java so any help is appreciated.
I have simplified the code down a bit.

Here is the first class:

```<code>public class classOne
{
    private classTwo[] arrayList;
    public void printArray()
        {
            classTwo.printArrayList();
        }
}
</code>```

And the second:

```<code>public class classTwo
{
    public void printArrayList()
    {
        System.out.println(arrayList);
    }
}
</code>```

答:
I see 7 answers to a Question to just invoke a method of another class , Let me write mine also -</p>

```<code>Method method = classTwo.getDeclaredMethod("printArrayList");
method.invoke(classTwo.newInstance());
</code>```

Body:
For a class project I am trying to access a method from a different class but my code gives the error "non-static method printArrayList() cannot be referenced from a static context." I am a a beginner to java so any help is appreciated.
I have simplified the code down a bit.

Here is the first class:

public class classOne
{
    private classTwo[] arrayList;
    public void printArray()
        {
            classTwo.printArrayList();
        }
}

And the second:

public class classTwo
{
    public void printArrayList()
    {
        System.out.println(arrayList);
    }
}

Body:
I see 7 answers to a Question to just invoke a method of another class , Let me write mine also -

Method method = classTwo.getDeclaredMethod("printArrayList");
method.invoke(classTwo.newInstance());


问:
Why is each public class in a separate file?
I recently started learning Java and found it very strange that every Java public class must be declared in a separate file. I am a C# programmer and C# doesn't enforce any such restriction.

Why does Java do this? Were there any design considerations?

Edit (based on a few answers):

Why is Java not removing this restriction now in the age of IDEs? This will not break any existing code (or will it?).

答:
Well, actually it is an optional restriction according to Java Language Specification (Section 7.6, Page No. 209) but followed by Oracle Java compiler as a mandatory restriction. According to Java Language Specification,

When packages are stored in a file system (§7.2.1), the host system
  may choose to enforce the restriction that it is a compile-time error
  if a type is not found in a file under a name composed of the type
  name plus an extension (such as .java or .jav) if either of the
  following is true:

The type is referred to by code in other compilation units of the package in which the type is declared.

The type is declared public (and therefore is potentially accessible from code in other packages).

This restriction implies that there must be at most one such type per
  compilation unit.  This restriction makes it easy for a Java compiler
  to find a named class within a package.

In practice, many programmers choose to put each class or interface
  type in its own compilation unit, whether or not it is public or is
  referred to by code in other compilation units.

For example, the source code for a public type wet.sprocket.Toad would
  be found in a file Toad.java in the directory wet/sprocket , and the
  corresponding object code would be found in the file Toad.class in the
  same directory.

To get more clear picture let's imagine there are two public classes public class A and public class B in a same source file and A class have reference to the not yet compiled class B. And we are compiling (compiling-linking-loading) class A now while linking to class B compiler will be forced to examine each *.java files within the current package because class B don’t have it’s specific B.java file. So In above case, it is a little bit time consuming for the compiler to find which class lies under which source file and in which class the main method lies.
So the reason behind keeping one public class per source file is to actually make compilation process faster because it enables a more efficient lookup of the source and compiled files during linking (import statements). The idea is if you know the name of a class, you know where it should be found for each classpath entry and no indexing will be required.

And also as soon as we execute our application JVM by default looks for the public class (since no restrictions and can be accessible from anywhere) and also looks for public static void main(String args[]) in that public class. Public class acts as the initial class from where the JVM instance for the Java application (program) is begun. So when we provide more than one public class in a program the compiler itself stops you by throwing an error. This is because later we can’t confuse the JVM as to which class to be its initial class because only one public class with the public static void main(String args[]) is the initial class for JVM.

You can read more on Why Single Java Source File Can Not Have More Than One public class


问:
Sorting Python list with exception
How can I sort a python list alphabetically, taking into consideration the numbering at the back of the list items. See example below and code used to sort.
Note that it is not possible to insert a zero into the code if the number is below 10.

original list:

['drawing-n-3', 'drawing-n-2', 'drawing-n-1', 'drawing-n-7',
  'drawing-n-6', 'drawing-n-5', 'drawing-n-4', 'drawing-n-9',
  'drawing-n-8', 'drawing-n-16', 'drawing-n-15', 'drawing-n-14',
  'drawing-n-13', 'drawing-n-12', 'drawing-n-11', 'drawing-n-10',
  'drawing-n-17']

Sorted list:

['drawing-n-1', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12',
  'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16',
  'drawing-n-17', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4',
  'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8',
  'drawing-n-9']

Desired List output:

['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4',
  'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8',
  'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12',
  'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16',
  'drawing-n-17']

Code:

```<code>dwg_number_keys = [key for key in kwargs if key.startswith("drawing-n-")]
print dwg_number_keys
print sorted(dwg_number_keys, key=str.lower)
</code>```

答:
Parse it from a string into an integer to sort on:-</p>

```<code>>>> begin = len("drawing-n-")
>>> sorted(dwg_number_keys, key=lambda s:int(s[len("drawing-n-"):]))
['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4', 'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8', 'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12', 'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16', 'drawing-n-17']
</code>```

Title: Sorting Python list with exception

Body:
How can I sort a python list alphabetically, taking into consideration the numbering at the back of the list items. See example below and code used to sort.
Note that it is not possible to insert a zero into the code if the number is below 10.

original list:

['drawing-n-3', 'drawing-n-2', 'drawing-n-1', 'drawing-n-7',
  'drawing-n-6', 'drawing-n-5', 'drawing-n-4', 'drawing-n-9',
  'drawing-n-8', 'drawing-n-16', 'drawing-n-15', 'drawing-n-14',
  'drawing-n-13', 'drawing-n-12', 'drawing-n-11', 'drawing-n-10',
  'drawing-n-17']

Sorted list:

['drawing-n-1', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12',
  'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16',
  'drawing-n-17', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4',
  'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8',
  'drawing-n-9']

Desired List output:

['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4',
  'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8',
  'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12',
  'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16',
  'drawing-n-17']

Code:

dwg_number_keys = [key for key in kwargs if key.startswith("drawing-n-")]
print dwg_number_keys
print sorted(dwg_number_keys, key=str.lower)

Body:
Parse it from a string into an integer to sort on:-

>>> begin = len("drawing-n-")
>>> sorted(dwg_number_keys, key=lambda s:int(s[len("drawing-n-"):]))
['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4', 'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8', 'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12', 'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16', 'drawing-n-17']


问:
Why would you ever call .call() on Observable functions?
I am a relative beginner in Angular, and I am struggling to understand some source I am reading from the ng-bootstrap project. The source code can be found here.

I am very confused by the code in ngOnInit:

```<code>ngOnInit(): void {
    const inputValues$ = _do.call(this._valueChanges, value => {
      this._userInput = value;
      if (this.editable) {
        this._onChange(value);
      }
    });
    const results$ = letProto.call(inputValues$, this.ngbTypeahead);
    const processedResults$ = _do.call(results$, () => {
      if (!this.editable) {
        this._onChange(undefined);
      }
    });
    const userInput$ = switchMap.call(this._resubscribeTypeahead, () => processedResults$);
    this._subscription = this._subscribeToUserInput(userInput$);
  }
</code>```

What is the point of calling .call(...) on these Observable functions? What kind of behaviour is this trying to achieve? Is this a normal pattern?

I've done a lot of reading/watching about Observables (no pun intended) as part of my Angular education but I have never come across anything like this. Any explanation would be appreciated

答:
I suppose

```<code>const inputValues$ = _do.call(this._valueChanges, value => {
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
});
</code>```

is equivalent to

```<code>const inputValues$=this._valueChanges.do(value=>{
 this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
})
</code>```

In my opinion it's not an usual pattern(I think it is the same pattern but written in different fashion)  for working with observable. _do() in the code is being used as standalone function take a callback as argument and required to be binded to the scope of the source Observable

https://github.com/ReactiveX/rxjs/blob/master/src/operator/do.ts

Body:
I am a relative beginner in Angular, and I am struggling to understand some source I am reading from the ng-bootstrap project. The source code can be found here.

I am very confused by the code in ngOnInit:

ngOnInit(): void {
    const inputValues$ = _do.call(this._valueChanges, value => {
      this._userInput = value;
      if (this.editable) {
        this._onChange(value);
      }
    });
    const results$ = letProto.call(inputValues$, this.ngbTypeahead);
    const processedResults$ = _do.call(results$, () => {
      if (!this.editable) {
        this._onChange(undefined);
      }
    });
    const userInput$ = switchMap.call(this._resubscribeTypeahead, () => processedResults$);
    this._subscription = this._subscribeToUserInput(userInput$);
  }

What is the point of calling .call(...) on these Observable functions? What kind of behaviour is this trying to achieve? Is this a normal pattern?

I've done a lot of reading/watching about Observables (no pun intended) as part of my Angular education but I have never come across anything like this. Any explanation would be appreciated

Body:
I suppose

const inputValues$ = _do.call(this._valueChanges, value => {
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
});

is equivalent to

const inputValues$=this._valueChanges.do(value=>{
 this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
})

In my opinion it's not an usual pattern(I think it is the same pattern but written in different fashion)  for working with observable. _do() in the code is being used as standalone function take a callback as argument and required to be binded to the scope of the source Observable

https://github.com/ReactiveX/rxjs/blob/master/src/operator/do.ts


问:
Are parentheses around the result significant in a return statement?
Is there a difference between these two statements inside a function?

```<code>bool returnValue = true;
// Code that does something
return(returnValue);
</code>```

and this?

```<code>bool returnValue = true;
// Code
return returnValue;
</code>```

The former has parentheses around returnValue.

答:
No difference!!

People use parenthesis if there's a complex expression involved.

BTW return is a statement not a function.

Body:
Is there a difference between these two statements inside a function?

bool returnValue = true;
// Code that does something
return(returnValue);

and this?

bool returnValue = true;
// Code
return returnValue;

The former has parentheses around returnValue.


问:
Downloading FTP file using Codeigniter Filepath Error
This is what I have done so far.

Configured Filezilla FTP server on localhost.
And added user: Admin with shared folder C://ftp
there is a file inside that folder 123.jpg

So when I try to Download it using ftp class in Codeigniter;

Unable to download the specified file. Please check your path.

this is the code I'm using to download. FTP successfully connects but fails download due to incorrect file path.

```<code>$this->ftp->download('/123.jpg', 'D:/');
</code>```

What should be changed in the above code?

答:
Well, D:/ definitely dose not seems to be a path that is wrong. As for the doubt goes in the file you trying to download.

You can debug with the same - connect the ftp server using a ftp client, see the files / folders in list. There you can confirm as whether or not the file exists directly in path or not.

Body:
This is what I have done so far.

Configured Filezilla FTP server on localhost.
And added user: Admin with shared folder C://ftp
there is a file inside that folder 123.jpg

So when I try to Download it using ftp class in Codeigniter;

Unable to download the specified file. Please check your path.

this is the code I'm using to download. FTP successfully connects but fails download due to incorrect file path.

$this->ftp->download('/123.jpg', 'D:/');

What should be changed in the above code?


问:
What is Google Chrome Browser Version 0.A.B.C?
I'm looking through my GA logs and I see a Google Chrome browser version 0.A.B.C. Could anybody tell me what this is exactly? Some kind of spider or bot or modified http header?</p>

答:
The full user agent string probably looks something like this:

"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13"

This is most likely a bot, but it could just be someone running an automated script using CasperJS or PhantomJS (or even a shell script using something like lynx) and spoofing the user agent.

The reason it looks like that instead of something that says  "My automated test runner v1.0" (or whatever is relevant to the author) is that this user agent string will pass most regular expression checks as "some version of Chrome" and not get filtered out properly by most bot checks that rely on a regular expression to match 'valid' user agent patterns.

In order to avoid it, your site bot checker would need to blacklist this string, or validate that all parts of the Chrome version to make sure they're all valid numbers. Even then, you can only do so much checking since the user agent string is so easy to spoof.