问:
Exception in thread "main" java.lang.NullPointerException during read texts and prints out its 2d array
I am trying  to write a program that reads a txt file and prints out its 2d numbers only array, but i got NullPointerEexception I have no idea why, please help

Here is my code:

```<code>import java.io.*;
import java.util.*;

public class FileR {
    public static void  main(String[] args) throws Exception {
        int[][] desktop;
        int rows = getTotalRow();
        desktop = new int[rows][];
        Scanner fin;
        InputStream is;
        is = new FileInputStream("hello.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = "";
        try {
            int row = 0;
            while ((line = br.readLine()) != null) {
                line = line.replaceAll("[^0-9]+", "");
                if (line.isEmpty())
                    continue;
                String[] nums = line.split("\\s*(|,|\\s)\\s*");
                desktop[row] = new int[nums.length];
                for (int i = 0; i < nums.length; i++) {
                    desktop[row][i] = Integer.parseInt(nums[i]);
                }
                row++;

            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        print(desktop);
    }

    public static int getTotalRow() throws IOException {
        LineNumberReader reader = null;
        try {
            reader = new LineNumberReader(new FileReader("hello.txt"));
            while ((reader.readLine()) != null) ;
            return reader.getLineNumber();
        } catch (Exception ex) {
            return -1;
        } finally {
            if (reader != null)
                reader.close();
        }
    }

    public static void print(int[][] value) {
        for (int i = 0; i < value.length; i++) {
            for (int j = 0; j < value[i].length; j++) {

                System.out.print(value[i][j] + " ");

            }
            System.out.println();
        }
    }
}
</code>```

HEre is my hello txt file:

```<code>There should be a specific text at the top of each page

2  2, 2, 2, 2, 2, 2, 2, 2, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 1, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
lmlmlm
</code>```

my ouput :

```<code>2 2 2 2 2 2 2 2 2 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 1 3 4 0 0 0 2
2 0 0 0 3 4 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 2 2 2 2 2 2 2 2 2
Exception in thread "main" java.lang.NullPointerException
    at FileR.print(FileR.java:55)
    at FileR.main(FileR.java:34)
</code>```

I guess NullPointerException caught when it loops empty string or null object, i want to omit null object but how to realize it i don't know
Any idea on how to solve it?

答:
The problem is in your method getTotalRow() it is returning the wrong count.</p>

```<code>public class FileR {
    public static String filePath = "hello.txt";

    public static void main(String[] args) throws Exception {
        int[][] desktop;
        int rows = getTotalRow();
        desktop = new int[rows][];
        Scanner fin;
        InputStream is;
        is = new FileInputStream(filePath);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = "";
        try {
            int row = 0;
            while ((line = br.readLine()) != null) {
                line = line.replaceAll("[^0-9]+", "");
                if (line.isEmpty())
                    continue;
                String[] nums = line.split("\\s*(|,|\\s)\\s*");
                desktop[row] = new int[nums.length];
                for (int i = 0; i < nums.length; i++) {
                    desktop[row][i] = Integer.parseInt(nums[i]);
                }
                row++;

            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        print(desktop);
    }

    public static int getTotalRow() throws IOException {
        BufferedReader br = null;
        String line;
        int count = 0;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            while ((line = br.readLine()) != null) {
                boolean isDigit = !line.isEmpty() && Character.isDigit(line.charAt(0));
                if (isDigit) {
                    count++;
                }
            }
        } catch (Exception ex) {
            return -1;
        } finally {
            if (br != null)
                br.close();
        }

        return count;
    }

    public static void print(int[][] value) {
        for (int i = 0; i < value.length; i++) {
            for (int j = 0; j < value[i].length; j++) {

                System.out.print(value[i][j] + " ");

            }
            System.out.println();
        }
    }
}
</code>```

Body:
I am trying  to write a program that reads a txt file and prints out its 2d numbers only array, but i got NullPointerEexception I have no idea why, please help

Here is my code:

import java.io.*;
import java.util.*;

public class FileR {
    public static void  main(String[] args) throws Exception {
        int[][] desktop;
        int rows = getTotalRow();
        desktop = new int[rows][];
        Scanner fin;
        InputStream is;
        is = new FileInputStream("hello.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = "";
        try {
            int row = 0;
            while ((line = br.readLine()) != null) {
                line = line.replaceAll("[^0-9]+", "");
                if (line.isEmpty())
                    continue;
                String[] nums = line.split("\\s*(|,|\\s)\\s*");
                desktop[row] = new int[nums.length];
                for (int i = 0; i < nums.length; i++) {
                    desktop[row][i] = Integer.parseInt(nums[i]);
                }
                row++;

            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        print(desktop);
    }

    public static int getTotalRow() throws IOException {
        LineNumberReader reader = null;
        try {
            reader = new LineNumberReader(new FileReader("hello.txt"));
            while ((reader.readLine()) != null) ;
            return reader.getLineNumber();
        } catch (Exception ex) {
            return -1;
        } finally {
            if (reader != null)
                reader.close();
        }
    }

    public static void print(int[][] value) {
        for (int i = 0; i < value.length; i++) {
            for (int j = 0; j < value[i].length; j++) {

                System.out.print(value[i][j] + " ");

            }
            System.out.println();
        }
    }
}

HEre is my hello txt file:

There should be a specific text at the top of each page

2  2, 2, 2, 2, 2, 2, 2, 2, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 1, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
lmlmlm

my ouput :

2 2 2 2 2 2 2 2 2 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 1 3 4 0 0 0 2
2 0 0 0 3 4 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 2 2 2 2 2 2 2 2 2
Exception in thread "main" java.lang.NullPointerException
    at FileR.print(FileR.java:55)
    at FileR.main(FileR.java:34)

I guess NullPointerException caught when it loops empty string or null object, i want to omit null object but how to realize it i don't know
Any idea on how to solve it?

Body:
The problem is in your method getTotalRow() it is returning the wrong count.

public class FileR {
    public static String filePath = "hello.txt";

    public static void main(String[] args) throws Exception {
        int[][] desktop;
        int rows = getTotalRow();
        desktop = new int[rows][];
        Scanner fin;
        InputStream is;
        is = new FileInputStream(filePath);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = "";
        try {
            int row = 0;
            while ((line = br.readLine()) != null) {
                line = line.replaceAll("[^0-9]+", "");
                if (line.isEmpty())
                    continue;
                String[] nums = line.split("\\s*(|,|\\s)\\s*");
                desktop[row] = new int[nums.length];
                for (int i = 0; i < nums.length; i++) {
                    desktop[row][i] = Integer.parseInt(nums[i]);
                }
                row++;

            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        print(desktop);
    }

    public static int getTotalRow() throws IOException {
        BufferedReader br = null;
        String line;
        int count = 0;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            while ((line = br.readLine()) != null) {
                boolean isDigit = !line.isEmpty() && Character.isDigit(line.charAt(0));
                if (isDigit) {
                    count++;
                }
            }
        } catch (Exception ex) {
            return -1;
        } finally {
            if (br != null)
                br.close();
        }

        return count;
    }

    public static void print(int[][] value) {
        for (int i = 0; i < value.length; i++) {
            for (int j = 0; j < value[i].length; j++) {

                System.out.print(value[i][j] + " ");

            }
            System.out.println();
        }
    }
}


来源: stackexchange

问:
Any alternative way to copy specific file from private git repository to remote server with Ansible without ssh
My question is that I want to copy a specific file from private git repository to remote server with ansible but I don't want to use ssh key. Do you know any alternative way like such as with api key? Like below code sample Im getting permission issue, so I want to add api key or sth else to get repo file.</p>

```<code>---
- name: Sample
  hosts: localhost
  connection: local
  become: true
  tasks:
   - name: Copy
     become: yes
     git:
        repo: 'https://gitlab.com/sample-project/branch-a/sample.xml'
        dest: "/home/sample-file"
</code>```

答:
You can use

a deploy token, see Gitlab access token for a single project or group?

in URL credentials, see How do I pass username and password while using Ansible Git module?

If you are using Gitlab CI, masked environment variables to store the token could be useful, see masked-variables. Else, a vaulted variable see vault.

```<code>---
- name: Sample
  hosts: localhost
  connection: local
  become: true
  tasks:
   - name: Copy
     become: yes
     git:
       repo: "https://{{ username| urlencode }}:{{ deploy_token | urlencode }}@gitlab.com/sample-project/branch-a/sample.xml"
       dest: /home/sample-file
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My question is that I want to copy a specific file from private git repository to remote server with ansible but I don't want to use ssh key. Do you know any alternative way like such as with api key? Like below code sample Im getting permission issue, so I want to add api key or sth else to get repo file.

---
- name: Sample
  hosts: localhost
  connection: local
  become: true
  tasks:
   - name: Copy
     become: yes
     git:
        repo: 'https://gitlab.com/sample-project/branch-a/sample.xml'
        dest: "/home/sample-file"

Body:
You can use

a deploy token, see Gitlab access token for a single project or group?

in URL credentials, see How do I pass username and password while using Ansible Git module?

If you are using Gitlab CI, masked environment variables to store the token could be useful, see masked-variables. Else, a vaulted variable see vault.

---
- name: Sample
  hosts: localhost
  connection: local
  become: true
  tasks:
   - name: Copy
     become: yes
     git:
       repo: "https://{{ username| urlencode }}:{{ deploy_token | urlencode }}@gitlab.com/sample-project/branch-a/sample.xml"
       dest: /home/sample-file


问:
HTML: img inside a tag not working
Why is my image not becoming hyperlinked? Here's my HTML code (with links taken out), and the CSS of the div it's in:</p>

```<code><div class=bannercontainer>
<a href="(working URL here)" target="_blank"><img src="image.png" width="194" height="67" border="0" /></a></div>
.bannercontainer{ margin-left: auto; margin-right:auto; width:900px; height:500px; margin-top:50px;}
</code>```

答:
```<code><div class=bannercontainer>
</code>```

needs quotes like this

```<code><div class='bannercontainer'>
</code>```

ContentLicense: CC BY-SA 3.0

Title: HTML: img inside a tag not working

Body:
Why is my image not becoming hyperlinked? Here's my HTML code (with links taken out), and the CSS of the div it's in:

.bannercontainer{ margin-left: auto; margin-right:auto; width:900px; height:500px; margin-top:50px;}

Body:
<div class=bannercontainer>

needs quotes like this

<div class='bannercontainer'>


问:
Why can't I use this closure inside a Rc<dyn Fn()>?
I have this struct:

pub struct ImmEval<Out> {
    closure: Rc<dyn Fn(&Self) -> Out>
}
impl<Out> From<Rc<dyn Fn(&Self) -> Out>> for ImmEval<Out> {
    /// Constructs the evaluator from the specified closure.
    fn from(cl: Rc<dyn Fn(&Self) -> Out>) -> Self {
        ImmEval {closure: cl}
    }
}
impl<Out> Evaluator for ImmEval<Out> {
    type Output = Out;
    /// Evaluates and returns the result.
    fn eval(&self) -> Self::Output {
        (*self.closure)(self)
    }
}
```

<p>which is used in a test like this:</p>

<pre class="lang-rust prettyprint-override"><code>let counter = Cell::new(0);
{
    let eval = ImmEval::<i32>::from(Rc::from(|_: &ImmEval<i32>| {
        counter.set(counter.get() + 1);
        counter.get()
    }));

    eval.eval();
    eval.eval();
}
assert_eq!(counter.get(), 2);
</code>```

The struct itself compiles but the test does not. Instead, it fails with the following rustc message:

error[E0277]: the trait bound `ImmEval<i32>: std::convert::From<std::rc::Rc<[closure@src\tests.rs:8:51: 11:10 counter:_]>>` is not satisfied
  --> src\tests.rs:8:41
   |
8  |           let eval = ImmEval::<i32>::from(Rc::from(|_: &ImmEval<i32>| {
   |  _________________________________________^
9  | |             counter.set(counter.get() + 1);
10 | |             counter.get()
11 | |         }));
   | |__________^ the trait `std::convert::From<std::rc::Rc<[closure@src\tests.rs:8:51: 11:10 counter:_]>>` is not implemented for `ImmEval<i32>`
   |
   = help: the following implementations were found:
             <ImmEval<Out> as std::convert::From<std::rc::Rc<(dyn for<'r> std::ops::Fn(&'r ImmEval<Out>) -> Out + 'static)>>>
   = note: required by `std::convert::From::from`
```

Surely this means that my closure isn't a valid Fn(&ImmEval<i32>) -> i32, but why?

Here's the playground example.

答:
A more elegant solution than creating a closure separately (as seen here, though I still appreciate the great explanation of the problem) is not using the From trait at all:

impl<'l, Out> ImmEval<'l, Out> {
    pub fn new<Cl>(closure: Cl) -> Self
    where Cl: (Fn(&ImmEval<Out>) -> Out) + 'l {
        let rcl: Rc<dyn Fn(&ImmEval<Out>) -> Out> = Rc::from(closure);
        ImmEval {closure: rcl}
    }
}
```

I replaced the From constructor with a generic new (and also added some lifetime specifiers to make sure that the closure lives long enough), which takes the closure itself (without the reference counter) and puts it into one in the same way that the first answer that I mentioned does. By then cloning the evaluator struct or adding a method get_closure, the reference-counted closure can be extracted and reused. Moreover, if the From trait is preserved, then the get_closure result would be usable in the same way as the first answer mentioned.

Body:
I have this struct:

pub struct ImmEval<Out> {
    closure: Rc<dyn Fn(&Self) -> Out>
}
impl<Out> From<Rc<dyn Fn(&Self) -> Out>> for ImmEval<Out> {
    /// Constructs the evaluator from the specified closure.
    fn from(cl: Rc<dyn Fn(&Self) -> Out>) -> Self {
        ImmEval {closure: cl}
    }
}
impl<Out> Evaluator for ImmEval<Out> {
    type Output = Out;
    /// Evaluates and returns the result.
    fn eval(&self) -> Self::Output {
        (*self.closure)(self)
    }
}

which is used in a test like this:

let counter = Cell::new(0);
{
    let eval = ImmEval::<i32>::from(Rc::from(|_: &ImmEval<i32>| {
        counter.set(counter.get() + 1);
        counter.get()
    }));

    eval.eval();
    eval.eval();
}
assert_eq!(counter.get(), 2);

The struct itself compiles but the test does not. Instead, it fails with the following rustc message:

error[E0277]: the trait bound `ImmEval<i32>: std::convert::From<std::rc::Rc<[closure@src\tests.rs:8:51: 11:10 counter:_]>>` is not satisfied
  --> src\tests.rs:8:41
   |
8  |           let eval = ImmEval::<i32>::from(Rc::from(|_: &ImmEval<i32>| {
   |  _________________________________________^
9  | |             counter.set(counter.get() + 1);
10 | |             counter.get()
11 | |         }));
   | |__________^ the trait `std::convert::From<std::rc::Rc<[closure@src\tests.rs:8:51: 11:10 counter:_]>>` is not implemented for `ImmEval<i32>`
   |
   = help: the following implementations were found:
             <ImmEval<Out> as std::convert::From<std::rc::Rc<(dyn for<'r> std::ops::Fn(&'r ImmEval<Out>) -> Out + 'static)>>>
   = note: required by `std::convert::From::from`

Surely this means that my closure isn't a valid Fn(&ImmEval<i32>) -> i32, but why?

Here's the playground example.

Body:
A more elegant solution than creating a closure separately (as seen here, though I still appreciate the great explanation of the problem) is not using the From trait at all:

impl<'l, Out> ImmEval<'l, Out> {
    pub fn new<Cl>(closure: Cl) -> Self
    where Cl: (Fn(&ImmEval<Out>) -> Out) + 'l {
        let rcl: Rc<dyn Fn(&ImmEval<Out>) -> Out> = Rc::from(closure);
        ImmEval {closure: rcl}
    }
}

I replaced the From constructor with a generic new (and also added some lifetime specifiers to make sure that the closure lives long enough), which takes the closure itself (without the reference counter) and puts it into one in the same way that the first answer that I mentioned does. By then cloning the evaluator struct or adding a method get_closure, the reference-counted closure can be extracted and reused. Moreover, if the From trait is preserved, then the get_closure result would be usable in the same way as the first answer mentioned.


问:
Unable to resolve module `react-native-gesture-handler`
unable to resolve "react-native-gesture-handler" from "node_modules/@react-navigation/native/src/Scrollables.js"</p>

```<code>E:\>npm install react-native-gesture-handler --save
npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno ENOENT
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t https://github.com/naver/hammer.js.git

npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\AppData\Roaming\npm-cache\_logs\2020-02-13T05_04_32_3
58Z-debug.log
</code>```

答:
I just found the solution of this problem ..
It's Just version Error

npm install react-native-gesture-handler@1.3.0

When I try this
It's Working

Body:
unable to resolve "react-native-gesture-handler" from "node_modules/@react-navigation/native/src/Scrollables.js"

E:\>npm install react-native-gesture-handler --save
npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno ENOENT
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t https://github.com/naver/hammer.js.git

npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\AppData\Roaming\npm-cache\_logs\2020-02-13T05_04_32_3
58Z-debug.log


问:
Problem with importing camelcase module to Python (VSCode terminal)
I am trying to import camelcase module to python:

```<code>from camelcase import CamelCase
txt = 'hello there world'
c = CamelCase()
print(c.hump(txt))
</code>```

I get an error: ModuleNotFoundError: No module named 'camelcase'

I tried also:

```<code>import camelcase
txt = 'hello there world'
c = camelcase.CamelCase()
print(c.hump(txt))
</code>```

Same issue. I have newest version of pip installed:

```<code>--pip --version
pip 20.0.2 from C:\Users\Eryk Słowiński\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pip (python 3.7)
</code>```

And for sure I have installed camelcase

```<code>--pip freeze
appdirs==1.4.3
camelcase==0.2
importlib-metadata==1.5.0
virtualenv==20.0.3
zipp==2.2.0
</code>```

What am I doing wrong?

答:
Ok I think I have found source of problem, I've installed virtual environment and I guess it was in wrong location. I deleted it and when I use my packages globally it works okay.
I guess I should take some tutorial how to use env before i mess with it in my terminal :D</p>

Body:
I am trying to import camelcase module to python:

from camelcase import CamelCase
txt = 'hello there world'
c = CamelCase()
print(c.hump(txt))

I get an error: ModuleNotFoundError: No module named 'camelcase'

I tried also:

import camelcase
txt = 'hello there world'
c = camelcase.CamelCase()
print(c.hump(txt))

Same issue. I have newest version of pip installed:

--pip --version
pip 20.0.2 from C:\Users\Eryk Słowiński\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pip (python 3.7)

And for sure I have installed camelcase

--pip freeze
appdirs==1.4.3
camelcase==0.2
importlib-metadata==1.5.0
virtualenv==20.0.3
zipp==2.2.0

What am I doing wrong?


问:
Apache2 reverse proxy to a nextcloud server does not work
I've made a Ubuntu 18.04 Reverse Proxy Server with Apache2 and it works. I can reverse proxy to another apache2 webserver with no problem.

But now I want to do the exact same thing to a nextcloud server but it does not work.

My steps:

1) I copied the old configuration

2) changed the external Domain and the internal IP Adress from the Server

3) now I restarted the apache2 server and it does not work

There is no error in the error.log file from apache.

Maybe there is an error on the nextcloud server but I don't know how to continue.

Thanks Raphael

答:
This is my working config for the Apache proxy pointing to the local Nextcloud in a Docker based instance:</p>

```<code>ProxyPreserveHost On
ProxyRequests Off
ServerName cloud.myserver.local
ServerAlias cloud
ProxyPass / http://localhost:8000/
ProxyPassReverse / http://localhost:8000/
</code>```

Body:
This is my working config for the Apache proxy pointing to the local Nextcloud in a Docker based instance:

ProxyPreserveHost On
ProxyRequests Off
ServerName cloud.myserver.local
ServerAlias cloud
ProxyPass / http://localhost:8000/
ProxyPassReverse / http://localhost:8000/


问:
Call a class attribute of a class instance from a function in python
Let's say I want to plot different class objects attribute from a function.

So far I have this:

...

import matplotlib.pyplot as plt

def plot2vars (deviceList, xVars, yVars, xLims, yLims, colormap=plt.cm.Spectral):
    x0 = xVars[0]
    x1 = xVars[1]
    y0 = yVars[0]
    y1 = yVars[1]
    fig, ax = plt.subplots(1,2)

    fig, ax = plt.subplots(1,2)
    for d in deviceList: #these 'd' are the class instances...
        if not d.discard:
                    ax[0].plot(d.x0, d.y0)
                    ax[0].set_xlim(xLims[0])
                    ax[0].set_ylim(yLims[0])

                    ax[1].plot(d.x1, d.y1)
                    ax[1].set_xlim(xLims[1])
                    ax[1].set_ylim(yLims[1])
    plt.show()

```

<p>where deviceList is a list containing class instances with different attributes like, for example, <code>u</code>, <code>z</code> or <code>T</code>.</p>

<p>Now, when I call the function, I declare xVars, yVars, xLims, yLims as arrays of strings, which obviously doesn't work. But I don't know how to call these. And I don't even know how to look for this in the manuals...</p>

<pre class="lang-py prettyprint-override"><code>plot2vars (
      deviceList,
      xVars=['u', 'u'], yVars=['z', 'T'],
      xLims=['', 'left=0.8'], yLims=['','bottom=0, top=0.8']
      )
</code>```

答:
Maybe, if you want to take the attributes given as strings from your xVars and yVars, you should use getattr method like this:

```<code>d.x0 -> getattr(d, x0)
</code>```

For example, if x0 = 'qwerty', getattr(d, x0) equals to d.qwerty.

So in your code you should use:

```<code>...
ax[0].plot(getattr(d, x0), getattr(d, y0))
...
ax[1].plot(getattr(d, x1), getattr(d, y1))
...
</code>```

Documentation: https://docs.python.org/3/library/functions.html#getattr

As for xLims and yLims, I would define it as list of dictionaries like this:

```<code>xLims = [{}, {'left': 0.8}]
yLims = [{}, {'bottom': 0, 'top': 0.8}]
</code>```

So this would allow me to use them through **kwargs approach:

```<code>...
ax[0].set_xlim(**xLims[0])
ax[0].set_ylim(**yLims[0])
...
ax[1].set_xlim(**xLims[1])
ax[1].set_ylim(**yLims[1])
...
</code>```

The main idea is when you pass a dictionary to a function with ** the key-values pairs will be unpacked into key-value arguments.

Body:
Let's say I want to plot different class objects attribute from a function.

So far I have this:

...

import matplotlib.pyplot as plt

def plot2vars (deviceList, xVars, yVars, xLims, yLims, colormap=plt.cm.Spectral):
    x0 = xVars[0]
    x1 = xVars[1]
    y0 = yVars[0]
    y1 = yVars[1]
    fig, ax = plt.subplots(1,2)

    fig, ax = plt.subplots(1,2)
    for d in deviceList: #these 'd' are the class instances...
        if not d.discard:
                    ax[0].plot(d.x0, d.y0)
                    ax[0].set_xlim(xLims[0])
                    ax[0].set_ylim(yLims[0])

                    ax[1].plot(d.x1, d.y1)
                    ax[1].set_xlim(xLims[1])
                    ax[1].set_ylim(yLims[1])
    plt.show()

where deviceList is a list containing class instances with different attributes like, for example, u, z or T.

Now, when I call the function, I declare xVars, yVars, xLims, yLims as arrays of strings, which obviously doesn't work. But I don't know how to call these. And I don't even know how to look for this in the manuals...

plot2vars (
      deviceList,
      xVars=['u', 'u'], yVars=['z', 'T'],
      xLims=['', 'left=0.8'], yLims=['','bottom=0, top=0.8']
      )

Body:
Maybe, if you want to take the attributes given as strings from your xVars and yVars, you should use getattr method like this:

d.x0 -> getattr(d, x0)

For example, if x0 = 'qwerty', getattr(d, x0) equals to d.qwerty.

So in your code you should use:

...
ax[0].plot(getattr(d, x0), getattr(d, y0))
...
ax[1].plot(getattr(d, x1), getattr(d, y1))
...

Documentation: https://docs.python.org/3/library/functions.html#getattr

As for xLims and yLims, I would define it as list of dictionaries like this:

xLims = [{}, {'left': 0.8}]
yLims = [{}, {'bottom': 0, 'top': 0.8}]

So this would allow me to use them through **kwargs approach:

...
ax[0].set_xlim(**xLims[0])
ax[0].set_ylim(**yLims[0])
...
ax[1].set_xlim(**xLims[1])
ax[1].set_ylim(**yLims[1])
...

The main idea is when you pass a dictionary to a function with ** the key-values pairs will be unpacked into key-value arguments.


问:
Saving matplotlib figure on azure blob storage
I have a word cloud created using WordCloud class. I am plotting this word cloud using matplotlib. Now I want to save this figure on azure blob storage, but I can't find any python SDK to do the same.

In order to use *plt.savefig(), path for blob storage is needed. Could anyone tell how this path can be mentioned or some other way to store it on blob?

Code I am using is:

```<code>fig, ax = plt.subplots()
words = text.split()
word_cloud = WordCloud(width = 8000, height = 800,
                background_color ='black',
                min_font_size = 10).generate(str(text))
plt.imshow(word_cloud)
display(fig)
</code>```

答:
As per my research, you cannot save Matplotlib output to Azure Blob Storage directly.

You may follow the below steps to save Matplotlib output to Azure Blob Storage:

Step 1: You need to first save it to the Databrick File System (DBFS) and then copy it to Azure Blob storage.

Saving Matplotlib output to Databricks File System (DBFS): We are using the below command to save the output to DBFS: plt.savefig('/dbfs/myfolder/Graph1.png')

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'fruits':['apple','banana'], 'count': [1,2]})
plt.close()
df.set_index('fruits',inplace = True)
df.plot.bar()
plt.savefig('/dbfs/myfolder/Graph1.png')
</code>```

Step 2: Copy the file from Databricks File System to Azure Blob Storage.

There are two methods to copy file from DBFS to Azure Blob Stroage.

Method 1: Access Azure Blob storage directly

Access Azure Blob Storage directly by setting "Spark.conf.set" and copy file from DBFS to Blob Storage.

```<code>spark.conf.set("fs.azure.account.key.< Blob Storage Name>.blob.core.windows.net", "<Azure Blob Storage Key>")
</code>```

Use dbutils.fs.cp to copy file from DBFS to Azure Blob Storage:

```<code>dbutils.fs.cp('dbfs:/myfolder/Graph1.png', 'wasbs://<Container>@<Storage Name>.blob.core.windows.net/Azure')
</code>```

Method 2: Mount Azure Blob storage containers to DBFS

You can mount a Blob storage container or a folder inside a container to Databricks File System (DBFS). The mount is a pointer to a Blob storage container, so the data is never synced locally.

```<code>dbutils.fs.mount(
  source = "wasbs://sampledata@chepra.blob.core.windows.net/Azure",
  mount_point = "/mnt/chepra",
  extra_configs = {"fs.azure.sas.sampledata.chepra.blob.core.windows.net":dbutils.secrets.get(scope = "azurestorage", key = "azurestoragekey")})
</code>```

Use dbutils.fs.cp copy the file to Azure Blob Storage Container:

dbutils.fs.cp('dbfs:/myfolder/Graph1.png', '/dbfs/mnt/chepra')

By following Method1 or Method2 you can successfully save the output to Azure Blob Storage.

Hope this helps. Do let us know if you any further queries.

Body:
I have a word cloud created using WordCloud class. I am plotting this word cloud using matplotlib. Now I want to save this figure on azure blob storage, but I can't find any python SDK to do the same.

In order to use *plt.savefig(), path for blob storage is needed. Could anyone tell how this path can be mentioned or some other way to store it on blob?

Code I am using is:

fig, ax = plt.subplots()
words = text.split()
word_cloud = WordCloud(width = 8000, height = 800,
                background_color ='black',
                min_font_size = 10).generate(str(text))
plt.imshow(word_cloud)
display(fig)

Body:
As per my research, you cannot save Matplotlib output to Azure Blob Storage directly.

You may follow the below steps to save Matplotlib output to Azure Blob Storage:

Step 1: You need to first save it to the Databrick File System (DBFS) and then copy it to Azure Blob storage.

Saving Matplotlib output to Databricks File System (DBFS): We are using the below command to save the output to DBFS: plt.savefig('/dbfs/myfolder/Graph1.png')

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'fruits':['apple','banana'], 'count': [1,2]})
plt.close()
df.set_index('fruits',inplace = True)
df.plot.bar()
plt.savefig('/dbfs/myfolder/Graph1.png')

Step 2: Copy the file from Databricks File System to Azure Blob Storage.

There are two methods to copy file from DBFS to Azure Blob Stroage.

Method 1: Access Azure Blob storage directly

Access Azure Blob Storage directly by setting "Spark.conf.set" and copy file from DBFS to Blob Storage.

spark.conf.set("fs.azure.account.key.< Blob Storage Name>.blob.core.windows.net", "<Azure Blob Storage Key>")

Use dbutils.fs.cp to copy file from DBFS to Azure Blob Storage:

dbutils.fs.cp('dbfs:/myfolder/Graph1.png', 'wasbs://<Container>@<Storage Name>.blob.core.windows.net/Azure')

Method 2: Mount Azure Blob storage containers to DBFS

You can mount a Blob storage container or a folder inside a container to Databricks File System (DBFS). The mount is a pointer to a Blob storage container, so the data is never synced locally.

dbutils.fs.mount(
  source = "wasbs://sampledata@chepra.blob.core.windows.net/Azure",
  mount_point = "/mnt/chepra",
  extra_configs = {"fs.azure.sas.sampledata.chepra.blob.core.windows.net":dbutils.secrets.get(scope = "azurestorage", key = "azurestoragekey")})

Use dbutils.fs.cp copy the file to Azure Blob Storage Container:

dbutils.fs.cp('dbfs:/myfolder/Graph1.png', '/dbfs/mnt/chepra')

By following Method1 or Method2 you can successfully save the output to Azure Blob Storage.

Hope this helps. Do let us know if you any further queries.


问:
Can istio circuit breaking be defined with the client configuration rather than the server configuration?
In istio a circuit breaker must be defined as a DestinationRule (https://istio.io/docs/concepts/traffic-management/#circuit-breakers). This is okay, but we might want to define different thresholds for each client and I would prefer the definition to be stored in the client's configuration.

As we are in a software company with organisational structures and configuration is in different places it would be nice for us to own this, and store it with the client config.

Is this possible?

Is it possible to configure circuit breaking on a client by client basis?

If the answer to the above two questions is no, why should I not have this? (Am I asking for something I shouldn't need?)

答:
Istio will look for DestinationRules in the following order:

consumer namespace

provider namespace

config root namespace, which is usually "istio-system".

That way you can have different circuit breaking configurations per client by placing them into the corresponding client namespaces.
This assumes of course that the clients run in different namespaces.


问:
Image gallery: Disable thumbnail when being clicked
I'm trying to create a simple "image gallery" where I have one big photo and a couple of thumbnails. When a thumbnail is clicked the big image should fade out and then fade in the new image. My problem is that when I click on the thumbnail that represents the current "big image" the big image fades out and no big image is displayed. I therefore want to disable the thumbnail once it's clicked and it's big image has been loaded. Any suggestions on how to do this would be greatly appreciated. My current code looks like this:

application.js

```<code>function addClickHandlers(){
  var large_image = document.getElementById("large_image")
  var thumbnail = $('img.thumbnail')

  // Adds click handlers to image thumbnails that update the larger image
  $(thumbnail, this).click(function() {
    src = this.src.replace("thumb", "large")
    $(large_image).fadeOut(200, function(){
      $(large_image).attr('src', src).bind('readystatechange load', function(){
        if  (this.complete) $(this).fadeIn(400);
      });
    });
  });
};

$(document).ready(addClickHandlers);
</code>```

And my HTML/HAML

```<code>.big_photo
  = image_tag(@tee.tee_images.first.photo.url(:large), :id => "large_image")
- tee.tee_images.each do |image|
  = image_tag(image.photo.url(:thumb), :class => "thumbnail")
</code>```

I've followed this tutorial: http://blog.randomutterings.com/articles/2009/02/15/changing-images-with-jquery-and-the-fade-effect

答:
How about checking if the big image matches the thumb? so change the code to</p>

```<code>$(thumbnail, this).click(function() {
  src = this.src.replace("thumb", "large");
  if (src != large_image.src)
    $(large_image).fadeOut(200, function(){
</code>```

Body:
I'm trying to create a simple "image gallery" where I have one big photo and a couple of thumbnails. When a thumbnail is clicked the big image should fade out and then fade in the new image. My problem is that when I click on the thumbnail that represents the current "big image" the big image fades out and no big image is displayed. I therefore want to disable the thumbnail once it's clicked and it's big image has been loaded. Any suggestions on how to do this would be greatly appreciated. My current code looks like this:

application.js

function addClickHandlers(){
  var large_image = document.getElementById("large_image")
  var thumbnail = $('img.thumbnail')

  // Adds click handlers to image thumbnails that update the larger image
  $(thumbnail, this).click(function() {
    src = this.src.replace("thumb", "large")
    $(large_image).fadeOut(200, function(){
      $(large_image).attr('src', src).bind('readystatechange load', function(){
        if  (this.complete) $(this).fadeIn(400);
      });
    });
  });
};

$(document).ready(addClickHandlers);

And my HTML/HAML

.big_photo
  = image_tag(@tee.tee_images.first.photo.url(:large), :id => "large_image")
- tee.tee_images.each do |image|
  = image_tag(image.photo.url(:thumb), :class => "thumbnail")

I've followed this tutorial: http://blog.randomutterings.com/articles/2009/02/15/changing-images-with-jquery-and-the-fade-effect

Body:
How about checking if the big image matches the thumb? so change the code to

$(thumbnail, this).click(function() {
  src = this.src.replace("thumb", "large");
  if (src != large_image.src)
    $(large_image).fadeOut(200, function(){


问:
Flutter app show grey screen in release mode but works fine in debug mode
I am trying out flutter and currently following this tutorial
https://www.youtube.com/watch?v=j6c_vHdbUfg

I notice that the app works fine in debug mode but when I try the apk on my phone the app shows a grey screen after the loading screen. I am not too familiar building apps on mobile and not sure what is causing the issue here. I've tried building the apk using the github project from the tutorial but it also have this issue. https://github.com/iamshaunjp/flutter-beginners-tutorial/tree/lesson-35

答:
I had exactly the same problem and got it working.

What you need to do is add the following line in AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

this can be found at: android/app/src/main/

The reason as you can probably see is that android requires this permission to access http requests.

Body:
I had exactly the same problem and got it working.

What you need to do is add the following line in AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

this can be found at: android/app/src/main/

The reason as you can probably see is that android requires this permission to access http requests.


问:
Java 11 compile error: Package xxx exists in another module
There is a class in my project. This class in package javax.swing extends javax.swing.JOptionPane because I want to use some protected methods of JOptionPane.

When the compiler is JDK 8 it works fine. I update the JDK version to 11 then I've got a compile error: Package 'javax.swing' exists in another module: java.desktop.

My IDE is Intellij idea. I opened the Settings--Build,Execution,Deployment--Java Compiler and added an item to 'Override compiler parameters pre-module'. The Module is my project. The compilation options is

```<code>--patch-module java.desktop=src -d mypatches/java.desktop/src/java.desktop/javax/swing/Top.java
</code>```

But it does not work.

My project tree is 'GreatProject/src/javax/swing/Top.java'.

What's the 'src -d' means?

What's the right '--patch-module'?

答:
Starting from Java 9 version, full support for the jigsaw project was added to ensure the project's modularity. This system can cause problems at the compile process if the same names are present in packages.

Please, check this topic about the module patching process to adapt your module for javax.swing package.

Also, you may try to use Reflection API for getting elements from 'JOptionPane' class.

Body:
There is a class in my project. This class in package javax.swing extends javax.swing.JOptionPane because I want to use some protected methods of JOptionPane.

When the compiler is JDK 8 it works fine. I update the JDK version to 11 then I've got a compile error: Package 'javax.swing' exists in another module: java.desktop.

My IDE is Intellij idea. I opened the Settings--Build,Execution,Deployment--Java Compiler and added an item to 'Override compiler parameters pre-module'. The Module is my project. The compilation options is

--patch-module java.desktop=src -d mypatches/java.desktop/src/java.desktop/javax/swing/Top.java

But it does not work.

My project tree is 'GreatProject/src/javax/swing/Top.java'.

What's the 'src -d' means?

What's the right '--patch-module'?


问:
How to get $_POST and $_FILES requests with same loop in PHP
I have quiz application. where questions and answers adding dynamically with add more button. so I have no number of questions and number of answers for each questions. every questions have image, also every answers have image. I want to get every post and files request with foreach loop. I can't use for loop because I do not know every questions/answers key in array. reason why array key is not known is that maybe user add 5 questions dynamically and then delete 3th and 4th question array keys will be 0,1,4.

in this code problem is undefined offset 1

```<code>for ($i=1; $i<count($_POST['questions'])+1 ; $i++) {

        echo'```';
        echo ($_POST['questions'][$i]['question_en']);
        var_dump($_FILES['questions']['tmp_name'][$i]['image_en']);
        echo '
';
        for($j=1;$j<count($_POST['questions'][$i]['answers'])+1;$j++){
            echo $_POST['questions'][$i]['answers'][$j]['title_en'];
            var_dump($_FILES['questions']['tmp_name'][$i]['answers'][$j]['image_en']);

        }
        echo '```';

     }
</code>```

答:
If the keys of the images are the same of the questions, it might be se solution for you:

```<code>foreach( $_POST['questions'] as $question_key => $question ) {
  echo'```';
  echo ($question['question_en']);
  var_dump($_FILES['questions']['tmp_name'][$question_key]['image_en']);
  echo '
';
  foreach( $question['answers'] as $answer_key => $answer )  {
    echo $answer['title_en'];
    var_dump($_FILES['questions']['tmp_name'][$question_key]['answers'][$answer_key]['image_en']);
  }
  echo '```';
}
</code>```

Body:
I have quiz application. where questions and answers adding dynamically with add more button. so I have no number of questions and number of answers for each questions. every questions have image, also every answers have image. I want to get every post and files request with foreach loop. I can't use for loop because I do not know every questions/answers key in array. reason why array key is not known is that maybe user add 5 questions dynamically and then delete 3th and 4th question array keys will be 0,1,4.

in this code problem is undefined offset 1

for ($i=1; $i<count($_POST['questions'])+1 ; $i++) {

        echo'
';
        echo ($_POST['questions'][$i]['question_en']);
        var_dump($_FILES['questions']['tmp_name'][$i]['image_en']);
        echo '
';
        for($j=1;$j<count($_POST['questions'][$i]['answers'])+1;$j++){
            echo $_POST['questions'][$i]['answers'][$j]['title_en'];
            var_dump($_FILES['questions']['tmp_name'][$i]['answers'][$j]['image_en']);

        }
        echo '
';

     }

Body:
If the keys of the images are the same of the questions, it might be se solution for you:

foreach( $_POST['questions'] as $question_key => $question ) {
  echo'<pre>';
  echo ($question['question_en']);
  var_dump($_FILES['questions']['tmp_name'][$question_key]['image_en']);
  echo '<br>';
  foreach( $question['answers'] as $answer_key => $answer )  {
    echo $answer['title_en'];
    var_dump($_FILES['questions']['tmp_name'][$question_key]['answers'][$answer_key]['image_en']);
  }
  echo '</pre>';
}


问:
Reason why deep and shallow copy differences between "primitive" and "non-primitive" objects?
I know the difference between shallow and deep copy in Python, and the question is not about when to use one or the other. However I find this trivial example pretty amusing and non-intuitive

```<code>from copy import deepcopy

 a=0
 b=deepcopy(a)
 c=a
 a+=1
 print(a,b,c)
</code>```

output: 1 0 0

```<code> from copy import deepcopy
 a=[0]
 b=deepcopy(a)
 c=a
 a[0]+=1
 print(a,b,c)
</code>```

output: [1] 0 [1]

I would like to know the reason why this design choice was made, since the two snippets of code are in my opinion quite equivalent however their output is completely different. To make myself more explicit I wonder why = is a deepcopy in the case of a "primitive" variable  and a shallow copy in the case of a "non-primitive" (but still part of the basic language) variable like a list? I personally find this behavior counter-intuitive
Note: I used python 3

答:
It is commonplace to link objects between them during copies and not primitives.

The difference between your snippets is that, in the second one, c is a copy of the list a, and a list is an object, so they are linked. Whereas c was a "copy" of a primitive in the first snippet, which doesn't link.

Body:
I know the difference between shallow and deep copy in Python, and the question is not about when to use one or the other. However I find this trivial example pretty amusing and non-intuitive

from copy import deepcopy

 a=0
 b=deepcopy(a)
 c=a
 a+=1
 print(a,b,c)

output: 1 0 0

 from copy import deepcopy
 a=[0]
 b=deepcopy(a)
 c=a
 a[0]+=1
 print(a,b,c)

output: [1] 0 [1]

I would like to know the reason why this design choice was made, since the two snippets of code are in my opinion quite equivalent however their output is completely different. To make myself more explicit I wonder why = is a deepcopy in the case of a "primitive" variable  and a shallow copy in the case of a "non-primitive" (but still part of the basic language) variable like a list? I personally find this behavior counter-intuitive
Note: I used python 3


问:
Difference between django-environ and python-decouple?
Here I have used django-environ to set the environment variable but it is giving me SECRET_KEY error.How to properly configure the environmental variable?

I also used the python-decouple for this instead of django-environ which works fine but didn't work with django-environ.

What is the difference between django-environ and python-decouple which will be the best for this ?

settings

```<code>import environ
env = environ.Env()

SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool("DEBUG", False)
</code>```

.env file

```<code>DEBUG = True
SECRET_KEY = #qoh86ptbe51lg0o#!v1#h(t+g&!4_v7f!ovsl^58bo)g4hqkq #this is the django gives
</code>```

Got this exception while using django-environ

django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY
  environment variable

答:
django-environ works fine, but you need to load the .env file – just instantiating an Env does not do that:

```<code>import environ
env = environ.Env()
env.read_env()

SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool("DEBUG", False)
</code>```

In addition, I've found it an useful idiom to have "sane defaults" based on the DEBUG value (which must only be true when developing):

```<code>DEBUG = env.bool("DEBUG", False)
SECRET_KEY = env('SECRET_KEY', default=('insecure' if DEBUG else Env.NOTSET))
</code>```

Setting Env.NOTSET as the default will have django-environ complain for unset values.

Body:
Here I have used django-environ to set the environment variable but it is giving me SECRET_KEY error.How to properly configure the environmental variable?

I also used the python-decouple for this instead of django-environ which works fine but didn't work with django-environ.

What is the difference between django-environ and python-decouple which will be the best for this ?

settings

import environ
env = environ.Env()

SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool("DEBUG", False)

.env file

DEBUG = True
SECRET_KEY = #qoh86ptbe51lg0o#!v1#h(t+g&!4_v7f!ovsl^58bo)g4hqkq #this is the django gives

Got this exception while using django-environ

django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY
  environment variable

Body:
django-environ works fine, but you need to load the .env file – just instantiating an Env does not do that:

import environ
env = environ.Env()
env.read_env()

SECRET_KEY = env('SECRET_KEY')
DEBUG = env.bool("DEBUG", False)

In addition, I've found it an useful idiom to have "sane defaults" based on the DEBUG value (which must only be true when developing):

DEBUG = env.bool("DEBUG", False)
SECRET_KEY = env('SECRET_KEY', default=('insecure' if DEBUG else Env.NOTSET))

Setting Env.NOTSET as the default will have django-environ complain for unset values.


问:
Graphql Sangria Many-to-Many example
I'm working on a Many-to-Many relation with Sangria and Slick.
I have 3 objects: Role, Permission and RolePermission (a mapping table)

```<code>case class Role(id: Long, name: String)
case class Permission(id: Long, name: String)
case class RolePermission(id: Long, roleId: Long, permissionId: Long)
</code>```

So far I figured out how to define the relation:

```<code>val permissionsByRoleId = Relation[Permission, (RolePermission, Permission), Long]("permissionsByRoleId", tmp ⇒ Seq(tmp._1.roleId), _._2)
</code>```

I don't know how to define the fetcher and how to add the right field to Role Schema, so that I could retrieve the Role's permissions passing by the intermediate table.

Any help ?

答: You have to define Relation type for both related entities. It's not easy to answer in short comment on StackOverflow, but I've explained such kind of relation in my blog post: https://scalac.io/akka-http-sangria-graphql-backend#implementing-many-to-many-relation I hope it helps..

Title: Graphql Sangria Many-to-Many example

Body:
I'm working on a Many-to-Many relation with Sangria and Slick.
I have 3 objects: Role, Permission and RolePermission (a mapping table)

case class Role(id: Long, name: String)
case class Permission(id: Long, name: String)
case class RolePermission(id: Long, roleId: Long, permissionId: Long)

So far I figured out how to define the relation:

val permissionsByRoleId = Relation[Permission, (RolePermission, Permission), Long]("permissionsByRoleId", tmp ⇒ Seq(tmp._1.roleId), _._2)

I don't know how to define the fetcher and how to add the right field to Role Schema, so that I could retrieve the Role's permissions passing by the intermediate table.

Any help ?


问:
Pyinstaller Intel MKL fatal error when running .exe file Python 2.7
I have made a GUI application using wxpython and some other packages (matplotlib, pandas, numpy). I tried to compile this into a standalone executable. However, when I run the 'my_script.exe'  I get the following error in my command prompt:

Intel MKL FATAL ERROR: Cannot load mkl_avx2.dll or mkl_def.dll.

The versions I am using are:

Anaconda 2.0.0 (Python 2.7) 64 bit

Setuptools 19.2 (downgraded from 20.3 because of import error)

Thanks in advance for helping me!

答:
Try this Command in Command Prompt

conda install --yes mkl mkl-service
```


问:
How to remove the first weather in weather forecast using weather api
here's the code.

```<code>setWeatherForecast(unit: any, scaleTemp: any) {
    this.forecast.splice(0, this.forecast.length);
    this.weatherService.getLocation().subscribe(data => {
      this.lat = JSON.parse(data['_body']).latitude;
      this.lon = JSON.parse(data['_body']).longitude;

      this.weatherService
        .fiveDayForecast(this.lat, this.lon, unit)
        .subscribe(forecastData => {
          for (let i = 0; i < forecastData.list.length; i = i + 8) {
            console.log(forecastData.list[i]);
            const forecastWeather = new Forecast(
              forecastData.city.name,
              forecastData.list[i].weather[0].description,
              forecastData.list[i].main.temp.toFixed(0) + scaleTemp,
              forecastData.list[i].dt_txt.replace(/\s/, 'T'),
              forecastData.list[i].weather[0].icon
            );
            this.forecast.push(forecastWeather);
          }
          return this.forecast;
        });
    });
  }
</code>```

what I want is to remove the first weather in weather forecast.
for example.

friday, saturday, sunday, monday, tuesday, wednesday

it will remove the saturday. it only display the sunday to tuesday.

答:
return this.forecast.shift();

to remove the first weather in forecast.

you can use the shift() - method removes the first element from an array and returns that removed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

Body:
here's the code.

setWeatherForecast(unit: any, scaleTemp: any) {
    this.forecast.splice(0, this.forecast.length);
    this.weatherService.getLocation().subscribe(data => {
      this.lat = JSON.parse(data['_body']).latitude;
      this.lon = JSON.parse(data['_body']).longitude;

      this.weatherService
        .fiveDayForecast(this.lat, this.lon, unit)
        .subscribe(forecastData => {
          for (let i = 0; i < forecastData.list.length; i = i + 8) {
            console.log(forecastData.list[i]);
            const forecastWeather = new Forecast(
              forecastData.city.name,
              forecastData.list[i].weather[0].description,
              forecastData.list[i].main.temp.toFixed(0) + scaleTemp,
              forecastData.list[i].dt_txt.replace(/\s/, 'T'),
              forecastData.list[i].weather[0].icon
            );
            this.forecast.push(forecastWeather);
          }
          return this.forecast;
        });
    });
  }

what I want is to remove the first weather in weather forecast.
for example.

friday, saturday, sunday, monday, tuesday, wednesday

it will remove the saturday. it only display the sunday to tuesday.


问:
How to merge two forms into one?
I want to have these two buttons in one line, so Remove button is in the position in which it is and the Update mapping button is on the right.
So it would looks like this:

[![enter image description here][1]][1]

答:
You just add style "display : inline-block" to your forms.

            <form style="display: inline-block" action="/.../delete" method="post">
                <button type="submit" name="name1" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="secondary">Remove
                </button>
            </form>
            <form style="display: inline-block" action="/.../update" method="get">
                <button type="submit" name="name2" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="button primary">Update mapping
                </button>
            </form>

```

Title: How to merge two forms into one?

Body:
You just add style "display : inline-block" to your forms.

<div>
            <form style="display: inline-block" action="/.../delete" method="post">
                <button type="submit" name="name1" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="secondary">Remove
                </button>
            </form>
            <form style="display: inline-block" action="/.../update" method="get">
                <button type="submit" name="name2" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="button primary">Update mapping
                </button>
            </form>
            <pre th:utext="${tmpl.response}"/>
        </div>


问:
Image orientation is changed on ImageView When fetching from Gallery and upload
I simply want to fetch Images from gallery and upload then download from Server and set it on an ImageView on Activity. The image View is placed at the center of the Activity. All is working fine just a screenOrientation variation problem with adjusting Image on ImageView after fetching it from Server, download and set to image View. Please have a look over code what i am using to download Image Bitmap from Server and set it to required ImageView. It usually display rotated Image in case of portrait capturing image from Gallery or Camera. Please let me know if i am missing anything in my Code.</p>

```<code>package com.fedorvlasov.lazylist;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.example.qlique.R;
import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    Handler handler = new Handler();// handler to display images in UI thread

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.stub;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        // from SD cache
        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // from web
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
}
</code>```

答:
One nice online tool to view the Orientation and the details EXIF information http://metapicz.com/#exif-box.

It would be good if you can fix/reset the orientation at the server side(once per image) and alternatively fixing at the client side is a bit costly ( as this conversion to happen every time )

Body:
I simply want to fetch Images from gallery and upload then download from Server and set it on an ImageView on Activity. The image View is placed at the center of the Activity. All is working fine just a screenOrientation variation problem with adjusting Image on ImageView after fetching it from Server, download and set to image View. Please have a look over code what i am using to download Image Bitmap from Server and set it to required ImageView. It usually display rotated Image in case of portrait capturing image from Gallery or Camera. Please let me know if i am missing anything in my Code.

package com.fedorvlasov.lazylist;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.example.qlique.R;
import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    Handler handler = new Handler();// handler to display images in UI thread

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.stub;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        // from SD cache
        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // from web
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
}


问:
how to use useRef to reference latest value
People use useRef to save latest value like this code

```<code>function MyComponent({ value }) {
  const valueRef = useRef();
  useEffect(() => {
    valueRef.current = value;
  });
}
</code>```

I know useEffect needs for concurrent mode.

and useEffect is executed in the order of the definition

```<code>function MyComponent({ value }) {
  useEffect(() => {
    console.log('log1');
  });
  useEffect(() => {
    console.log('log2');
  });
}
// result is
// log1
// log2
</code>```

so in the below code,
log1 is printed with old value and log2 is printed with new value

```<code>function MyComponent({ value }) {
  const valueRef = useRef();
  useEffect(() => {
    console.log('log1', valueRef.current);
  });
  useEffect(() => {
    valueRef.current = value;
  });
  useEffect(() => {
    console.log('log2', valueRef.current);
  });
}
</code>```

I think it's weird because the value is different according to the position.

What is the right way to use useRef to reference latest value?
(FYI I know it's better to use deps than to use useRef)

答:
The idiomatic way is to store some "current" value for the next render and retrieve the current ref value (the previous value). Hooks FAQ: How to get the previous props or state

```<code>const prevValueRef = useRef();
useEffect(() => {
  prevValueRef.current = value; // cache current value for next render
});
const prevValue = prevValueRef.current; // get previous value from last render
</code>```

Running sandbox demo

Body:
People use useRef to save latest value like this code

function MyComponent({ value }) {
  const valueRef = useRef();
  useEffect(() => {
    valueRef.current = value;
  });
}

I know useEffect needs for concurrent mode.

and useEffect is executed in the order of the definition

function MyComponent({ value }) {
  useEffect(() => {
    console.log('log1');
  });
  useEffect(() => {
    console.log('log2');
  });
}
// result is
// log1
// log2

so in the below code,
log1 is printed with old value and log2 is printed with new value

function MyComponent({ value }) {
  const valueRef = useRef();
  useEffect(() => {
    console.log('log1', valueRef.current);
  });
  useEffect(() => {
    valueRef.current = value;
  });
  useEffect(() => {
    console.log('log2', valueRef.current);
  });
}

I think it's weird because the value is different according to the position.

What is the right way to use useRef to reference latest value?
(FYI I know it's better to use deps than to use useRef)

Body:
The idiomatic way is to store some "current" value for the next render and retrieve the current ref value (the previous value). Hooks FAQ: How to get the previous props or state

const prevValueRef = useRef();
useEffect(() => {
  prevValueRef.current = value; // cache current value for next render
});
const prevValue = prevValueRef.current; // get previous value from last render

Running sandbox demo


问:
Cannot store particular Unicode code points / characters in NVARCHAR fields
I'm doing some tests with SQL Server 2017.
I'm trying to store arbitrary Unicode code points in an NVARCHAR column.
I've tried different collations.
I have no problem with common characters in the BMP plane of Unicode.

For more exotic symbols, for example if I try to store the "" character (U+1D33), the following happens:

If I do it within Management Studio, I only see the infamous square symbol. But Management Studio has the proper font since I can paste it in the query editor.

If I send the text from Visual Studio, the value I see in Management Studio is "??", that's what I retrieve from Visual Studio, too, after performing a query.

My understanding is, for non-supplementary character collations, characters outside the UCS-2 subset shouldn't be interpreted correctly because NCHAR fields are limited to 2 bytes.

But, I tried with Latin1_General_100_CS_AS_KS_WS_SC, both at the DB level and column level, and it doesn't seem to work either.

Any ideas?
Thanks

答:
I'm trying to store arbitrary unicode points in an nvarchar column. I've tried different collations. I have no problem with common characters in the PBS plane of Unicode.

Collations have nothing to do with what code points you can store in an NVARCHAR / NCHAR / NTEXT (deprecated) column, variable, or literal. Those datatypes can store all 1,114,112 Unicode code points (even though most haven't been mapped to a character yet).

if I try to store  character(U+1D33), ... within Management Studio, i only see the infamous square symbol. But management studio has the proper font since i can paste it in the query editor.

As others have explained already: this is merely a font issue. Fonts can hold a max of 65k characters, so you might need multiple fonts to cover all of the characters you are trying to use. I prefer Code2003 which you can find on FontSpace.com.

If i send the text from Visual Studio, the value i see in management studio is '??'

This should be due to forgetting to prefix the string literal with an upper-case "N" ;-).

SELECT '' AS [Oops], N'' AS [No Oops];
-- ??
```

My understanding is, for non supplementary character collations, characters outside the UCS-2 subset shouldn't be interpreted correctly because nchar fields are limited to 2 bytes.

The Supplementary Character-Aware (SCA) collations — those ending with _SC or with _140_ in their names — do support supplementary characters. BUT, "support" only means that the built-in functions handle the surrogate pair as a single, supplementary code point instead a pair of surrogate code points. But, support for sorting and comparison of supplementary characters actually started in SQL Server 2005 with the introduction of the version 90 collations.

All code units in UCS-2 and UTF-16 are 16 bits / 2 bytes. Supplementary characters are merely two of those 2-byte code units. Hence, being able to store supplementary characters should have been available back in SQL Server 7.0 when NVARCHAR was introduced. Even though no supplementary characters were defined until years later (after SQL Server 2000 was released), the NVARCHAR types were still capable of storing and retrieving them. I don't have SQL Server 7.0 to test with, but I have confirmed this on SQL Server 2000.

For more info, please see:

How Many Bytes Per Character in SQL Server: a Completely Complete Guide

Collations Info

Body:
I'm trying to store arbitrary unicode points in an nvarchar column. I've tried different collations. I have no problem with common characters in the PBS plane of Unicode.

Collations have nothing to do with what code points you can store in an NVARCHAR / NCHAR / NTEXT (deprecated) column, variable, or literal. Those datatypes can store all 1,114,112 Unicode code points (even though most haven't been mapped to a character yet).

if I try to store  character(U+1D33), ... within Management Studio, i only see the infamous square symbol. But management studio has the proper font since i can paste it in the query editor.

As others have explained already: this is merely a font issue. Fonts can hold a max of 65k characters, so you might need multiple fonts to cover all of the characters you are trying to use. I prefer Code2003 which you can find on FontSpace.com.

If i send the text from Visual Studio, the value i see in management studio is '??'

This should be due to forgetting to prefix the string literal with an upper-case "N" ;-).

SELECT '' AS [Oops], N'' AS [No Oops];
-- ??

My understanding is, for non supplementary character collations, characters outside the UCS-2 subset shouldn't be interpreted correctly because nchar fields are limited to 2 bytes.

The Supplementary Character-Aware (SCA) collations — those ending with _SC or with _140_ in their names — do support supplementary characters. BUT, "support" only means that the built-in functions handle the surrogate pair as a single, supplementary code point instead a pair of surrogate code points. But, support for sorting and comparison of supplementary characters actually started in SQL Server 2005 with the introduction of the version 90 collations.

All code units in UCS-2 and UTF-16 are 16 bits / 2 bytes. Supplementary characters are merely two of those 2-byte code units. Hence, being able to store supplementary characters should have been available back in SQL Server 7.0 when NVARCHAR was introduced. Even though no supplementary characters were defined until years later (after SQL Server 2000 was released), the NVARCHAR types were still capable of storing and retrieving them. I don't have SQL Server 7.0 to test with, but I have confirmed this on SQL Server 2000.

For more info, please see:

How Many Bytes Per Character in SQL Server: a Completely Complete Guide

Collations Info


问:
3D plot of x1 and x2 versus z, where z is defined as z = x1^2 + 0.1*x1 in R
Heres my code:

```<code>x1 = seq(from=0,to=1,length.out=10)
x2 = seq(from=0,to=1,length.out=10)
x1x2 = expand.grid(x1,x2)

z = (x1)^2+0.1*(x1)

z = length(length(x1x2))
x1x2z = data.frame(x1x2,z)
x1x2z

colnames(xyz) = c("x1=","x2","z")
head(x1x2z,3)
plot_ly(x1x2z,x1=~x,x2=~x2,z=~z,color="red")
</code>```

I am getting the error:

```<code>No trace type specified:
  Based on info supplied, a 'scatter3d' trace seems appropriate.
  Read more about this trace type -> https://plot.ly/r/reference/#scatter3d
Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 10: Column `x`
* Length 100: Columns `y`, `z`
</code>```

答:
I debugged your code and used scatterplot3d instead of plot_ly.

```<code>> x1 = seq(from=0,to=1,length.out=50) # 10 seems too few
> x2 = seq(from=0,to=1,length.out=50)
> x1x2 = expand.grid(x1,x2)

> z = (x1)^2+0.1*(x1)

> #z = length(length(x1x2))  # Why do this?
> x1x2z = data.frame(x1x2,z)
> colnames(x1x2z) = c("x1","x2","z")
> head(x1x2z,3)
          x1 x2           z
1 0.00000000  0 0.000000000
2 0.02040816  0 0.002457309
3 0.04081633  0 0.005747605

> library(scatterplot3d)
> scatterplot3d(x1x2z, color="red")
</code>```

Body:
Heres my code:

x1 = seq(from=0,to=1,length.out=10)
x2 = seq(from=0,to=1,length.out=10)
x1x2 = expand.grid(x1,x2)

z = (x1)^2+0.1*(x1)

z = length(length(x1x2))
x1x2z = data.frame(x1x2,z)
x1x2z

colnames(xyz) = c("x1=","x2","z")
head(x1x2z,3)
plot_ly(x1x2z,x1=~x,x2=~x2,z=~z,color="red")

I am getting the error:

No trace type specified:
  Based on info supplied, a 'scatter3d' trace seems appropriate.
  Read more about this trace type -> https://plot.ly/r/reference/#scatter3d
Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 10: Column `x`
* Length 100: Columns `y`, `z`

Body:
I debugged your code and used scatterplot3d instead of plot_ly.

> x1 = seq(from=0,to=1,length.out=50) # 10 seems too few
> x2 = seq(from=0,to=1,length.out=50)
> x1x2 = expand.grid(x1,x2)

> z = (x1)^2+0.1*(x1)

> #z = length(length(x1x2))  # Why do this?
> x1x2z = data.frame(x1x2,z)
> colnames(x1x2z) = c("x1","x2","z")
> head(x1x2z,3)
          x1 x2           z
1 0.00000000  0 0.000000000
2 0.02040816  0 0.002457309
3 0.04081633  0 0.005747605

> library(scatterplot3d)
> scatterplot3d(x1x2z, color="red")


问:
Reading line by line from text file and assign each value into a specific variable
I have to build an automated test scenario where I need to populate multiple fields in a web page. The data to populate the specific fields come from a text file

```<code>in1=data1,in2=data2,in3=data3
in11=data11,in12=data12,in13=data13
in21=data21,in22=data22,in23=data23
</code>```

where each key/value pair is deliminated by a comma.

I need to read this file, line by line, and assign each key/value pair to its unique variable.
Once the key/value pairs have been assigned to a unique variable I will pass those variables as parameters to a python script that uses the parameters to build a dictionary object and hands it to a http request.

I have completed a python script that uses a python array instead of a text file to read the key/value pairs from and have successfully passed that to the http request and successfully filled the fields in the web page.

However, I need to be able to read the data from the bash script so that I can send the values to the python script

So far, in the bash script, I can read from the file and, using awk, print each key/value pair to the screen. However, I need to be able to assign each key/value pair to a variable as I read the text file line by line.

In the end I should have for line one:

```<code>var1 = in1, var2 = data1, var3 = in2, var4 = data2, var5 = in3, var6 = data3
</code>```

Now, line one is passed to the python script

```<code>  %python python_script.py $var1 $var2 $var3 $var4 $var5 $var6
</code>```

Then, read next line from text file and assign key/value pair to unique variable and send the variables to the python script.

```<code>while read line
do
    echo $line | awk  (Could not figure out the arguments for awk)
    python python_script.py [parameter list]
done < input_file.txt
</code>```

答:
I'm not sure than understand what you need, but this:

```<code>< input_file.txt sed 's/[^A-Za-z0-9]/ /g' | while read line
do
    python python_script.py $line
done
</code>```

will run your python_script.py as next:

```<code>python python_script.py in1 data1 in2 data2 in3 data3
python python_script.py in11 data11 in12 data12 in13 data13
python python_script.py in21 data21 in22 data22 in23 data23
</code>```

this is ok?

ps: dont worry, your python got 6 parameters, not only 1 :)

Body:
I have to build an automated test scenario where I need to populate multiple fields in a web page. The data to populate the specific fields come from a text file

in1=data1,in2=data2,in3=data3
in11=data11,in12=data12,in13=data13
in21=data21,in22=data22,in23=data23

where each key/value pair is deliminated by a comma.

I need to read this file, line by line, and assign each key/value pair to its unique variable.
Once the key/value pairs have been assigned to a unique variable I will pass those variables as parameters to a python script that uses the parameters to build a dictionary object and hands it to a http request.

I have completed a python script that uses a python array instead of a text file to read the key/value pairs from and have successfully passed that to the http request and successfully filled the fields in the web page.

However, I need to be able to read the data from the bash script so that I can send the values to the python script

So far, in the bash script, I can read from the file and, using awk, print each key/value pair to the screen. However, I need to be able to assign each key/value pair to a variable as I read the text file line by line.

In the end I should have for line one:

var1 = in1, var2 = data1, var3 = in2, var4 = data2, var5 = in3, var6 = data3

Now, line one is passed to the python script

  %python python_script.py $var1 $var2 $var3 $var4 $var5 $var6

Then, read next line from text file and assign key/value pair to unique variable and send the variables to the python script.

while read line
do
    echo $line | awk  (Could not figure out the arguments for awk)
    python python_script.py [parameter list]
done < input_file.txt

Body:
I'm not sure than understand what you need, but this:

< input_file.txt sed 's/[^A-Za-z0-9]/ /g' | while read line
do
    python python_script.py $line
done

will run your python_script.py as next:

python python_script.py in1 data1 in2 data2 in3 data3
python python_script.py in11 data11 in12 data12 in13 data13
python python_script.py in21 data21 in22 data22 in23 data23

this is ok?

ps: dont worry, your python got 6 parameters, not only 1 :)


问:
How can I fix my bash script to find a random word from a dictionary?
I'm studying bash scripting and I'm stuck fixing an exercise of this site: https://ryanstutorials.net/bash-scripting-tutorial/bash-variables.php#activities

The task is to write a bash script to output a random word from a dictionary whose length is equal to the number supplied as the first command line argument.

My idea was to create a sub-dictionary, assign each word a number line, select a random number from those lines and filter the output, which worked for a similar simpler script, but not for this.

This is the code I used:

```<code>  6 DIC='/usr/share/dict/words'
  7 SUBDIC=$( egrep '^.{'$1'}$' $DIC )
  8
  9 MAX=$( $SUBDIC | wc -l )
 10 RANDRANGE=$((1 + RANDOM % $MAX))
 11
 12 RWORD=$(nl "$SUBDIC" | grep "\b$RANDRANGE\b" | awk '{print $2}')
 13
 14 echo "Random generated word from $DIC which is $1 characters long:"
 15 echo $RWORD
</code>```

and this is the error I get using as input "21":

```<code>bash script.sh 21
script.sh: line 9: counterintelligence's: command not found
script.sh: line 10: 1 + RANDOM % 0: division by 0 (error token is "0")
nl: 'counterintelligence'\''s'$'\n''electroencephalograms'$'\n''electroencephalograph': No such file or directory
Random generated word from /usr/share/dict/words which is 21 characters long:

</code>```

I tried in bash to split the code in smaller pieces obtaining no error (input=21):

```<code>egrep '^.{'21'}$' /usr/share/dict/words | wc -l
3
</code>```

but once in the script line 9 and 10 give error.

Where do you think is the error?

答:
This code will do it. My test dictionary of words is in file file. It's a good idea to get all words of a given length first but put them in an array not in var. And then get a random index and echo it.

```<code>dic=( $(sed -n "/^.\{$1\}$/p" file) )
ind=$((0 + RANDOM % ${#dic[@]}))
echo ${dic[$ind]}
</code>```

Body:
I'm studying bash scripting and I'm stuck fixing an exercise of this site: https://ryanstutorials.net/bash-scripting-tutorial/bash-variables.php#activities

The task is to write a bash script to output a random word from a dictionary whose length is equal to the number supplied as the first command line argument.

My idea was to create a sub-dictionary, assign each word a number line, select a random number from those lines and filter the output, which worked for a similar simpler script, but not for this.

This is the code I used:

  6 DIC='/usr/share/dict/words'
  7 SUBDIC=$( egrep '^.{'$1'}$' $DIC )
  8
  9 MAX=$( $SUBDIC | wc -l )
 10 RANDRANGE=$((1 + RANDOM % $MAX))
 11
 12 RWORD=$(nl "$SUBDIC" | grep "\b$RANDRANGE\b" | awk '{print $2}')
 13
 14 echo "Random generated word from $DIC which is $1 characters long:"
 15 echo $RWORD

and this is the error I get using as input "21":

bash script.sh 21
script.sh: line 9: counterintelligence's: command not found
script.sh: line 10: 1 + RANDOM % 0: division by 0 (error token is "0")
nl: 'counterintelligence'\''s'$'\n''electroencephalograms'$'\n''electroencephalograph': No such file or directory
Random generated word from /usr/share/dict/words which is 21 characters long:

I tried in bash to split the code in smaller pieces obtaining no error (input=21):

egrep '^.{'21'}$' /usr/share/dict/words | wc -l
3

but once in the script line 9 and 10 give error.

Where do you think is the error?

Body:
This code will do it. My test dictionary of words is in file file. It's a good idea to get all words of a given length first but put them in an array not in var. And then get a random index and echo it.

dic=( $(sed -n "/^.\{$1\}$/p" file) )
ind=$((0 + RANDOM % ${#dic[@]}))
echo ${dic[$ind]}


问:
How can I solve this problem nested renamer is not supported
```<code>SpecificationError                        Traceback (most recent call last)
<ipython-input-42-d850d85f8342> in <module>
----> 1 train_label=extract_feature(train,train_label)

<ipython-input-33-23ab8dbf7d96> in extract_feature(df, train)
      1 def extract_feature(df,train):
----> 2     t=groupy_feature(df,'ship','x',['max','min','mean','std','median','std','skew','sum'])
      3     train=pd.merge(train,t,on='ship',how='left')
      4     t=groupy_feature(df,'ship','y',['max','min','mean','std','median','std','skew','sum'])
      5     train=pd.merge(train,t,on='ship',how='left')

<ipython-input-32-63d47754fe81> in groupy_feature(df, key, target, aggs)
      4         agg_dict[f'{target}_{agg}']=agg
      5     print(agg_dict)
----> 6     t=df.groupby(key)[target].agg(agg_dict).reset_index()
      7     return t

~\AppData\Roaming\Python\Python37\site-packages\pandas\core\groupby\generic.py in aggregate(self, func, *args, **kwargs)
    251             # but not the class list / tuple itself.
    252             func = _maybe_mangle_lambdas(func)
--> 253             ret = self._aggregate_multiple_funcs(func)
    254             if relabeling:
    255                 ret.columns = columns

~\AppData\Roaming\Python\Python37\site-packages\pandas\core\groupby\generic.py in _aggregate_multiple_funcs(self, arg)
    292             # GH 15931
    293             if isinstance(self._selected_obj, Series):
--> 294                 raise SpecificationError("nested renamer is not supported")
    295
    296             columns = list(arg.keys())

**SpecificationError: nested renamer is not supported**
</code>```

答:
I see two times the term 'std' in

t=groupy_feature(df,'ship','x',['max','min','mean','std','median','std','skew','sum'])


答:
You should use bootstrap's grid system:

```<code><html>
....
<div class="collapse">
    <th:block th:each="tmpl,iterStat : ${templates}">
        ...
        <div class="row">
          <div class="col">
            <form action="/.../delete" method="post">
                <button type="submit" name="name1" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="secondary">Remove
                </button>
            </form>
          </div>
          <div class="col">
            <form action="/.../update" method="get">
                <button type="submit" name="name2" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="button primary">Update mapping
                </button>
            </form>
          </div>
            <pre th:utext="${tmpl.response}"/>
        </div>
    </th:block>
</div>
</body>
</html>
</code>```

Now you can set the width of columns changing the col class. Here's the guide: Bootstrap Grid System

Title: How to merge two forms into one?

Body:
I want to have these two buttons in one line, so Remove button is in the position in which it is and the Update mapping button is on the right.
So it would looks like this:

[![enter image description here][1]][1]

Body:
You should use bootstrap's grid system:

<html>
....
<div class="collapse">
    <th:block th:each="tmpl,iterStat : ${templates}">
        ...
        <div class="row">
          <div class="col">
            <form action="/.../delete" method="post">
                <button type="submit" name="name1" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="secondary">Remove
                </button>
            </form>
          </div>
          <div class="col">
            <form action="/.../update" method="get">
                <button type="submit" name="name2" th:value="${tmpl.variable1} + '_' + ${tmpl.variable2}"
                        class="button primary">Update mapping
                </button>
            </form>
          </div>
            <pre th:utext="${tmpl.response}"/>
        </div>
    </th:block>
</div>
</body>
</html>

Now you can set the width of columns changing the col class. Here's the guide: Bootstrap Grid System


问:
How do I execute an external JavaScript every few seconds?
I like to load an external JavaScript once every 10 seconds or so. Or whenever the body of the page is clicked(if so, I need to run the script only if few seconds are passed).
Even if anyone points me to the documentation., it will be more than sufficient.</p>

答:
setInterval(function(){ alert("Hello"); }, 10000); //will execute the alert every 10 seconds.

Please find an example here.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval


问:
Calico & K8S on Azure - can't access pods
I'm starting with K8S. I installed 2 Debian 10 VMs on Azure (1 master node & 2 slaves).

I installed the master node with this doc:
https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/

I installed Calico with this one :
https://docs.projectcalico.org/getting-started/kubernetes/installation/calico#installing-with-the-kubernetes-api-datastore50-nodes-or-less

I created a simple nginx deployment:

```<code>kubectl run nginx --replicas=2 --image=nginx
</code>```

I have the following pods (sazultk8s1/2 are the working nodes) :

```<code>root@itf-infra-sazultk8s0-vm:~# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP               NODE
nginx-6db489d4b7-mzmnq              1/1     Running   0          12s   192.168.47.18     itf-infra-sazultk8s2-vm
nginx-6db489d4b7-sgdz7              1/1     Running   0          12s   192.168.247.115   itf-infra-sazultk8s1-vm
</code>```

From the master node I can't curl to these nginx:

```<code>root@itf-infra-sazultk8s0-vm:~# curl 192.168.47.18 --connect-timeout 5
curl: (28) Connection timed out after 5001 milliseconds
root@itf-infra-sazultk8s0-vm:~# curl 192.168.247.115 --connect-timeout 5
curl: (28) Connection timed out after 5000 milliseconds
</code>```

I tried from a simple busybox image:

```<code>kubectl run access --rm -ti --image busybox /bin/sh
/ #ifconfig eth0 | grep -i inet
   inet addr:192.168.247.116  Bcast:0.0.0.0  Mask:255.255.255.255
/ # wget --timeout 5 192.168.247.115
Connecting to 192.168.247.115 (192.168.247.115:80)
saving to 'index.html'
index.html           100% |********************************************************************************************************|   612  0:00:00 ETA
'index.html' saved
/ # wget --timeout 5 192.168.47.18
Connecting to 192.168.47.18 (192.168.47.18:80)
wget: download timed out
</code>```

From a scratch install:

does a pod can ping a pod on another host ?

is it possible to curl from master node to a pod on a worker node ?

does azure apply restrictions and prevent k8s to work properly ?

答:
does a pod can ping a pod on another host ?

As per kubernetes networking model yes as long as you have a  CNI provider installed.

is it possible to curl from master node to a pod on a worker node ?

You need to create either Nodeport or Loadbalancer type service to access your pods from outside the cluster and for accessing pods from nodes.

does azure apply restrictions and prevent k8s to work properly ?

There may be firewalls restricting traffic between VMs.

Body:
I'm starting with K8S. I installed 2 Debian 10 VMs on Azure (1 master node & 2 slaves).

I installed the master node with this doc:
https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/

I installed Calico with this one :
https://docs.projectcalico.org/getting-started/kubernetes/installation/calico#installing-with-the-kubernetes-api-datastore50-nodes-or-less

I created a simple nginx deployment:

kubectl run nginx --replicas=2 --image=nginx

I have the following pods (sazultk8s1/2 are the working nodes) :

root@itf-infra-sazultk8s0-vm:~# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP               NODE
nginx-6db489d4b7-mzmnq              1/1     Running   0          12s   192.168.47.18     itf-infra-sazultk8s2-vm
nginx-6db489d4b7-sgdz7              1/1     Running   0          12s   192.168.247.115   itf-infra-sazultk8s1-vm

From the master node I can't curl to these nginx:

root@itf-infra-sazultk8s0-vm:~# curl 192.168.47.18 --connect-timeout 5
curl: (28) Connection timed out after 5001 milliseconds
root@itf-infra-sazultk8s0-vm:~# curl 192.168.247.115 --connect-timeout 5
curl: (28) Connection timed out after 5000 milliseconds

I tried from a simple busybox image:

kubectl run access --rm -ti --image busybox /bin/sh
/ #ifconfig eth0 | grep -i inet
   inet addr:192.168.247.116  Bcast:0.0.0.0  Mask:255.255.255.255
/ # wget --timeout 5 192.168.247.115
Connecting to 192.168.247.115 (192.168.247.115:80)
saving to 'index.html'
index.html           100% |********************************************************************************************************|   612  0:00:00 ETA
'index.html' saved
/ # wget --timeout 5 192.168.47.18
Connecting to 192.168.47.18 (192.168.47.18:80)
wget: download timed out

From a scratch install:

does a pod can ping a pod on another host ?

is it possible to curl from master node to a pod on a worker node ?

does azure apply restrictions and prevent k8s to work properly ?