问:
TypeError: songs.map is not a function
Hi I'm new to react Every time when i run the code it shows the same error. Can anyone explain what is wrong with this code.</p>

```<code>import React, { Component } from 'react'
import '../Search.css'
import axios from 'axios'

export default class Search extends Component {

    state = {
        songs: [],
    };

componentDidMount(key) {
    axios.get(`https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=`+key).then(res => {
        console.log(res);
        this.setState({songs: res.data});
    });
}
render() {
    const {songs} = this.state;
    return (
        <div className="container-fluid">

                    <input
                    type="text"
                    name="search"
                    placeholder="Search..."
                    id="search"
                    onChange={(event) => this.componentDidMount(event.target.value)}
                    />

                    <div>
                        {songs.map(song => (
                            <h1>{song.artistName}</h1>
                        ))}
                    </div>

        </div>

    )
  }
}
</code>```

答: The map method is available only for an Array type. This means that res.data is not an array. Please inspect the response coming from the request URL first.

Title: TypeError: songs.map is not a function

Body:
Hi I'm new to react Every time when i run the code it shows the same error. Can anyone explain what is wrong with this code.

import React, { Component } from 'react'
import '../Search.css'
import axios from 'axios'

export default class Search extends Component {

    state = {
        songs: [],
    };

componentDidMount(key) {
    axios.get(`https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=`+key).then(res => {
        console.log(res);
        this.setState({songs: res.data});
    });
}
render() {
    const {songs} = this.state;
    return (

                    <input
                    type="text"
                    name="search"
                    placeholder="Search..."
                    id="search"
                    onChange={(event) => this.componentDidMount(event.target.value)}
                    />

                        {songs.map(song => (

{song.artistName}

                        ))}

    )
  }
}


来源: stackexchange

问:
regex - How to match email:password regex combination only in the first 10 lines by ignoring the rest of the long text
I'm quite new to using regex and I'm trying to match email:password combinations in a long text using regex and below is the working regex I use for my requirement and I currently have a set of long text files to look for a possible match.

```<code>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+[*:]+(\b\w{5,}\b)
</code>```

However I wanted to know how could I match only the first 10 lines of my text. I want my regex to return a match only if there are email:password combinations in the first 10 lines and ignore the rest of the text. Any help would be appreciated.

```<code> Email : test@hotmail.com
 Password : password94
 Combo : test@hotmail.com:password94
 Plan : Premium
 Screens : 4
 HD : true
 UHD : true
 Expires in : 11-06-2019
 Country : en-PH
 NetFlix Checker | by xRisky
 Combo : test2@hotmail.com:password96
 Combo : test1@hotmail.com:password95
</code>```

For example I only want to match the first email:pass combo in the 3rd line and not the ones in line 11 and 12

答:
When I ran your code, it only returns empty lists, maybe the reason is because of this part:

```<code>(\b\w{5,}\b)
</code>```

Actually, after the colon, the password could be anything, so I changed the password to:

```<code>.+
</code>```

Here is my way:

```<code>import re
a = '''Email : test@hotmail.com
Password : password94
Combo : test@hotmail.com:password94
Plan : Premium
Screens : 4
HD : true
UHD : true
Expires in : 11-06-2019
Country : en-PH
NetFlix Checker | by xRisky
Combo : test2@hotmail.com:password96
Combo : test1@hotmail.com:password95'''
i = 0
for line in a.split('\n'):

    found = re.findall('[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+[*:]+.+',line)

    if found and i<=10:
        print(found)
    i+=1
</code>```

Output:

```<code>['test@hotmail.com:password94']
['test2@hotmail.com:password96']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm quite new to using regex and I'm trying to match email:password combinations in a long text using regex and below is the working regex I use for my requirement and I currently have a set of long text files to look for a possible match.

[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+[*:]+(\b\w{5,}\b)

However I wanted to know how could I match only the first 10 lines of my text. I want my regex to return a match only if there are email:password combinations in the first 10 lines and ignore the rest of the text. Any help would be appreciated.

 Email : test@hotmail.com
 Password : password94
 Combo : test@hotmail.com:password94
 Plan : Premium
 Screens : 4
 HD : true
 UHD : true
 Expires in : 11-06-2019
 Country : en-PH
 NetFlix Checker | by xRisky
 Combo : test2@hotmail.com:password96
 Combo : test1@hotmail.com:password95

For example I only want to match the first email:pass combo in the 3rd line and not the ones in line 11 and 12

Body:
When I ran your code, it only returns empty lists, maybe the reason is because of this part:

(\b\w{5,}\b)

Actually, after the colon, the password could be anything, so I changed the password to:

.+

Here is my way:

import re
a = '''Email : test@hotmail.com
Password : password94
Combo : test@hotmail.com:password94
Plan : Premium
Screens : 4
HD : true
UHD : true
Expires in : 11-06-2019
Country : en-PH
NetFlix Checker | by xRisky
Combo : test2@hotmail.com:password96
Combo : test1@hotmail.com:password95'''
i = 0
for line in a.split('\n'):

    found = re.findall('[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+[*:]+.+',line)

    if found and i<=10:
        print(found)
    i+=1

Output:

['test@hotmail.com:password94']
['test2@hotmail.com:password96']


问:
Codeigniter issue with escaping values when passing array to query with "in" in the where clause
I have the function below in my model for a codeigniter project, and the variable $id is an array and for example, contains (1,2,3). Now that i'm revisiting it, I think that i'm not actually escaping my array $id. I think I would have to change the line
$this->db->escape($id)
to
$id = $this->db->escape($id)

If I do that, then it puts single quotes around every element in the array and treats it as one long string like this: '(1,2,3)'.

Can someone confirm that I am not actually escaping my variable and either suggest a solution or let me know if this is a bug within the codeigniter framework?

```<code>function get_ratings($id)
    {

        $this->db->escape($id); // had to manually escape the variable since it's being used in an "in" in the where clause.

        $sql = "select * from toys t
                 where t.toy_id in ($id)";

        $query = $this->db->query($sql, $id);

        if($query->num_rows() > 0)
        {
            return $query->result_array();
        }
        else
        {
            return false;
        }
    }
</code>```

答:
You may be interested in using the CI Active Record class:

Beyond simplicity, a major benefit to using the Active Record features is that it allows you to create database independent applications, since the query syntax is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.

Your rewritten query would look like this (assuming $id is an array):

```<code>$this->db->where_in('toy_id', $id)->get('toys');
</code>```

Aside: I will admit I am a bit confused, as it looks like $ids would be a more appropriate variable name, and the way you are using it in the query, I would assume it is a string...

If active record is not your thing, you may also find Query Bindings to be useful:

The secondary benefit of using binds is that the values are automatically escaped, producing safer queries. You don't have to remember to manually escape data; the engine does it automatically for you.

EDIT: Looking back on this later, it looks like this is what you're trying to do. In that case, try replacing:

```<code>$sql = "select * from toys t where t.toy_id in ($id)";
</code>```

With:

```<code>$sql = "select * from toys t where t.toy_id in (?)";
</code>```

And pass $id as the second argument to query(), but as a comma separated string (implode(',', $id) if $id is indeed an array).

Otherwise you may want to use $this->db->escape_str().

$this->db->escape_str() This function escapes the data passed to it, regardless of type.

Here is an excerpt from the source code of the mysql driver to maybe put your mind at ease.

```<code>function escape_str($str, $like = FALSE)
{
    if (is_array($str))
    {
        foreach ($str as $key => $val)
        {
            $str[$key] = $this->escape_str($val, $like);
        }

        return $str;
    }
   // continued...
</code>```

It loops through arrays and escapes their values.

It does indeed seem that $this->db->escape is not going to work for arrays.

$this->db->escape() This function determines the data type so that it can escape only string data.

Here is the source:

```<code>function escape($str)
{
    if (is_string($str))
    {
        $str = "'".$this->escape_str($str)."'";
    }
    elseif (is_bool($str))
    {
        $str = ($str === FALSE) ? 0 : 1;
    }
    elseif (is_null($str))
    {
        $str = 'NULL';
    }

    return $str;
}
</code>```

Looks like it ignores arrays.

Anyways, hope you find a solution that works for you. My vote is for Active Record.

ContentLicense: CC BY-SA 3.0

Body:
I have the function below in my model for a codeigniter project, and the variable $id is an array and for example, contains (1,2,3). Now that i'm revisiting it, I think that i'm not actually escaping my array $id. I think I would have to change the line
$this->db->escape($id)
to
$id = $this->db->escape($id)

If I do that, then it puts single quotes around every element in the array and treats it as one long string like this: '(1,2,3)'.

Can someone confirm that I am not actually escaping my variable and either suggest a solution or let me know if this is a bug within the codeigniter framework?

function get_ratings($id)
    {

        $this->db->escape($id); // had to manually escape the variable since it's being used in an "in" in the where clause.

        $sql = "select * from toys t
                 where t.toy_id in ($id)";

        $query = $this->db->query($sql, $id);

        if($query->num_rows() > 0)
        {
            return $query->result_array();
        }
        else
        {
            return false;
        }
    }

Body:
You may be interested in using the CI Active Record class:

Beyond simplicity, a major benefit to using the Active Record features is that it allows you to create database independent applications, since the query syntax is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.

Your rewritten query would look like this (assuming $id is an array):

$this->db->where_in('toy_id', $id)->get('toys');

Aside: I will admit I am a bit confused, as it looks like $ids would be a more appropriate variable name, and the way you are using it in the query, I would assume it is a string...

If active record is not your thing, you may also find Query Bindings to be useful:

The secondary benefit of using binds is that the values are automatically escaped, producing safer queries. You don't have to remember to manually escape data; the engine does it automatically for you.

EDIT: Looking back on this later, it looks like this is what you're trying to do. In that case, try replacing:

$sql = "select * from toys t where t.toy_id in ($id)";

With:

$sql = "select * from toys t where t.toy_id in (?)";

And pass $id as the second argument to query(), but as a comma separated string (implode(',', $id) if $id is indeed an array).

Otherwise you may want to use $this->db->escape_str().

$this->db->escape_str() This function escapes the data passed to it, regardless of type.

Here is an excerpt from the source code of the mysql driver to maybe put your mind at ease.

function escape_str($str, $like = FALSE)
{
    if (is_array($str))
    {
        foreach ($str as $key => $val)
        {
            $str[$key] = $this->escape_str($val, $like);
        }

        return $str;
    }
   // continued...

It loops through arrays and escapes their values.

It does indeed seem that $this->db->escape is not going to work for arrays.

$this->db->escape() This function determines the data type so that it can escape only string data.

Here is the source:

function escape($str)
{
    if (is_string($str))
    {
        $str = "'".$this->escape_str($str)."'";
    }
    elseif (is_bool($str))
    {
        $str = ($str === FALSE) ? 0 : 1;
    }
    elseif (is_null($str))
    {
        $str = 'NULL';
    }

    return $str;
}

Looks like it ignores arrays.

Anyways, hope you find a solution that works for you. My vote is for Active Record.


问:
@PostConstruct and @PreDestroy annotations do not work
I have TennisCoach class:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class TennisCoach implements Coach {
    @Autowired
    @Qualifier("randomFortuneService")
    private FortuneService fortuneService;

    public TennisCoach() {
        System.out.println("Inside default constructor");
    }

    @PostConstruct
    public void doMyStartupStuff() {
        System.out.println("Inside postconstructor");
    }

    @PreDestroy
    public void doMyFinalStuff() {
        System.out.println("Inside predestroyer");
    }

    @Override
    public String getDailyFortune() {
        return fortuneService.getFortune();
    }

    @Override
    public String getDailyWorkout() {
        return "Practice your backhand volley";
    }
}
</code>```

And such main class:

```<code>import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnotationBeanScopeDemoApp {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        Coach theCoach = context.getBean("tennisCoach", Coach.class);

        System.out.println(theCoach.getDailyFortune());
        System.out.println(theCoach.getDailyWorkout());

        context.close();
    }
}
</code>```

Expected output is:

Inside default constructor

Inside postconstructor

DailyFortune

Practice your backhand volley

Inside predestroyer

But I get this:

Inside default constructor

DailyFortune

Practice your backhand volley

It seems like @PostContruct and @PreDestroy annotations do not work correctly. I cannot find the reason of my problem.

答:
Eclipse is unable to import @PostConstruct or @PreDestroy

This happens because of Java 9 and higher.

When using Java 9 and higher, javax.annotation has been removed from its default classpath.
Solution

Download the javax.annotation-api-1.3.2.jar from

maven.org

Copy the JAR file to the lib folder of your project

Use the following steps to add it to your Java Build Path.

Right-click your project, select Properties

On left-hand side, click Java Build Path

In top-center of dialog, click Libraries

Click Classpath and then Click Add JARs ...

Navigate to the JAR file /lib/javax.annotation-api-1.3.2.jar

Click OK then click Apply and Close

Eclipse will perform a rebuild of your project and it will resolve the related build errors.

Body:
I have TennisCoach class:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class TennisCoach implements Coach {
    @Autowired
    @Qualifier("randomFortuneService")
    private FortuneService fortuneService;

    public TennisCoach() {
        System.out.println("Inside default constructor");
    }

    @PostConstruct
    public void doMyStartupStuff() {
        System.out.println("Inside postconstructor");
    }

    @PreDestroy
    public void doMyFinalStuff() {
        System.out.println("Inside predestroyer");
    }

    @Override
    public String getDailyFortune() {
        return fortuneService.getFortune();
    }

    @Override
    public String getDailyWorkout() {
        return "Practice your backhand volley";
    }
}

And such main class:

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnotationBeanScopeDemoApp {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");

        Coach theCoach = context.getBean("tennisCoach", Coach.class);

        System.out.println(theCoach.getDailyFortune());
        System.out.println(theCoach.getDailyWorkout());

        context.close();
    }
}

Expected output is:

Inside default constructor

Inside postconstructor

DailyFortune

Practice your backhand volley

Inside predestroyer

But I get this:

Inside default constructor

DailyFortune

Practice your backhand volley

It seems like @PostContruct and @PreDestroy annotations do not work correctly. I cannot find the reason of my problem.


问:
How to install websocket in with pip3?
I got the following error. Does anybody know how to install it correctly? Thanks.</p>

```<code>$ pip3 install websocket
Collecting websocket
  Using cached websocket-0.2.1.tar.gz (195 kB)
Collecting gevent
  Using cached gevent-20.5.2.tar.gz (5.6 MB)
  Installing build dependencies ... error
  ERROR: Command errored out with exit status 1:
   command: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip install --ignore-installed --no-user --prefix /private/tmp/mktemp/pip-build-env-u69lfxee/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools >= 40.8.0' wheel 'Cython >= 3.0a5' 'cffi >= 1.12.3 ; platform_python_implementation == '"'"'CPython'"'"'' 'greenlet>=0.4.14 ; platform_python_implementation == '"'"'CPython'"'"''
       cwd: None
  Complete output (14 lines):
  Traceback (most recent call last):
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
      "__main__", mod_spec)
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
      exec(code, run_globals)
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/__main__.py", line 23, in <module>
      from pip._internal.cli.main import main as _main  # isort:skip # noqa
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/main.py", line 5, in <module>
      import locale
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/locale.py", line 16, in <module>
      import re
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 143, in <module>
      class RegexFlag(enum.IntFlag):
  AttributeError: module 'enum' has no attribute 'IntFlag'
  ----------------------------------------
ERROR: Command errored out with exit status 1: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip install --ignore-installed --no-user --prefix /private/tmp/mktemp/pip-build-env-u69lfxee/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools >= 40.8.0' wheel 'Cython >= 3.0a5' 'cffi >= 1.12.3 ; platform_python_implementation == '"'"'CPython'"'"'' 'greenlet>=0.4.14 ; platform_python_implementation == '"'"'CPython'"'"'' Check the logs for full command output.
</code>```

答:
It's because your enum is not the standard library enum module. You probably have the package enum34 installed.

One way check if this is the case is to inspect the property enum.file

```<code>import enum
print(enum.__file__)
# standard library location should be something like
# /usr/local/lib/python3.6/enum.py
</code>```

Since python 3.6 the enum34 library is no longer compatible with the standard library. The library is also unnecessary, so you can simply uninstall it.

pip uninstall -y enum34
If you need the code to run on python versions both <=3.4 and >3.4, you can try having enum-compat as a requirement. It only installs enum34 for older versions of python without the standard library enum.

Title: How to install websocket in with pip3?

Body:
I got the following error. Does anybody know how to install it correctly? Thanks.

$ pip3 install websocket
Collecting websocket
  Using cached websocket-0.2.1.tar.gz (195 kB)
Collecting gevent
  Using cached gevent-20.5.2.tar.gz (5.6 MB)
  Installing build dependencies ... error
  ERROR: Command errored out with exit status 1:
   command: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip install --ignore-installed --no-user --prefix /private/tmp/mktemp/pip-build-env-u69lfxee/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools >= 40.8.0' wheel 'Cython >= 3.0a5' 'cffi >= 1.12.3 ; platform_python_implementation == '"'"'CPython'"'"'' 'greenlet>=0.4.14 ; platform_python_implementation == '"'"'CPython'"'"''
       cwd: None
  Complete output (14 lines):
  Traceback (most recent call last):
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
      "__main__", mod_spec)
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
      exec(code, run_globals)
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/__main__.py", line 23, in <module>
      from pip._internal.cli.main import main as _main  # isort:skip # noqa
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/main.py", line 5, in <module>
      import locale
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/locale.py", line 16, in <module>
      import re
    File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 143, in <module>
      class RegexFlag(enum.IntFlag):
  AttributeError: module 'enum' has no attribute 'IntFlag'
  ----------------------------------------
ERROR: Command errored out with exit status 1: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip install --ignore-installed --no-user --prefix /private/tmp/mktemp/pip-build-env-u69lfxee/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools >= 40.8.0' wheel 'Cython >= 3.0a5' 'cffi >= 1.12.3 ; platform_python_implementation == '"'"'CPython'"'"'' 'greenlet>=0.4.14 ; platform_python_implementation == '"'"'CPython'"'"'' Check the logs for full command output.

Body:
It's because your enum is not the standard library enum module. You probably have the package enum34 installed.

One way check if this is the case is to inspect the property enum.file

import enum
print(enum.__file__)
# standard library location should be something like
# /usr/local/lib/python3.6/enum.py

Since python 3.6 the enum34 library is no longer compatible with the standard library. The library is also unnecessary, so you can simply uninstall it.

pip uninstall -y enum34
If you need the code to run on python versions both <=3.4 and >3.4, you can try having enum-compat as a requirement. It only installs enum34 for older versions of python without the standard library enum.


问:
Cannot find name 'describe'. Do you need to install type definitions for a test runner?
When using TypeScript in conjunction with Jest, my specs would fail with error messages like:

test/unit/some.spec.ts:1:1 - error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
test/unit/some.spec.ts:2:3 - error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
test/unit/some.spec.ts:3:7 - error TS2304: Cannot find name 'expect'.
test/unit/some.spec.ts:7:1 - error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
```
<p>The types are already installed.</p>
<p>I use:</p>
<pre class="lang-none prettyprint-override"><code>    "@types/jest": "^23.3.12",
    "jest": "^23.6.0",
    "ts-jest": "^23.10.5",
    "typescript": "^3.1.6"
</code>```

I run tests using jest --forceExit --coverage --verbose

答:
I am using Mocha, Chai and chai-http for testing a Node.js Express.js project. I was not using types in compilerOptions earlier, but adding the below setting in file tsconfig.json made it work for me:

```<code>{
  "compilerOptions": {
    // ...rest of my settings
    "types": ["mocha", "chai", "chai-http"]
  }
}
</code>```

Body:
When using TypeScript in conjunction with Jest, my specs would fail with error messages like:

test/unit/some.spec.ts:1:1 - error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
test/unit/some.spec.ts:2:3 - error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
test/unit/some.spec.ts:3:7 - error TS2304: Cannot find name 'expect'.
test/unit/some.spec.ts:7:1 - error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.

The types are already installed.

I use:

    "@types/jest": "^23.3.12",
    "jest": "^23.6.0",
    "ts-jest": "^23.10.5",
    "typescript": "^3.1.6"

I run tests using jest --forceExit --coverage --verbose

Body:
I am using Mocha, Chai and chai-http for testing a Node.js Express.js project. I was not using types in compilerOptions earlier, but adding the below setting in file tsconfig.json made it work for me:

{
  "compilerOptions": {
    // ...rest of my settings
    "types": ["mocha", "chai", "chai-http"]
  }
}


问:
Validate Regex: min/max characters, one hypen and start/finish conditions
I am trying to create a validation function for usernames.  It must be:

Min six characters / Max 16 characters

Only letters, numbers and, at the most, one hyphen

It must start with a letter and no end with a hyphen

I came up with this regular expression:

```<code>^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$
</code>```

Which does everything but the maximum number of characters.  What am I missing?

You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).

This is a simple validation function in Python:

```<code># Username validation
import re

def validate(username):
    regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username
</code>```

Thanks very much for any suggestion.

答:
Please use this website to try out your regex:

https://regex101.com/r/RfD4YR/11

As you can see the first group matches all the expression because + is greedy and takes as many characters as needed. This should work properly:

```<code>^([A-Za-z][A-Za-z0-9-]{4,14}[A-Za-z0-9])$
</code>```

Body:
I am trying to create a validation function for usernames.  It must be:

Min six characters / Max 16 characters

Only letters, numbers and, at the most, one hyphen

It must start with a letter and no end with a hyphen

I came up with this regular expression:

^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$

Which does everything but the maximum number of characters.  What am I missing?

You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).

This is a simple validation function in Python:

# Username validation
import re

def validate(username):
    regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username

Thanks very much for any suggestion.

Body:
Please use this website to try out your regex:

https://regex101.com/r/RfD4YR/11

As you can see the first group matches all the expression because + is greedy and takes as many characters as needed. This should work properly:

^([A-Za-z][A-Za-z0-9-]{4,14}[A-Za-z0-9])$


问:
Open.json file from API
could anyone provide the code to open the content of this file?

url = 'https://datos.madrid.es/egob/catalogo/202625-0-aparcamientos-publicos.json'

I have tried requests.get(url).json() and I just keep getting the following error no mather what I do:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

答:
The server is expecting a User-Agent header. Try:

```<code>import requests

url = 'https://datos.madrid.es/egob/catalogo/202625-0-aparcamientos-publicos.json'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}
response = requests.get(url, headers=headers)
print(response.json())
</code>```

Outputs:

```<code>{'@context': {'c': 'http://www.w3.org/2002/12/cal#', 'dcterms': 'http://purl.org/dc/terms/', 'geo': 'http://www.w3.org/2003/01/geo/wgs84_pos#', 'loc': 'http://purl.org/ctic/infraestructuras/localizacion#', 'org': 'http://purl.org/ctic/infraestructuras/organizacion#', 'vcard': 'http://www.w3.org/2006/vcard/ns#', 'schema': 'https://schema.org/', 'title': 'vcard:fn', 'id': 'dcterms:identifier', 'relation': 'dcterms:relation', 'references': 'dcterms:references', 'address': 'vcard:adr', 'area': 'loc:barrio', 'district': 'loc :distrito', ...
</code>```

To get the @graph object just use normal JSON parsing:

```<code>print(response.json()['@graph'])
</code>```

Or if you want it as a string:

```<code>import json
...
print(json.dumps(response.json()['@graph']))
</code>```

Or iterate over the graphs objects:

```<code>for graph in response.json()['@graph']:
    print(json.dumps(graph))
</code>```

Title: Open.json file from API

Body:
The server is expecting a User-Agent header. Try:

import requests

url = 'https://datos.madrid.es/egob/catalogo/202625-0-aparcamientos-publicos.json'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}
response = requests.get(url, headers=headers)
print(response.json())

Outputs:

{'@context': {'c': 'http://www.w3.org/2002/12/cal#', 'dcterms': 'http://purl.org/dc/terms/', 'geo': 'http://www.w3.org/2003/01/geo/wgs84_pos#', 'loc': 'http://purl.org/ctic/infraestructuras/localizacion#', 'org': 'http://purl.org/ctic/infraestructuras/organizacion#', 'vcard': 'http://www.w3.org/2006/vcard/ns#', 'schema': 'https://schema.org/', 'title': 'vcard:fn', 'id': 'dcterms:identifier', 'relation': 'dcterms:relation', 'references': 'dcterms:references', 'address': 'vcard:adr', 'area': 'loc:barrio', 'district': 'loc :distrito', ...

To get the @graph object just use normal JSON parsing:

print(response.json()['@graph'])

Or if you want it as a string:

import json
...
print(json.dumps(response.json()['@graph']))

Or iterate over the graphs objects:

for graph in response.json()['@graph']:
    print(json.dumps(graph))


问:
How to add element of a list to list of dictionary in python
Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

```<code>fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]
</code>```

list

```<code>rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]
</code>```

Desired output

```<code>[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]
</code>```

I will appreciate any help in getting this done.
Thank you

答:
This is what you need :)</p>

```<code>for fortunne_dict,rpe in zip(fortunne_500,rev_per_emp):
  fortunne_dict['rev per emp'] = rpe
</code>```

Body:
Am trying to add element of a list to a list dictionary, I have tried all my possible best but could not get it done.

list of dict

fortunne_500=[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion'},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion'},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion'}]

list

rev_per_emp = [217391.30434782608,376142.84374767606,911953.2812190612]

Desired output

[{'Rank': 1,
  'Company': 'Walmart',
  'Country': 'United States',
  'Industry': 'Retail',
  'Revenue in USD': '$500 billion',
  'rev per emp': 217391.30434782608},
 {'Rank': 2,
  'Company': 'State Grid',
  'Country': 'China',
  'Industry': 'Power',
  'Revenue in USD': '$349 billion',
  'rev per emp': 376142.84374767606},
 {'Rank': 3,
  'Company': 'Sinopec Group',
  'Country': 'China',
  'Industry': 'Petroleum',
  'Revenue in USD': '$327 billion',
  'rev per emp': 911953.2812190612}]

I will appreciate any help in getting this done.
Thank you

Body:
This is what you need :)

for fortunne_dict,rpe in zip(fortunne_500,rev_per_emp):
  fortunne_dict['rev per emp'] = rpe


问:
arrayWithContentsOfFile can't read plist file
i have a plist with an array that contain 2 strings see image :

http://imageshack.us/photo/my-images/263/myplist.png/

and in my viewDidLoad i add this :

```<code>NSString *file = [[NSBundle  mainBundle] pathForResource:@"Data"    ofType:@"plist"];

NSArray *array = [NSArray    arrayWithContentsOfFile:file];

NSLog(@"array = %@", array);
</code>```

But i got always null why? Thanks for help.

UPDATE : the solution is that you need to manually edit the plist file (Xcode4 use Dictionnary by default)

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <array>
        <string>HO</string>
        <string>HI</string>
    </array>
</array>
</plist>
</code>```

答: in you application you need to change the root  key name as  it can not be datatype

Body:
i have a plist with an array that contain 2 strings see image :

http://imageshack.us/photo/my-images/263/myplist.png/

and in my viewDidLoad i add this :

NSString *file = [[NSBundle  mainBundle] pathForResource:@"Data"    ofType:@"plist"];

NSArray *array = [NSArray    arrayWithContentsOfFile:file];

NSLog(@"array = %@", array);

But i got always null why? Thanks for help.

UPDATE : the solution is that you need to manually edit the plist file (Xcode4 use Dictionnary by default)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <array>
        <string>HO</string>
        <string>HI</string>
    </array>
</array>
</plist>


问:
Redirect page in react class component
how can i redirect the page in react's class component after performing submiting a form (like create a post, login etc...) ?
is there an equivalent to useHistory hook for class based component ?</p>

答:
You can use history prop.

```<code>this.props.history.push('/path to page');
</code>```

If history prop is not available in your component, wrap your component with withRouter

```<code>export default withRouter(MyComponent);
</code>```

Title: Redirect page in react class component

Body:
You can use history prop.

this.props.history.push('/path to page');

If history prop is not available in your component, wrap your component with withRouter

export default withRouter(MyComponent);


问:
How to make Superfish menu horizontal width 100%?
I am using Superfish 1.4.8 as a horizontal menu

The menu is inside of a fixed-width div of 900px

I would like Superfish's width to be 100% (900px), and have each li's width automatically scaled depending on the number of items. The number of items in this menu will change over time.

Basically I want the same behavior of a 100% width TABLE and the auto-sizing behavior of TD's

I found the following CSS additions from an old 2009 post on how to do this:

```<code>.sf-menu { width: 100%; float: left; display: table;}
.sf-menu ul { display: table-row; }
.sf-menu ul li { display: table-cell; min-width: 20%; }
</code>```

It looks like it should work, but it does not, the menu still appears exactly the same

Here it is on jsFiddle:
http://jsfiddle.net/xRcJL/

Has anyone been able to make Superfish scale to 100% of a container?

答:
any element that is floated will ignore the display property so in your code .sfmenu is not displaying as a table (in your fiddle the float is set much later in the code)

.sfmenu is the parent ul so it should be display: table-row; with it's immediate children li items being  display: table-cell; - .sfmenu ul li is selecting the drop down lists not the top level horizontal one

the #container div should probably be the one that is display: table;

See this example

As your code above stands it's only the drop lists that getting these properties which is why the first level isn't stretching, although I don't think the child level lists will need them, it should probably just be the first level. I'm not altogether sure the child menu positioning will work properly even if the above is corrected as "real" table cells don't accept relative positioning, would need some drop levels to test..

Body:
I am using Superfish 1.4.8 as a horizontal menu

The menu is inside of a fixed-width div of 900px

I would like Superfish's width to be 100% (900px), and have each li's width automatically scaled depending on the number of items. The number of items in this menu will change over time.

Basically I want the same behavior of a 100% width TABLE and the auto-sizing behavior of TD's

I found the following CSS additions from an old 2009 post on how to do this:

.sf-menu { width: 100%; float: left; display: table;}
.sf-menu ul { display: table-row; }
.sf-menu ul li { display: table-cell; min-width: 20%; }

It looks like it should work, but it does not, the menu still appears exactly the same

Here it is on jsFiddle:
http://jsfiddle.net/xRcJL/

Has anyone been able to make Superfish scale to 100% of a container?


问:
Multiple bars in one bar plot
I want to 'combine' these plots, in the same bar chart.

Here is the code with which I generated these graphics

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

plt.rcParams['figure.figsize'] = (13,6)

def generate_histogram(distribucion):
    values = list(distribucion.values())
    intensities = list(distribucion.keys())

    # plotting configuration
    figure = plt.figure()
    axes = figure.add_axes([0,0,1,1])
    histogram = axes.bar(intensities,values,width=14)
    plt.xticks(intensities,intensities)

    # title and label
    axes.set_title('Intensity distribution')
    axes.set_xlabel('Intensity (0 to 255)')
    axes.set_ylabel('Probability')

    # fix scale
    plt.ylim(0, 0.55)
    plt.autoscale(False)

    # function that make the labels
    def autolabel(rects):
        """Attach a text label above each bar in *rects*, displaying its height."""
        for rect in rects:
            height = round((float)(rect.get_height()),4)
            axes.annotate('{}'.format(height),
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 3),  # 3 points vertical offset
                        textcoords="offset points",
                        ha='center', va='bottom',fontsize=10)

    # generate autolabels
    autolabel(histogram)

    # show graph
    plt.show()

generate_histogram(distribution_1)
generate_histogram(distribution_2)
generate_histogram(distribution_3)
</code>```

here is the data that I'm using

```<code>distribution_1 = {221: 0.360416255051639, 238: 0.19880422092501124, 204: 0.08321239335428827, 187: 0.05222900763358779, 170: 0.048701841041760216, 153: 0.04666771441400988, 136: 0.04238796587337225, 119: 0.03527929950606197, 255: 0.008626852267624607, 102: 0.029128423888639426, 85: 0.025297709923664122, 68: 0.025161652447238437, 51: 0.02414683430624158, 34: 0.015194881005837449, 17: 0.004271216883700045, 0: 0.00047373147732375395}
distribution_2 = {221: 0.4157265379434216, 238: 0.19262191288729233, 204: 0.07130848675348002, 187: 0.04102649303996408, 170: 0.041006286484059275, 153: 0.04099775482712169, 136: 0.03805253704535249, 119: 0.03213920071845532, 102: 0.0272240682532555, 255: 0.007630893578805568, 85: 0.024198473282442748, 68: 0.024454422990570275, 51: 0.023817691962281097, 34: 0.015106870229007634, 17: 0.004220925011225864, 0: 0.00046744499326448137}
distribution_3 = {255: 0.4824301751234845, 221: 0.0699272563987427, 187: 0.06918679838347552, 170: 0.050990121239335426, 153: 0.04777503367759318, 238: 0.024907049842837897, 136: 0.04586124831612034, 119: 0.041772339470139204, 102: 0.034856757970363715, 85: 0.022533453075886844, 68: 0.03175348001796138, 51: 0.025796587337224966, 34: 0.02501930848675348, 17: 0.015535698248765155, 0: 0.008881903906600808, 204: 0.002772788504714863}
</code>```

I want something like this with the label turn 90 degree so they don't overlap

答:
This function should be outside of the other one so it's not being defined each time.

```<code># function that make the labels
def autolabel(rects,axes):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = round((float)(rect.get_height()),4)
        axes.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom',fontsize=10,rotation=90)
</code>```

Then you have to offset two sets of the x values by the width of the bars:

the first set gets offset -.1 (to the left)

the second set doesn't get offset

the third set gets offset +.1 (to the right)

```<code>def generate_histogram(distribucion,axes=None,figure=None,h_adjustment=None):
    values = list(distribucion.values())
    intensities = list(distribucion.keys())
    width = .1

    # plotting configuration
    if not figure:
        figure = plt.figure(figsize=(13,6))
        axes = figure.add_axes([0,0,1,1])
    histogram = axes.bar([intensity + h_adjustment
                          for intensity in intensities],values,width)
    #plt.xticks(intensities,intensities)

    # title and label
    axes.set_title('Intensity distribution')
    axes.set_xlabel('Intensity (0 to 255)')
    axes.set_ylabel('Probability')

    # fix scale
    plt.ylim(0, 0.55)
    plt.autoscale(False)

    # generate autolabels
    autolabel(histogram,axes)

    return figure, axes
</code>```

Call the function like this:

```<code>a = {8:.5,7:.2,10:.11,6:.3}
figure,axes = generate_histogram(a,h_adjustment=-.1)
b = {10:.35,7:.23,8:.25,6:.4}
figure,axes = generate_histogram(b,figure=figure,axes=axes,h_adjustment=0)
c = {10:.25,8:.44,9:.5,6:.45}
generate_histogram(c,figure=figure,axes=axes,h_adjustment=.1)

plt.show()
</code>```

Result:

Title: Multiple bars in one bar plot

Body:
I want to 'combine' these plots, in the same bar chart.

Here is the code with which I generated these graphics

import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = (13,6)

def generate_histogram(distribucion):
    values = list(distribucion.values())
    intensities = list(distribucion.keys())

    # plotting configuration
    figure = plt.figure()
    axes = figure.add_axes([0,0,1,1])
    histogram = axes.bar(intensities,values,width=14)
    plt.xticks(intensities,intensities)

    # title and label
    axes.set_title('Intensity distribution')
    axes.set_xlabel('Intensity (0 to 255)')
    axes.set_ylabel('Probability')

    # fix scale
    plt.ylim(0, 0.55)
    plt.autoscale(False)

    # function that make the labels
    def autolabel(rects):
        """Attach a text label above each bar in *rects*, displaying its height."""
        for rect in rects:
            height = round((float)(rect.get_height()),4)
            axes.annotate('{}'.format(height),
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 3),  # 3 points vertical offset
                        textcoords="offset points",
                        ha='center', va='bottom',fontsize=10)

    # generate autolabels
    autolabel(histogram)

    # show graph
    plt.show()

generate_histogram(distribution_1)
generate_histogram(distribution_2)
generate_histogram(distribution_3)

here is the data that I'm using

distribution_1 = {221: 0.360416255051639, 238: 0.19880422092501124, 204: 0.08321239335428827, 187: 0.05222900763358779, 170: 0.048701841041760216, 153: 0.04666771441400988, 136: 0.04238796587337225, 119: 0.03527929950606197, 255: 0.008626852267624607, 102: 0.029128423888639426, 85: 0.025297709923664122, 68: 0.025161652447238437, 51: 0.02414683430624158, 34: 0.015194881005837449, 17: 0.004271216883700045, 0: 0.00047373147732375395}
distribution_2 = {221: 0.4157265379434216, 238: 0.19262191288729233, 204: 0.07130848675348002, 187: 0.04102649303996408, 170: 0.041006286484059275, 153: 0.04099775482712169, 136: 0.03805253704535249, 119: 0.03213920071845532, 102: 0.0272240682532555, 255: 0.007630893578805568, 85: 0.024198473282442748, 68: 0.024454422990570275, 51: 0.023817691962281097, 34: 0.015106870229007634, 17: 0.004220925011225864, 0: 0.00046744499326448137}
distribution_3 = {255: 0.4824301751234845, 221: 0.0699272563987427, 187: 0.06918679838347552, 170: 0.050990121239335426, 153: 0.04777503367759318, 238: 0.024907049842837897, 136: 0.04586124831612034, 119: 0.041772339470139204, 102: 0.034856757970363715, 85: 0.022533453075886844, 68: 0.03175348001796138, 51: 0.025796587337224966, 34: 0.02501930848675348, 17: 0.015535698248765155, 0: 0.008881903906600808, 204: 0.002772788504714863}

I want something like this with the label turn 90 degree so they don't overlap

Body:
This function should be outside of the other one so it's not being defined each time.

# function that make the labels
def autolabel(rects,axes):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = round((float)(rect.get_height()),4)
        axes.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom',fontsize=10,rotation=90)

Then you have to offset two sets of the x values by the width of the bars:

the first set gets offset -.1 (to the left)

the second set doesn't get offset

the third set gets offset +.1 (to the right)

def generate_histogram(distribucion,axes=None,figure=None,h_adjustment=None):
    values = list(distribucion.values())
    intensities = list(distribucion.keys())
    width = .1

    # plotting configuration
    if not figure:
        figure = plt.figure(figsize=(13,6))
        axes = figure.add_axes([0,0,1,1])
    histogram = axes.bar([intensity + h_adjustment
                          for intensity in intensities],values,width)
    #plt.xticks(intensities,intensities)

    # title and label
    axes.set_title('Intensity distribution')
    axes.set_xlabel('Intensity (0 to 255)')
    axes.set_ylabel('Probability')

    # fix scale
    plt.ylim(0, 0.55)
    plt.autoscale(False)

    # generate autolabels
    autolabel(histogram,axes)

    return figure, axes

Call the function like this:

a = {8:.5,7:.2,10:.11,6:.3}
figure,axes = generate_histogram(a,h_adjustment=-.1)
b = {10:.35,7:.23,8:.25,6:.4}
figure,axes = generate_histogram(b,figure=figure,axes=axes,h_adjustment=0)
c = {10:.25,8:.44,9:.5,6:.45}
generate_histogram(c,figure=figure,axes=axes,h_adjustment=.1)

plt.show()

Result:


问:
unable to read kafka topic data using spark
I have data like below in one of the topics which I created named "sampleTopic"

```<code>sid,Believer
</code>```

Where the first argument is the username and the second argument is the song name which the user frequently listens. Now, I have started zookeeper, Kafka server, and producer with the topic name as mentioned above. I have entered the above data for that topic using CMD. Now, I want to read the topic in spark perform some aggregation, and write it back to stream. Below is my code:

```<code>package com.sparkKafka
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
object SparkKafkaTopic {
  def main(args: Array[String]) {
    val spark = SparkSession.builder().appName("SparkKafka").master("local[*]").getOrCreate()
    println("hey")
    val df = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "localhost:9092")
      .option("subscribe", "sampleTopic1")
      .load()
    val query = df.writeStream
      .outputMode("append")
      .format("console")
      .start().awaitTermination()

  }
}
</code>```

However, when I execute the above code it gives :

```<code>    +----+--------------------+------------+---------+------+--------------------+-------------+
| key|               value|       topic|partition|offset|           timestamp|timestampType|
+----+--------------------+------------+---------+------+--------------------+-------------+
|null|[73 69 64 64 68 6...|sampleTopic1|        0|     4|2020-05-31 12:12:...|            0|
+----+--------------------+------------+---------+------+--------------------+-------------+
</code>```

with infinite below looping messages too

```<code>20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
</code>```

I need output something like below:

As modified on the suggestion by Srinivas I got the following output:

Not sure what exactly is wrong over here. Please guide me through it.

答:
Try to add spark-sql-kafka library to your build file. Check below.

build.sbt

libraryDependencies += "org.apache.spark" %% "spark-sql-kafka-0-10" % "2.3.0"
// Change to Your spark version
```

<p><strong>pom.xml</strong></p>

<pre class="lang-xml prettyprint-override"><code><dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql-kafka-0-10_2.11</artifactId>
    <version>2.3.0</version>    // Change to Your spark version
</dependency>

</code>```

Change your code like below

    package com.sparkKafka
    import org.apache.spark.SparkContext
    import org.apache.spark.SparkConf
    import org.apache.spark.sql.SparkSession
    import org.apache.spark.sql.types._
    import org.apache.spark.sql.functions._
    case class KafkaMessage(key: String, value: String, topic: String, partition: Int, offset: Long, timestamp: String)

    object SparkKafkaTopic {

      def main(args: Array[String]) {
        //val spark = SparkSession.builder().appName("SparkKafka").master("local[*]").getOrCreate()
        println("hey")
        val spark = SparkSession.builder().appName("SparkKafka").master("local[*]").getOrCreate()
        import spark.implicits._
        val mySchema = StructType(Array(
          StructField("userName", StringType),
          StructField("songName", StringType)))
        val df = spark
          .readStream
          .format("kafka")
          .option("kafka.bootstrap.servers", "localhost:9092")
          .option("subscribe", "sampleTopic1")
          .load()

        val query = df
          .as[KafkaMessage]
          .select(split($"value", ",")(0).as("userName"),split($"value", ",")(1).as("songName"))
          .writeStream
          .outputMode("append")
          .format("console")
          .start()
          .awaitTermination()
      }
    }

     /*
        +------+--------+
        |userid|songname|
        +------+--------+
        |   sid|Believer|
        +------+--------+
       */

      }
    }
```

Body:
I have data like below in one of the topics which I created named "sampleTopic"

sid,Believer

Where the first argument is the username and the second argument is the song name which the user frequently listens. Now, I have started zookeeper, Kafka server, and producer with the topic name as mentioned above. I have entered the above data for that topic using CMD. Now, I want to read the topic in spark perform some aggregation, and write it back to stream. Below is my code:

package com.sparkKafka
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
object SparkKafkaTopic {
  def main(args: Array[String]) {
    val spark = SparkSession.builder().appName("SparkKafka").master("local[*]").getOrCreate()
    println("hey")
    val df = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "localhost:9092")
      .option("subscribe", "sampleTopic1")
      .load()
    val query = df.writeStream
      .outputMode("append")
      .format("console")
      .start().awaitTermination()

  }
}

However, when I execute the above code it gives :

    +----+--------------------+------------+---------+------+--------------------+-------------+
| key|               value|       topic|partition|offset|           timestamp|timestampType|
+----+--------------------+------------+---------+------+--------------------+-------------+
|null|[73 69 64 64 68 6...|sampleTopic1|        0|     4|2020-05-31 12:12:...|            0|
+----+--------------------+------------+---------+------+--------------------+-------------+

with infinite below looping messages too

20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.
20/05/31 11:56:12 INFO Fetcher: [Consumer clientId=consumer-1, groupId=spark-kafka-source-0d6807b9-fcc9-4847-abeb-f0b81ab25187--264582860-driver-0] Resetting offset for partition sampleTopic1-0 to offset 4.

I need output something like below:

As modified on the suggestion by Srinivas I got the following output:

Not sure what exactly is wrong over here. Please guide me through it.

Body:
Try to add spark-sql-kafka library to your build file. Check below.

build.sbt

libraryDependencies += "org.apache.spark" %% "spark-sql-kafka-0-10" % "2.3.0"
// Change to Your spark version

pom.xml

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql-kafka-0-10_2.11</artifactId>
    <version>2.3.0</version>    // Change to Your spark version
</dependency>

Change your code like below

    package com.sparkKafka
    import org.apache.spark.SparkContext
    import org.apache.spark.SparkConf
    import org.apache.spark.sql.SparkSession
    import org.apache.spark.sql.types._
    import org.apache.spark.sql.functions._
    case class KafkaMessage(key: String, value: String, topic: String, partition: Int, offset: Long, timestamp: String)

    object SparkKafkaTopic {

      def main(args: Array[String]) {
        //val spark = SparkSession.builder().appName("SparkKafka").master("local[*]").getOrCreate()
        println("hey")
        val spark = SparkSession.builder().appName("SparkKafka").master("local[*]").getOrCreate()
        import spark.implicits._
        val mySchema = StructType(Array(
          StructField("userName", StringType),
          StructField("songName", StringType)))
        val df = spark
          .readStream
          .format("kafka")
          .option("kafka.bootstrap.servers", "localhost:9092")
          .option("subscribe", "sampleTopic1")
          .load()

        val query = df
          .as[KafkaMessage]
          .select(split($"value", ",")(0).as("userName"),split($"value", ",")(1).as("songName"))
          .writeStream
          .outputMode("append")
          .format("console")
          .start()
          .awaitTermination()
      }
    }

     /*
        +------+--------+
        |userid|songname|
        +------+--------+
        |   sid|Believer|
        +------+--------+
       */

      }
    }


问:
UIImageView circular shape swift
I used this code to make UIImageView in a custom UITableViewCell, but the circular shape isn't updated until i pressed on the table cell, I tried the code in both awakeFromNib() and  layoutSubviews() </p>

```<code>  userImage.layer.cornerRadius = userImage.frame.size.width / 2
  userImage.layer.masksToBounds = true
  userImage.layer.borderColor = UIColor.black.cgColor
  userImage.layer.borderWidth = 1
</code>```

答:
You simply have to override the layoutSubviews() method of your UITableViewCell subclass, as it will be called on drawing updates.

Then just set your UIImageView's cornerRadius as you like:

```<code>class MyCustomTableViewCell: UITableViewCell {

    private let circularImageView: UIImageView = {
        $0.contentMode = .scaleAspectFill
        $0.layer.masksToBounds = true
        $0.layer.borderColor = UIColor.black.cgColor
        $0.layer.borderWidth = 1
        return $0
    }(UIImageView())

    // ...

    override func layoutSubviews() {
        super.layoutSubviews()
        circularImageView.layer.cornerRadius = circularImageView.frame.size.width/2
    }
}
</code>```

Title: UIImageView circular shape swift

Body:
I used this code to make UIImageView in a custom UITableViewCell, but the circular shape isn't updated until i pressed on the table cell, I tried the code in both awakeFromNib() and  layoutSubviews()

  userImage.layer.cornerRadius = userImage.frame.size.width / 2
  userImage.layer.masksToBounds = true
  userImage.layer.borderColor = UIColor.black.cgColor
  userImage.layer.borderWidth = 1

Body:
You simply have to override the layoutSubviews() method of your UITableViewCell subclass, as it will be called on drawing updates.

Then just set your UIImageView's cornerRadius as you like:

class MyCustomTableViewCell: UITableViewCell {

    private let circularImageView: UIImageView = {
        $0.contentMode = .scaleAspectFill
        $0.layer.masksToBounds = true
        $0.layer.borderColor = UIColor.black.cgColor
        $0.layer.borderWidth = 1
        return $0
    }(UIImageView())

    // ...

    override func layoutSubviews() {
        super.layoutSubviews()
        circularImageView.layer.cornerRadius = circularImageView.frame.size.width/2
    }
}


问:
Can't get correct peer ip address when accepting TCP socket connection on localhost in Python
I am working on a P2P network application code for file transmission. Each peer has a listening socket on which it can accept incoming connections.

"Server" part of code:

```<code>listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listening_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

try:
    listening_socket.bind((self.address, self.listening_port))
    break
except SocketError:
    return

listening_socket.listen(5)
listening_socket.setblocking(0)
self.listening_socket = listening_socket

####

new_connection, address = self.listening_socket.accept()
new_connection.setblocking(0)
print 'Accepted new connection from %s' % (peer_address)
</code>```

"Client" part of code:

```<code>try:
    sock = socket.create_connection((peer_address, peer_port), timeout=5)
except socket.error:
    return False
print 'Connected to %s' % (peer_address)

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(0)
</code>```

If I bind the first peer (server) to '127.0.0.1' and the second one (client) to '127.0.0.2' (or any other address from loopback subnet) and connect to '127.0.0.1', accept() returns address as '127.0.0.1', instead of '127.0.0.2'. How can I display the correct incoming ip address when accepting the connection?

getpeername() also returns '127.0.0.1'.

On local wifi network, it displays the correct incoming ip address.
I mention that the connection itself works well, I just need to display the correct address and not '127.0.0.1'.

Testing on an Unix machine.

I would appreciate any help.

答:
Unless a TCP client is explicitly bound to a local IP address it might use any of the local IP addresses on the interface which provides a route to the target IP. Usually systems have an implicit internal order and the first IP address is used if multiple are available.

In your case you only connect to the target IP 127.0.0.2. This IP address is reachable from both 127.0.0.1 and 127.0.0.2 with the same costs. 127.0.0.1 is likely the first IP address on the loopback interface so this is used as the source IP. If you want to have it different you need to explicitly bind the connecting socket. It does not matter what happens on your listening socket - binding is per socket and not per application.

Binding a client socket is similar to binding a server socket:

```<code>s = socket.socket()
s.bind(('127.0.0.2',0))
s.connect(('127.0.0.2', peer_port))
</code>```

Body:
I am working on a P2P network application code for file transmission. Each peer has a listening socket on which it can accept incoming connections.

"Server" part of code:

listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listening_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

try:
    listening_socket.bind((self.address, self.listening_port))
    break
except SocketError:
    return

listening_socket.listen(5)
listening_socket.setblocking(0)
self.listening_socket = listening_socket

####

new_connection, address = self.listening_socket.accept()
new_connection.setblocking(0)
print 'Accepted new connection from %s' % (peer_address)

"Client" part of code:

try:
    sock = socket.create_connection((peer_address, peer_port), timeout=5)
except socket.error:
    return False
print 'Connected to %s' % (peer_address)

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(0)

If I bind the first peer (server) to '127.0.0.1' and the second one (client) to '127.0.0.2' (or any other address from loopback subnet) and connect to '127.0.0.1', accept() returns address as '127.0.0.1', instead of '127.0.0.2'. How can I display the correct incoming ip address when accepting the connection?

getpeername() also returns '127.0.0.1'.

On local wifi network, it displays the correct incoming ip address.
I mention that the connection itself works well, I just need to display the correct address and not '127.0.0.1'.

Testing on an Unix machine.

I would appreciate any help.

Body:
Unless a TCP client is explicitly bound to a local IP address it might use any of the local IP addresses on the interface which provides a route to the target IP. Usually systems have an implicit internal order and the first IP address is used if multiple are available.

In your case you only connect to the target IP 127.0.0.2. This IP address is reachable from both 127.0.0.1 and 127.0.0.2 with the same costs. 127.0.0.1 is likely the first IP address on the loopback interface so this is used as the source IP. If you want to have it different you need to explicitly bind the connecting socket. It does not matter what happens on your listening socket - binding is per socket and not per application.

Binding a client socket is similar to binding a server socket:

s = socket.socket()
s.bind(('127.0.0.2',0))
s.connect(('127.0.0.2', peer_port))


问:
How do I convert a PIL Image into a NumPy array?
How do I convert a PIL Image back and forth to a NumPy array so that I can do faster pixel-wise transformations than PIL's PixelAccess allows? I can convert it to a NumPy array via:

```<code>pic = Image.open("foo.jpg")
pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)
</code>```

But how do I load it back into the PIL Image after I've modified the array? pic.putdata() isn't working well.

答:
Convert Numpy to PIL image  and PIL to Numpy

```<code>import numpy as np
from PIL import Image

def pilToNumpy(img):
    return np.array(img)

def NumpyToPil(img):
    return Image.fromarray(img)
</code>```

OwnerDisplayName: akdom

Body:
How do I convert a PIL Image back and forth to a NumPy array so that I can do faster pixel-wise transformations than PIL's PixelAccess allows? I can convert it to a NumPy array via:

pic = Image.open("foo.jpg")
pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)

But how do I load it back into the PIL Image after I've modified the array? pic.putdata() isn't working well.

Body:
Convert Numpy to PIL image  and PIL to Numpy

import numpy as np
from PIL import Image

def pilToNumpy(img):
    return np.array(img)

def NumpyToPil(img):
    return Image.fromarray(img)


问:
wget ERROR: The certificate of ‘xyz’ is not trusted, has expired
I have a Debian 10 buster server, one of several identical hardware/software configs.  I use a script that deploys them, they are all identical.  However, one of them is throwing an error when using wget:

```<code># wget https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.6.15.tar.xz
--2020-05-30 12:49:20--  https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.6.15.tar.xz
Resolving mirrors.edge.kernel.org (mirrors.edge.kernel.org)... 147.75.69.165, 2604:1380:1000:8100::1
Connecting to mirrors.edge.kernel.org (mirrors.edge.kernel.org)|147.75.69.165|:443... connected.
ERROR: The certificate of ‘mirrors.edge.kernel.org’ is not trusted.
ERROR: The certificate of ‘mirrors.edge.kernel.org’ has expired.
</code>```

Things I've done:

Checked that the SSL certificate is valid

Confirmed the exact same command works on other servers

Checked the system date, confirmed correct

Checked resolv.conf, configuring for 8.8.8.8 8.8.4.4 identical to others

Checked name resolution manually, working fine

Reinstall apt-get install --reinstall ca-certificates

Ran update-ca-certificates --fresh

Ran c_rehash

Used curl, it works fine without errors, shows correct SSL expiration

The problem seems to only be wget from what I can tell.  I don't need a workaround.  I need a solution so I have confidence this server is operating as it should.

答:
I was able to solve my own problem using --no-dns-cache

```<code># wget --no-dns-cache --debug https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.6.15.tar.xz
</code>```

After this, it apparently updated whatever file was broken.  It now works without the --no-dns-cache as well.  So strange, but it seems stable.

Body:
I have a Debian 10 buster server, one of several identical hardware/software configs.  I use a script that deploys them, they are all identical.  However, one of them is throwing an error when using wget:

# wget https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.6.15.tar.xz
--2020-05-30 12:49:20--  https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.6.15.tar.xz
Resolving mirrors.edge.kernel.org (mirrors.edge.kernel.org)... 147.75.69.165, 2604:1380:1000:8100::1
Connecting to mirrors.edge.kernel.org (mirrors.edge.kernel.org)|147.75.69.165|:443... connected.
ERROR: The certificate of ‘mirrors.edge.kernel.org’ is not trusted.
ERROR: The certificate of ‘mirrors.edge.kernel.org’ has expired.

Things I've done:

Checked that the SSL certificate is valid

Confirmed the exact same command works on other servers

Checked the system date, confirmed correct

Checked resolv.conf, configuring for 8.8.8.8 8.8.4.4 identical to others

Checked name resolution manually, working fine

Reinstall apt-get install --reinstall ca-certificates

Ran update-ca-certificates --fresh

Ran c_rehash

Used curl, it works fine without errors, shows correct SSL expiration

The problem seems to only be wget from what I can tell.  I don't need a workaround.  I need a solution so I have confidence this server is operating as it should.

Body:
I was able to solve my own problem using --no-dns-cache

# wget --no-dns-cache --debug https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.6.15.tar.xz

After this, it apparently updated whatever file was broken.  It now works without the --no-dns-cache as well.  So strange, but it seems stable.


问:
No execution for functions with scanf
```<code>void reg() {
    char name[60];
    char city[1000];
    puts("Name");
    scanf("%s", name);
    puts("City?");
    scanf("%s", city);
    FILE *fptr = fopen("./src/details.txt", "a");
    fputs(strncat(strncat(name, " ", 61), city, 1061), fptr);
    fclose(fptr);
}
</code>```

<p>When I call this function (present in another file) from main, it doesn't execute (program runs without any output). In fact, any function with scanf in my file doesn't execute. However, functions without scanf work fine. Could anyone tell me what's wrong? </p>

答:
Try substituting scanf() with fgets() to read strings.

```<code>fgets(name, 60, stdin);

</code>```

Also your error with scanf() most probably seems to be caused by a trailing whitespace that is left unconsumed.
Add:

```<code>scanf(" %*c");
</code>```

Or add a call to getchar() before calling scanf()

Title: No execution for functions with scanf

Body:
void reg() {
    char name[60];
    char city[1000];
    puts("Name");
    scanf("%s", name);
    puts("City?");
    scanf("%s", city);
    FILE *fptr = fopen("./src/details.txt", "a");
    fputs(strncat(strncat(name, " ", 61), city, 1061), fptr);
    fclose(fptr);
}

When I call this function (present in another file) from main, it doesn't execute (program runs without any output). In fact, any function with scanf in my file doesn't execute. However, functions without scanf work fine. Could anyone tell me what's wrong?

Body:
Try substituting scanf() with fgets() to read strings.

fgets(name, 60, stdin);

Also your error with scanf() most probably seems to be caused by a trailing whitespace that is left unconsumed.
Add:

scanf(" %*c");

Or add a call to getchar() before calling scanf()


问:
WordPress Editor not updating files: Unable to communicate back with site to check for fatal errors
I've run into an issue with updating the header.php file in a WordPress website.

Firstly, I tried updating the file manually through C-Panel -> File Manager. The code appears to stay in the file, but when you view the page source in incognito mode and different web browsers the code doesn't render.

It's not a server problem, I already contacted the server support team and there aren't any error logs being reported by MySQL.

There doesn't appear to be many solutions for this from what I can find from doing some searches on Google.

Full Error

Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.

答:
In my case, I used a wordpress installation behind cloudflare. My website protocole was HTTPS as I used the cloudflare certificate. However, on the server side, it was a self-signed certificate.

I have installed a let's encrypt certificate in place of the self-signed certificate and then it worked. Afterwards, I could save PHP files in the wordpress file editor.

After installing a wordpress plugin named health check, I saw that the error was "curl self signed certficate".


问:
Multilevel package - Java
I am just a newbie in java And i am using packages for the first time.
I am trying to make packages in this hierarchy:

/chess/game/Pieces.class

/chess/Board.class imports Pieces

/Game.java imports Board

I compiled using just javac filename.java to get the class files.

Game.java doesn't use any of the methods and variables of the Pieces.class just to be sure.
All the Classes,Functions  and Variables are public.
I tested the board.java with a main and it works perfectly fine.But when i use it as a package it doesn't work and i get class not found.

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: game/Pieces
        at chess.Board.initializeboard(Board.java:31)
        at Game.main(Game.java:14)
Caused by: java.lang.ClassNotFoundException: game.Pieces
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        at chess.Board.initializeboard(Board.java:31)
        at Game.main(Game.java:14)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:415)
        at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:192)
        at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:132)
</code>```

I cannot import both the classes in Game.java cause i made a // package game; in Pieces.class
so i cannot import it as // import chess.game.Pieces; in Game.java .

If this is illegal.Is there some other OOP approach?

EDIT-
The code i used-
Pieces.java -(compiled it to .class file)

```<code>package game;

import javax.swing.JButton;

public class  Pieces{
public enum Type {ROOKE,KNIGHT,BISHOP,KING,QUEEN,PAWN};

public boolean alive = true;
public boolean white = false;
public boolean firstmove = false;
public int mx;
public int my;
public Type types;

public JButton button=new JButton();
public void setButton(JButton b){
                        this.button=b;}

}
</code>```

Board.java - (compiled it to .class file)

```<code>package chess;

import game.*;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;

public class Board{

public void initializeboard(JButton [][] spots){
JFrame f = new JFrame("CHESS");
f.setVisible(true);
f.setSize(800,800);

GridLayout layout =new GridLayout(8,8,1,1);
f.setLayout(layout);

for(int ver=0;ver<8;ver++){
  for(int hor=0;hor<8;hor++){
      JButton button = new JButton();
      if((ver+hor)%2==0){
                    button.setBackground(Color.WHITE); }
      else{
           button.setBackground(new Color(255,205,51)); }
 Pieces p =new Pieces();
 spots[ver][hor] = button;
 p.setButton(button);
 f.add(button);
 } //close for loop
 } // close for loop
 f.revalidate();
 } //  close initializeboard
 }// close board
</code>```

Game.java -

```<code>import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;

import chess.Board;
public class Game{
public static void main(String [] args){

JButton [][] spots =new  JButton [8][8];

Board b =new Board();
b.initializeboard(spots);
}
}
</code>```

答:
Go to directory containing file Game.java

Enter this command

javac chess/game/Pieces.java

After that, enter this command

javac -cp . game/Board.java

After that, enter this command

javac -cp . Game.java

Title: Multilevel package - Java

Body:
I am just a newbie in java And i am using packages for the first time.
I am trying to make packages in this hierarchy:

/chess/game/Pieces.class

/chess/Board.class imports Pieces

/Game.java imports Board

I compiled using just javac filename.java to get the class files.

Game.java doesn't use any of the methods and variables of the Pieces.class just to be sure.
All the Classes,Functions  and Variables are public.
I tested the board.java with a main and it works perfectly fine.But when i use it as a package it doesn't work and i get class not found.

Exception in thread "main" java.lang.NoClassDefFoundError: game/Pieces
        at chess.Board.initializeboard(Board.java:31)
        at Game.main(Game.java:14)
Caused by: java.lang.ClassNotFoundException: game.Pieces
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        at chess.Board.initializeboard(Board.java:31)
        at Game.main(Game.java:14)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:415)
        at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:192)
        at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:132)

I cannot import both the classes in Game.java cause i made a // package game; in Pieces.class
so i cannot import it as // import chess.game.Pieces; in Game.java .

If this is illegal.Is there some other OOP approach?

EDIT-
The code i used-
Pieces.java -(compiled it to .class file)

package game;

import javax.swing.JButton;

public class  Pieces{
public enum Type {ROOKE,KNIGHT,BISHOP,KING,QUEEN,PAWN};

public boolean alive = true;
public boolean white = false;
public boolean firstmove = false;
public int mx;
public int my;
public Type types;

public JButton button=new JButton();
public void setButton(JButton b){
                        this.button=b;}

}

Board.java - (compiled it to .class file)

package chess;

import game.*;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;

public class Board{

public void initializeboard(JButton [][] spots){
JFrame f = new JFrame("CHESS");
f.setVisible(true);
f.setSize(800,800);

GridLayout layout =new GridLayout(8,8,1,1);
f.setLayout(layout);

for(int ver=0;ver<8;ver++){
  for(int hor=0;hor<8;hor++){
      JButton button = new JButton();
      if((ver+hor)%2==0){
                    button.setBackground(Color.WHITE); }
      else{
           button.setBackground(new Color(255,205,51)); }
 Pieces p =new Pieces();
 spots[ver][hor] = button;
 p.setButton(button);
 f.add(button);
 } //close for loop
 } // close for loop
 f.revalidate();
 } //  close initializeboard
 }// close board

Game.java -

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;

import chess.Board;
public class Game{
public static void main(String [] args){

JButton [][] spots =new  JButton [8][8];

Board b =new Board();
b.initializeboard(spots);
}
}


问:
How to make function work after another (which contains ajax request)
I have 2 finctions: first load svg on page, second change color of certain <path> in some svg.

This functions looks like:

get_svg_part(category,position,part_name); -- contains ajax

svg_part_color(category,position,color,parameter); -- need execute it after get_svg_part()

I have cases when i neen just load svg and not change color, in another cases i need load svg and change color of couple  in it. That's why i not used success or complite in ajax. Also i need do it on page loading so i put all (2 functions and call) before jQuery(document).ready() (if this information is necessary).

I tried to do it by $.when and .then but this has no effect:

```<code>$.when(get_svg_part('accent','bottom',' U+1F60A')).then(svg_part_color('accent','bottom','#FF7892',0));
</code>```

Maybe i need make svg_part_color(); in some sense asynchronous too? If so, then how?

Question: How to make function work after another (which contains ajax request)?

Cool if this will work like:

get_svg_part('accent','bottom',' U+1F60A');
svg_part_color('accent','bottom','#FF7892',0);

$.when(get_svg_part()).then(svg_part_color()); // just set a rule and not execute function here

// or maybe put this rule in svg_part_color() function```
</div>
</div>
</p>

<hr>

<p><strong>Update:</strong> get_svg_part code:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function get_svg_part(cathegory,position,part_name){
   $.ajax({
      url: "img/icons/parts/"+cathegory+"/"+position+"/"+part_name+".svg",
      type: 'GET',
      dataType: 'html',
      success: function( data ){
       let rate_block_rated = movie_block.find('.movie_rating.rated'); //rate_block_rated
       let svg_symbol = rate_block_rated.find(".composite_rate svg ."+cathegory+"."+position);
       // prepend (insert) data to svg_symbol (accent bottom),
       // then find inserted svg, and delete svg tag (unwrap path)
       svg_symbol.prepend(data).find('svg').children().unwrap();

      }
    });
};</code>```

答:
So long as your first function returns a promise related to the ajax then you can do something like the following:

```<code>function get_svg_part(a, b, c){

    // return the jQuery `$.ajax()`, `$.post()`, `$.getJSON()`
    // or whatever method you are using
    return $.ajax({/* options */})

}
</code>```

Usage:

```<code>get_svg_part().then(function() {
   svg_part_color('accent','bottom','#FF7892',0);
})
</code>```

Body:
I have 2 finctions: first load svg on page, second change color of certain <path> in some svg.

This functions looks like:

get_svg_part(category,position,part_name); -- contains ajax

svg_part_color(category,position,color,parameter); -- need execute it after get_svg_part()

I have cases when i neen just load svg and not change color, in another cases i need load svg and change color of couple  in it. That's why i not used success or complite in ajax. Also i need do it on page loading so i put all (2 functions and call) before jQuery(document).ready() (if this information is necessary).

I tried to do it by $.when and .then but this has no effect:

$.when(get_svg_part('accent','bottom',' U+1F60A')).then(svg_part_color('accent','bottom','#FF7892',0));

Maybe i need make svg_part_color(); in some sense asynchronous too? If so, then how?

Question: How to make function work after another (which contains ajax request)?

Cool if this will work like:

get_svg_part('accent','bottom',' U+1F60A');
svg_part_color('accent','bottom','#FF7892',0);

$.when(get_svg_part()).then(svg_part_color()); // just set a rule and not execute function here

// or maybe put this rule in svg_part_color() function

Update: get_svg_part code:

function get_svg_part(cathegory,position,part_name){
   $.ajax({
      url: "img/icons/parts/"+cathegory+"/"+position+"/"+part_name+".svg",
      type: 'GET',
      dataType: 'html',
      success: function( data ){
       let rate_block_rated = movie_block.find('.movie_rating.rated'); //rate_block_rated
       let svg_symbol = rate_block_rated.find(".composite_rate svg ."+cathegory+"."+position);
       // prepend (insert) data to svg_symbol (accent bottom),
       // then find inserted svg, and delete svg tag (unwrap path)
       svg_symbol.prepend(data).find('svg').children().unwrap();

      }
    });
};

Body:
So long as your first function returns a promise related to the ajax then you can do something like the following:

function get_svg_part(a, b, c){

    // return the jQuery `$.ajax()`, `$.post()`, `$.getJSON()`
    // or whatever method you are using
    return $.ajax({/* options */})

}

Usage:

get_svg_part().then(function() {
   svg_part_color('accent','bottom','#FF7892',0);
})


问:
kubernetes nodeport external ip not accessible
I have been trying to deploy the Spring Boot application on kubernetes cluseter. But somehow I can not access the rest end point from outside the cluster.

Here are the steps which i performed

Setup the kubernetes cluster using kubespray following the guide - Kubernetes Cluster setup using Kubespray

Pushed the spring boot docker image to docker hub

Created kubernetes deployment

```<code>vagrant@node1:~/spring-boot$ kubectl create deployment demo --image=rahulwagh17/kubernetes:jhooq-k8s-springboot
</code>```

```<code>deployment.apps/demo created
</code>```

Exposed the deployment with external IP = 1.1.1.1

```<code>kubectl expose deployment demo --type=LoadBalancer --name=demo-service --external-ip=1.1.1.1 --port=8080

service/demo-service exposed
</code>```

This is how my deployment is looking

```<code>vagrant@node1:~/spring-boot$ kubectl get deployment
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
demo   1/1     1            1           24s
</code>```

This is how my services are looking

```<code>vagrant@node1:~/spring-boot$ kubectl get service
NAME           TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
demo-service   LoadBalancer   10.233.31.159   1.1.1.1       8080:30099/TCP   13s
kubernetes     ClusterIP      10.233.0.1      <none>        443/TCP          23h
</code>```

I can curl the rest end point within the cluster without a problem

```<code>vagrant@node1:~/spring-boot$ curl 10.233.31.159:8080/hello
Hello - Jhooq-k8s
</code>```

Problem I am facing - When i am trying to curl the rest point from outside the cluster, i can not do

```<code>$ curl http://1.1.1.1:30099/hello
curl: (7) Failed to connect to 1.1.1.1 port 30099: Operation timed out
</code>```

I am little new to kubernetes, so any leads or suggestions are highly appreciated

答:
Please try via below approach:
 Via Node Port:- Which means NodeIP:NodePort and in this case, please get any node-ip and then run a command

```<code>curl http://$NODE_IP:30099/hello
</code>```

and you should be able to access your service.

Body:
I have been trying to deploy the Spring Boot application on kubernetes cluseter. But somehow I can not access the rest end point from outside the cluster.

Here are the steps which i performed

Setup the kubernetes cluster using kubespray following the guide - Kubernetes Cluster setup using Kubespray

Pushed the spring boot docker image to docker hub

Created kubernetes deployment

vagrant@node1:~/spring-boot$ kubectl create deployment demo --image=rahulwagh17/kubernetes:jhooq-k8s-springboot

deployment.apps/demo created

Exposed the deployment with external IP = 1.1.1.1

kubectl expose deployment demo --type=LoadBalancer --name=demo-service --external-ip=1.1.1.1 --port=8080

service/demo-service exposed

This is how my deployment is looking

vagrant@node1:~/spring-boot$ kubectl get deployment
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
demo   1/1     1            1           24s

This is how my services are looking

vagrant@node1:~/spring-boot$ kubectl get service
NAME           TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
demo-service   LoadBalancer   10.233.31.159   1.1.1.1       8080:30099/TCP   13s
kubernetes     ClusterIP      10.233.0.1      <none>        443/TCP          23h

I can curl the rest end point within the cluster without a problem

vagrant@node1:~/spring-boot$ curl 10.233.31.159:8080/hello
Hello - Jhooq-k8s

Problem I am facing - When i am trying to curl the rest point from outside the cluster, i can not do

$ curl http://1.1.1.1:30099/hello
curl: (7) Failed to connect to 1.1.1.1 port 30099: Operation timed out

I am little new to kubernetes, so any leads or suggestions are highly appreciated

Body:
Please try via below approach:
 Via Node Port:- Which means NodeIP:NodePort and in this case, please get any node-ip and then run a command

curl http://$NODE_IP:30099/hello

and you should be able to access your service.