问:
Create a new database with MySQL Workbench
Being new to MySQL, I have installed the latest version of the MySQL Workbench (5.2.33). I would like to know how you can create a database with this application. In the Overview tab of the SQL editor there are few "MySQL Schema" displayed, are these schemas the existing databases?</p>

答:
This answer is for Ubuntu users looking for a solution without writing SQL queries.

The following is the initial screen you'll get after opening it

In the top right, where it says Administration, click in the arrow to the right

This will show Schema (instead of Administration) and it's possible to see a sys database.

Right click in the grey area after functions and click Create Schema...

This will open the following where I'm creating a table named StackOverflow_db

Clicking in the bottom right button that says "Apply",

And in this new view click in "Apply" too. In the end you'll get a database called StackOverflow_db


来源: stackexchange

问:
Is it possible to create 1 Spring component index for a multi-module project?
We have a multimodule spring project, and we would like to create one component index for the entire project.

When adding the 'spring-context-indexer' to the POM(s) a seperate index is created per module in the project, however what we are looking for is one component index for all modules of the multi-module project together.

Does anyone know if it is possible to generate such an index?

答:
Put this on the main pom, or on each module pom. Each package will have it's own index.</p>

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${mavenCompilerVer}</version>
            <configuration>
                <source>11</source>
                <target>11</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-context-indexer</artifactId>
                        <version>${springContextIndexerVer}</version>
                    </path>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>${lombokVer}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Put this on the main pom, or on each module pom. Each package will have it's own index.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${mavenCompilerVer}</version>
            <configuration>
                <source>11</source>
                <target>11</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-context-indexer</artifactId>
                        <version>${springContextIndexerVer}</version>
                    </path>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>${lombokVer}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>


问:
How to upload a file in Flutter firebase and show it
I have searched a lot on uploading a file in firebase in flutter ,but none of them are working properly .
basically i want to select a file from my device and upload it to firebase and retrieve that file and show on screen .
Also i am new to flutter so i dont know how to handel permission for my SD card.
So can someone please show me the basic code required to do this task.</p>

答:
Basically these are the steps you need to follow (Assuming you've already connected your app to Firebase):

Implement file_picker: https://pub.dev/packages/file_picker

```<code>    File file = await FilePicker.getFile();
</code>```

(Add getFile() to a button during implementation)

Upload file to Firebase Storage:

```<code>StorageReference str = FirebaseStorage.instance
           .ref()
           .child('Files');
//Uploading
StorageUploadTask uploadTask =
           str.putFile(file);
//Getting download URL to save in database
String downloadURL =
           await (await uploadTask.onComplete).ref.getDownloadURL();
</code>```

Save downloadURL to Firebase Realtime Database:

```<code>realtimedb = FirebaseDatabase.instance.reference().child('FileLink');
realtimedb.set(downloadURL);
</code>```

Now to retrieve this you need to fetch the file link:

```<code>String dURL;
await realtimedb.instance
.reference()
.once()
.then((snapshot){dURL=snapshot.value;});
</code>```

Finally, depending on the type of file it is you can perform further steps to display it. For example, if it's an image you can use Image.network() to display it on your app. You have the link of the file in dURL so you can use it to access the file.

Body:
Basically these are the steps you need to follow (Assuming you've already connected your app to Firebase):

Implement file_picker: https://pub.dev/packages/file_picker

    File file = await FilePicker.getFile();

(Add getFile() to a button during implementation)

Upload file to Firebase Storage:

StorageReference str = FirebaseStorage.instance
           .ref()
           .child('Files');
//Uploading
StorageUploadTask uploadTask =
           str.putFile(file);
//Getting download URL to save in database
String downloadURL =
           await (await uploadTask.onComplete).ref.getDownloadURL();

Save downloadURL to Firebase Realtime Database:

realtimedb = FirebaseDatabase.instance.reference().child('FileLink');
realtimedb.set(downloadURL);

Now to retrieve this you need to fetch the file link:

String dURL;
await realtimedb.instance
.reference()
.once()
.then((snapshot){dURL=snapshot.value;});

Finally, depending on the type of file it is you can perform further steps to display it. For example, if it's an image you can use Image.network() to display it on your app. You have the link of the file in dURL so you can use it to access the file.


问:
Which design pattern to use to iterate over request attributes in spring boot
I have a requirement to save the request entity into multiple data sources. My request can have one or more request objects and they should be saved in respective databases. Which design patterns suits the requirement?

HTTP Request

```<code>{
  "params" : [
    {
       "id": "AB",
       "data": //some object
    },
    {
       "id": "CD",
       "data": //some object
    },
    {
       "id": "EF",
       "data": //some object
    },
    {
       "id": "GH",
       "data": //some object
    },
    {
       "id": "IJ",
       "data": //some object
    },
    ...........
    ...........
  ]
}
</code>```

AB & CD - to ORACLE instance 1

EF & GH - to ORACLE instance 2

IJ - to MYSQL

Here I know which object should be saved in which database. I don't want to iterate through the params array and create multiple small arrays, unless that's the only option. I'm looking here to apply a design pattern which will take care of the purpose, can someone please suggest?

答:
I think the best design pattern, in this case, is the [Factory method pattern][1]. Indeed you will create an appropriate object by the client data. I mean according id value the relevant service will call to save data into the respective database.

suppose you will have an interface for saving data with different implementations.

```<code>public interface IService {

   void save(Data data);

   List<String> types();
}
</code>```

and their implementations are something like these:

```<code>@Service
class OracleInstance1 implements IService {

   void save(Data data){}

   List<String> types(){return List.of("AB","CD");}
}
</code>```

for mysql  instance:

```<code>@Service
class MysqlInstance implements IService {

  void save(Data date){}

  List<String> types(){return List.of("IJ");}
}
</code>```

now you need a factory method to create a relevant object based on data entry.(id) for create a factory method I create a new service with ServiceHolder name. In this class all implementations of base service will use. because you use spring framework, it will do in easily. just by auto wiring a list.

```<code>@Service
class ServiceHolder{

  @Autowired
  List<IService> allService;

  public IService getByType(String type){
     return allService.stream()
            .filter(s->s.getTypes().contains(type))
            .findFirst().orElse(null);
  }
}
</code>```

now by performing this service and looping over data entries you can save in its own database.

```<code>for(MyParam param: params){
  serviceHolder.getByType(param.getId()).save(param.getData());
}
</code>```

by using getByType method you can find appropriate service for every data entry and call save method to insert into database.
[1]: https://en.wikipedia.org/wiki/Factory_method_pattern

Body:
I have a requirement to save the request entity into multiple data sources. My request can have one or more request objects and they should be saved in respective databases. Which design patterns suits the requirement?

HTTP Request

{
  "params" : [
    {
       "id": "AB",
       "data": //some object
    },
    {
       "id": "CD",
       "data": //some object
    },
    {
       "id": "EF",
       "data": //some object
    },
    {
       "id": "GH",
       "data": //some object
    },
    {
       "id": "IJ",
       "data": //some object
    },
    ...........
    ...........
  ]
}

AB & CD - to ORACLE instance 1

EF & GH - to ORACLE instance 2

IJ - to MYSQL

Here I know which object should be saved in which database. I don't want to iterate through the params array and create multiple small arrays, unless that's the only option. I'm looking here to apply a design pattern which will take care of the purpose, can someone please suggest?

Body:
I think the best design pattern, in this case, is the [Factory method pattern][1]. Indeed you will create an appropriate object by the client data. I mean according id value the relevant service will call to save data into the respective database.

suppose you will have an interface for saving data with different implementations.

public interface IService {

   void save(Data data);

   List<String> types();
}

and their implementations are something like these:

@Service
class OracleInstance1 implements IService {

   void save(Data data){}

   List<String> types(){return List.of("AB","CD");}
}

for mysql  instance:

@Service
class MysqlInstance implements IService {

  void save(Data date){}

  List<String> types(){return List.of("IJ");}
}

now you need a factory method to create a relevant object based on data entry.(id) for create a factory method I create a new service with ServiceHolder name. In this class all implementations of base service will use. because you use spring framework, it will do in easily. just by auto wiring a list.

@Service
class ServiceHolder{

  @Autowired
  List<IService> allService;

  public IService getByType(String type){
     return allService.stream()
            .filter(s->s.getTypes().contains(type))
            .findFirst().orElse(null);
  }
}

now by performing this service and looping over data entries you can save in its own database.

for(MyParam param: params){
  serviceHolder.getByType(param.getId()).save(param.getData());
}

by using getByType method you can find appropriate service for every data entry and call save method to insert into database.
[1]: https://en.wikipedia.org/wiki/Factory_method_pattern


问:
Connect Four game - understanding how array keeps always the same length
I'm a self learner, please bear with me.
So I'm following this tutorial on how to code a connect4 game and there's two things I'm definitely not getting

1 - every time I click on a cell I call the changeColor() and push to an empty array that specific cell. I dont get how the array always keeps only one cell.. it always has same length. Shouldn't it be adding each cell I click on to the array?

2 - in the stylesheet I defined that every cell would have the background color of white and when applying a if/ else condition as "if the cell is white then do something" the person in the tutorial defined in the js file once again that each cell has to have the background color of white in order for this condition to work
This does not make much sense to me because if its already defined in the stylesheet why does it not work unless I define it again in the js file?

Any help is much appreciated :)
codepen : https://codepen.io/mullerz/pen/WNremXo?editors=1111

tableCell.forEach(el => {
    el.addEventListener("click", changeColor);

    el.style.backgroundColor = 'white'
})

function changeColor(e){
    let column = e.target.cellIndex;
    let row = [];
    for(let i = tableRow.length-1 ; i > -1; i--){

        if (tableRow[i].children[column].style.backgroundColor == 'white'){
          row.push(tableRow[i].children[column])

          console.log(row)

            if (currentPlayer === 1){
                row[0].style.backgroundColor = 'red';
                playerTurn.style.color = player1Color;
                return currentPlayer = 2;
            }
            else{
                row[0].style.backgroundColor = 'yellow';
                playerTurn.style.color = player2Color;
                return currentPlayer = 1;
            }
        }

    }

}

```

答:
Variables in JavaScript are scoped. You are defining let row = [] every time the functions is called thats why the array is always empty at the start.
If you would move the variable declaration outside the function block it would not be redeclared everytime the function is run.

Because of if (tableRow[i].children[column].style.backgroundColor == 'white')
It seems to me the background color is used to check if the field was not selected before. But this is a bad practice and shouldnt be done.


问:
C: Solve an arithmetic expression with processes
I am trying to solve the expression (a+bc) / (a-b+d-c) + abcd, with different processes. But I don't know how fork() works. I know it is like a new thread but how can I join the result to another thread and finish each 'child' when an operation is done?

My code:

```<code>int arithOpera (int a, int b, int c, int d){
    int pid, pid1, pid2, pid3, pid4, pid5, pid6, pid7, pid8, pid9;
    pid = fork();
    int term1, term2, term3;
    if (pid == 0) {
        sol = term1 / term2;
    }

    else {
        pid1 = fork();
        if (pid1 == 0) {
            term3 *= d;
        }
        else {
            pid2 = fork();
            if (pid2 == 0) {
                term3 *= c;
            }
            else {
                pid3 = fork();
                if (pid3 == 0) {
                    term3 = a*b;
                }
                else {
                    pid4 = fork();
                    if (pid4 == 0) {
                        term2 -= c;
                    }
                    else {
                        pid5 = fork();
                        if (pid5 == 0) {
                            term2 += d;
                        }
                        else {
                            pid6 = fork();
                            if (pid6 == 0) {
                                term2 = a-b;
                            }
                            else {
                                pid7 = fork();
                                if (pid7 == 0) {
                                    term1 += a;
                                }
                                else {
                                    pid8 = fork();
                                    if (pid8 == 0) {
                                        term1 = b * c;
                                    }
                                    else {
                                        sol += term3;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return sol;
}
</code>```

I should do each operation in a different thread.

答:
First, fork() generates new processes not threads of the same process, if you need to make a new thread instead of another process, you can use the pthread library (1) , where you can use pthread_create (2) to generate a new thread, return the result of one thread to another one with  pthread_exit (3) and catch it in the desired thread with the pthread_join function (4).

But if you want to use the fork function, you will need to generate some share memory among all the different processes, in that case you also need to be aware of the possible concurrence problems that may appear. (This way is more complex if you do not know anything about concurrence programming).

If you want me to provide you wider explanations, please let me know.
I attach here the manual pages regarding the pthread library functions.

pthread overview https://www.man7.org/linux/man-pages/man7/pthreads.7.html

pthread_create https://www.man7.org/linux/man-pages/man3/pthread_create.3.html

pthread_exit https://www.man7.org/linux/man-pages/man3/pthread_exit.3.html

pthread_join https://www.man7.org/linux/man-pages/man3/pthread_join.3.html

Body:
I am trying to solve the expression (a+bc) / (a-b+d-c) + abcd, with different processes. But I don't know how fork() works. I know it is like a new thread but how can I join the result to another thread and finish each 'child' when an operation is done?

My code:

int arithOpera (int a, int b, int c, int d){
    int pid, pid1, pid2, pid3, pid4, pid5, pid6, pid7, pid8, pid9;
    pid = fork();
    int term1, term2, term3;
    if (pid == 0) {
        sol = term1 / term2;
    }

    else {
        pid1 = fork();
        if (pid1 == 0) {
            term3 *= d;
        }
        else {
            pid2 = fork();
            if (pid2 == 0) {
                term3 *= c;
            }
            else {
                pid3 = fork();
                if (pid3 == 0) {
                    term3 = a*b;
                }
                else {
                    pid4 = fork();
                    if (pid4 == 0) {
                        term2 -= c;
                    }
                    else {
                        pid5 = fork();
                        if (pid5 == 0) {
                            term2 += d;
                        }
                        else {
                            pid6 = fork();
                            if (pid6 == 0) {
                                term2 = a-b;
                            }
                            else {
                                pid7 = fork();
                                if (pid7 == 0) {
                                    term1 += a;
                                }
                                else {
                                    pid8 = fork();
                                    if (pid8 == 0) {
                                        term1 = b * c;
                                    }
                                    else {
                                        sol += term3;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return sol;
}

I should do each operation in a different thread.


问:
How to update Spring Boot version using a command line
How do you update the spring boot version of a java application (preferably using a command line)? I have tried googling but I haven't found anything that works - these usually involve changing certain lines of code which I don't have in my pre-existing project.

EDIT: I have a build.gradle file with a line under dependencies that goes: classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.4.RELEASE") but when I change it to 2.3.0 it doesn't build correctly - I get an error saying "error: package javax.validation.constraints does not exist
import javax.validation.constrants.NotEmpty;"

答: There is no way to upgrade Spring Boot version automatically. You need to review your application source code and apply the update manually. How to do it will depend on you application e.g. if you are using Maven build tool then you should start by modifying pom.xml


问:
How to mock a https server by pact-python, could you give me a example
I can't mock a https serve according to API,please give me some advice

python version: 3.6.5
pact-python: 1.0
pytest:5.3.5
platform:windows

Error message:
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='localhost', port=1234): Max retries exceeded with url: / (Caused by SSLError(SSLError("bad handshake: Error([('SSL rou
tines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

process:

I try to mock a https server by pact-python so I set ssl=True and don't set sslcert and sslkey, it can't work. Then I try to creat a self-signed sslcert and sslkey  use openssl tools then set option: sslcert = 'server.crt', sslkey = 'server.key',it still not work. It's a very simple example, I just wanna mock a https server:

```<code>import requests
import atexit
import pytest

from pact import Consumer, Provider

def user(user_name):
    """Fetch a user object by user_name from the server."""
    uri = 'https://localhost:1234/users/' + user_name
    return requests.get(uri, verify = False).json()

pact = Consumer('Consumer').has_pact_with(Provider('Provider'), port=1234, ssl = True,
                                          sslcert = 'server.crt', sslkey = 'server.key')
pact.start_service()
atexit.register(pact.stop_service)

def test_get_user():
    expected = {
        'username': 'UserA',
        'id': 123,
        'groups': ['Editors']
    }

    (pact
     .given('UserA exists and is not an administrator')
     .upon_receiving('a request for UserA')
     .with_request('get', '/users/UserA')
     .will_respond_with(200, body = expected))

    with pact:
        result = user('UserA')

    assert(result, expected)
</code>```

答:
I think it might be the Pact Python trying to see if the server has come up. It might be a bug, if you can reproduce the bug reliably, please share that code and raise an issue.

FWIW using Pact tests with https is usually pointless IMO. Pact tests are designed to tests the contract, and the s part of HTTP makes no difference to this.

Body:
I can't mock a https serve according to API,please give me some advice

python version: 3.6.5
pact-python: 1.0
pytest:5.3.5
platform:windows

Error message:
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='localhost', port=1234): Max retries exceeded with url: / (Caused by SSLError(SSLError("bad handshake: Error([('SSL rou
tines', 'tls_process_server_certificate', 'certificate verify failed')],)",),))

process:

I try to mock a https server by pact-python so I set ssl=True and don't set sslcert and sslkey, it can't work. Then I try to creat a self-signed sslcert and sslkey  use openssl tools then set option: sslcert = 'server.crt', sslkey = 'server.key',it still not work. It's a very simple example, I just wanna mock a https server:

import requests
import atexit
import pytest

from pact import Consumer, Provider

def user(user_name):
    """Fetch a user object by user_name from the server."""
    uri = 'https://localhost:1234/users/' + user_name
    return requests.get(uri, verify = False).json()

pact = Consumer('Consumer').has_pact_with(Provider('Provider'), port=1234, ssl = True,
                                          sslcert = 'server.crt', sslkey = 'server.key')
pact.start_service()
atexit.register(pact.stop_service)

def test_get_user():
    expected = {
        'username': 'UserA',
        'id': 123,
        'groups': ['Editors']
    }

    (pact
     .given('UserA exists and is not an administrator')
     .upon_receiving('a request for UserA')
     .with_request('get', '/users/UserA')
     .will_respond_with(200, body = expected))

    with pact:
        result = user('UserA')

    assert(result, expected)


问:
ARKit capturedImage and snapshot are not same
I am trying to get an image without 3D models and 3D models at the same time.

I use

session.currentFrame!.capturedImage

and then I take a snapshot using

sceneView.snapshot()

when both are done. the images look different, how do I get same image twice, one with and without 3D content. preferably in high res.

taken on iPhone 7s plus. so I am guessing the capturedImage and snapshot are using different lens?

Session Captured Image

Scene Session Snapshot

If you see the images. the captured image cropped is not same. somehow the focal length or something is different in the snapshot.

答:
The displayTransformForOrientation:viewportSize: provides the transform that ARKit uses to map the capturedImage onto the view's background:

This method creates an affine transform representing the rotation and
  aspect-fit crop operations necessary to adapt the camera image to the
  specified orientation and to the aspect ratio of the specified
  viewport.


问:
How to configure go back button in Browser for Flutter Web App
I'm not asking about webview. This is about Flutter web app. I need to go back to a specific page when user press back button which is inbuilt in browser.

Any guessing  ?

I'm getting this error when I press  back button

```<code>Error: Assertion failed: org-dartlang-
    sdk:///flutter_web_sdk/lib/_engine/engine/history.dart:110:14
    _userProvidedRouteName != null
    is not true
        at Object.throw_ [as throw] (http://localhost:8300/dart_sdk.js:4770:11)
        at Object.assertFailed (http://localhost:8300/dart_sdk.js:4721:15)
</code>```

答:
In case if you don't want to navigate to a new page</p>

```<code>    @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => true,
      child: Scaffold(

        key: _scaffold,
        backgroundColor: Colors.indigo,
        body: Center(
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                registerForm(),
                registerBtn(),
                SizedBox(height: 30,),
                _buildSignInButton()
              ],
            ),
          ),
        ),
      ),
    );
  }
</code>```

Body:
I'm not asking about webview. This is about Flutter web app. I need to go back to a specific page when user press back button which is inbuilt in browser.

Any guessing  ?

I'm getting this error when I press  back button

Error: Assertion failed: org-dartlang-
    sdk:///flutter_web_sdk/lib/_engine/engine/history.dart:110:14
    _userProvidedRouteName != null
    is not true
        at Object.throw_ [as throw] (http://localhost:8300/dart_sdk.js:4770:11)
        at Object.assertFailed (http://localhost:8300/dart_sdk.js:4721:15)

Body:
In case if you don't want to navigate to a new page

    @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => true,
      child: Scaffold(

        key: _scaffold,
        backgroundColor: Colors.indigo,
        body: Center(
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                registerForm(),
                registerBtn(),
                SizedBox(height: 30,),
                _buildSignInButton()
              ],
            ),
          ),
        ),
      ),
    );
  }


问:
Material-UI TextField state incorrect after uncontrolled value change with react-hook-form
I have a Material-UI TextField element as below

```<code><TextField
    variant='outlined' fullWidth
    name={'webhook'}
    label={'Webhook URL'}
    defaultValue={state.webhook}
    error={errors.webhook !== undefined}
    helperText={errors.webhook && 'Not a valid webhook URL.'}
    inputRef={register({
        required: true,
    })}
/>
</code>```

And I control the value of the input using react-hook-form.  It says as per the documentation that it is to be used with uncontrolled inputs as it controls the value of it through the useForm props.

So when I set the value from the default value of '' (empty string) to an actual value provided by a variable (non-empty string) using setValue from useForm(), the input label overlays the text in the center of the textfield instead of moving to the top as it would with an input that has a value.

Modifying the value of the field after the input's value gets set will make it work properly, but I need it to recognize that the value changed without modifying the value.

How can I get it to properly recognize that the value of the input has changed?

Example of image in glitched state:

答:
You want to take a look at Controller: https://react-hook-form.com/api#Controller

here is a codesandbox: https://codesandbox.io/s/react-hook-form-controller-079xx

```<code><Controller name="test" control={control} as={TextField} />
</code>```

Body:
I have a Material-UI TextField element as below

<TextField
    variant='outlined' fullWidth
    name={'webhook'}
    label={'Webhook URL'}
    defaultValue={state.webhook}
    error={errors.webhook !== undefined}
    helperText={errors.webhook && 'Not a valid webhook URL.'}
    inputRef={register({
        required: true,
    })}
/>

And I control the value of the input using react-hook-form.  It says as per the documentation that it is to be used with uncontrolled inputs as it controls the value of it through the useForm props.

So when I set the value from the default value of '' (empty string) to an actual value provided by a variable (non-empty string) using setValue from useForm(), the input label overlays the text in the center of the textfield instead of moving to the top as it would with an input that has a value.

Modifying the value of the field after the input's value gets set will make it work properly, but I need it to recognize that the value changed without modifying the value.

How can I get it to properly recognize that the value of the input has changed?

Example of image in glitched state:

Body:
You want to take a look at Controller: https://react-hook-form.com/api#Controller

here is a codesandbox: https://codesandbox.io/s/react-hook-form-controller-079xx

<Controller name="test" control={control} as={TextField} />


问:
VB6 -> VB.NET ... Cannot find the Canvas control in .NET
I am trying to convert some old VB6 code to VB.NET. The VB6 uses a Canvas control, simply

```<code>Dim cv as Canvas
</code>```

I cannot for the life of me figure out how to use the Canvas control in VB.NET (using VS2005). MSDN says it is in the System.Windows.Controls namespace, which doesn't seem to exist? All I see is System.Windows.Forms, which doesn't include the Canvas control. Any tips?

Thanks

答:
In recent history things have changed a bit here. There are now two sets of windows frameworks.

Forms are the old one. The new ones are controls, and they come in the WPF and Silverlight variety. WPF is to replace windows forms, silverlight is meant for the web, etc etc.

Since you are using the older VS2005, I believe you will need to install the WPF extensions to get access to them.

Unfortunately the WPF Extensions for VS2005 are no longer supported by Microsoft:

http://blogs.msdn.com/b/acangialosi/archive/2008/06/27/vs-2005-extensions-for-net-framework-3-0-wpf-wcf-ctp-is-coming-off-the-ms-download-center.aspx

You can still get them from various places, but for your own ease you should probably consider upgrading to at least VS2008 if you want to use WPF/Silverlight.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to convert some old VB6 code to VB.NET. The VB6 uses a Canvas control, simply

Dim cv as Canvas

I cannot for the life of me figure out how to use the Canvas control in VB.NET (using VS2005). MSDN says it is in the System.Windows.Controls namespace, which doesn't seem to exist? All I see is System.Windows.Forms, which doesn't include the Canvas control. Any tips?

Thanks


问:
How to update donation bar when someone makes donation via PayPal?
I use this code snippet for redirecting people to PayPal site when they click on donation button:

```<code><form action="https://www.paypal.com/cgi-bin/webscr" method=post target="_top">
    <input type=hidden name=cmd value="_donations">
    <input type=hidden name=business value="mail@example.de">
    <input type=hidden name=lc value="DE">
    <input type=hidden name="currency_code" value="EUR">
    <input type=hidden name=return value="URL-HERE">
    <input type=hidden name="cancel_return" value="URL-HERE">
    <input type=hidden name="item_name" value="MYSITE.de">
    <input type=hidden name=p3 value="1">
    <input type=hidden name=t3 value="M">

    <input type=radio name=amount value="3.00">
    <input type=radio name=amount value="5.00">

    <button type=submit name=submit>DONATE-BTN</button>

</form>
</code>```

Is it possible to make a donation bar that gets updated after someone made donation? And how I accomplish it?

答: You can subscribe to webhook events for payment notifications.</p>

Body:
I use this code snippet for redirecting people to PayPal site when they click on donation button:

<form action="https://www.paypal.com/cgi-bin/webscr" method=post target="_top">
    <input type=hidden name=cmd value="_donations">
    <input type=hidden name=business value="mail@example.de">
    <input type=hidden name=lc value="DE">
    <input type=hidden name="currency_code" value="EUR">
    <input type=hidden name=return value="URL-HERE">
    <input type=hidden name="cancel_return" value="URL-HERE">
    <input type=hidden name="item_name" value="MYSITE.de">
    <input type=hidden name=p3 value="1">
    <input type=hidden name=t3 value="M">

    <input type=radio name=amount value="3.00">
    <input type=radio name=amount value="5.00">

    <button type=submit name=submit>DONATE-BTN</button>

</form>

Is it possible to make a donation bar that gets updated after someone made donation? And how I accomplish it?


问:
How do I update values without refreshing the page on my Flask project?
I have a website that shows the prices of items in a video game.

Currently, I have an "auto-refresh" script that refreshes the page every 5 seconds, but it is a bit annoying as every time you search for a product, it removes your search because the page refreshes.

I would like to update the numbers in my table without refreshing the page for the user. I read something about 'updating the DOM', in javascript but didn't get it.

Here is the link to my website: http://xeltool.com/

And here is my python code:

```<code>@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[cannot show]').json()

    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return render_template("bprices.html", products=products)
</code>```

And here is my HTML code:

```<code><div class="container">
  <div class="search_div">
    <input
      type="text"
      onkeyup="myFunction()"
      id="myInput"
      title="Type in a product"
      class="search-box"
      placeholder="Search for a product..."
    />
    <button class="search-btn"><i class="fas fa-search"></i></button>
  </div>

  <table
    id="myTable"
    class="table table-striped table-bordered table-sm table-dark sortable"
    cellspacing="0"
  >
    <thead>
      <tr>
        <th aria-label="Product Name" data-balloon-pos="up">Product</th>
        <th aria-label="Product's buy price" data-balloon-pos="up">
          Buy Price
        </th>
        <th aria-label="Product's sell price" data-balloon-pos="up">
          Sell Price
        </th>
        <th aria-label="Product's buy volume" data-balloon-pos="up">
          Buy Volume
        </th>
        <th aria-label="Product's sell volume" data-balloon-pos="up">
          Sell Volume
        </th>
        <th>
          Margin
        </th>
      </tr>
    </thead>
    <tbody>
      {% for product in products %}
      <tr>
        <td>{{ product.id|replace("_", ' ')|lower()|title() }}</td>
        {% for buy in product.buy_price %}
        <td>{{ buy.pricePerUnit }}</td>
        {% for sell in product.sell_price %}
        <td>{{ sell.pricePerUnit }}</td>

        <td>{{ product.buy_volume| numberFormat }}</td>
        <td>{{ product.sell_volume| numberFormat }}</td>
        {% set margin = buy.pricePerUnit - sell.pricePerUnit%} {% set marginPer
        = margin/buy.pricePerUnit * 100%}
        <td
          aria-label="{{ marginPer|round(1, 'floor') }} % "
          data-balloon-pos="right"
        >
          {{ margin|round(1, 'floor')}}
        </td>
        {% endfor %}{% endfor %}
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>
</code>```

If you NEED the API to test this out, I can provide a link to it :)

答:
You have 3 options:

AJAX - https://www.w3schools.com/js/js_ajax_intro.asp

SSE - https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

Websocket - https://developer.mozilla.org/en-US/docs/Glossary/WebSockets

I think the best option in your case is SSE since the server knows that the price was changed so it can push it to the clients.

Body:
I have a website that shows the prices of items in a video game.

Currently, I have an "auto-refresh" script that refreshes the page every 5 seconds, but it is a bit annoying as every time you search for a product, it removes your search because the page refreshes.

I would like to update the numbers in my table without refreshing the page for the user. I read something about 'updating the DOM', in javascript but didn't get it.

Here is the link to my website: http://xeltool.com/

And here is my python code:

@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[cannot show]').json()

    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return render_template("bprices.html", products=products)

And here is my HTML code:

    <input
      type="text"
      onkeyup="myFunction()"
      id="myInput"
      title="Type in a product"
      class="search-box"
      placeholder="Search for a product..."
    />
    <button class="search-btn"></button>

        Product

          Buy Price

          Sell Price

          Buy Volume

          Sell Volume

          Margin

      {% for product in products %}

        {{ product.id|replace("_", ' ')|lower()|title() }}
        {% for buy in product.buy_price %}
        {{ buy.pricePerUnit }}
        {% for sell in product.sell_price %}
        {{ sell.pricePerUnit }}

        {{ product.buy_volume| numberFormat }}
        {{ product.sell_volume| numberFormat }}
        {% set margin = buy.pricePerUnit - sell.pricePerUnit%} {% set marginPer
        = margin/buy.pricePerUnit * 100%}

          {{ margin|round(1, 'floor')}}

        {% endfor %}{% endfor %}

      {% endfor %}

If you NEED the API to test this out, I can provide a link to it :)


问:
How to point on the concrete Dockerfile for the docker build command inside the jenkins pipeline?
Please let me know how to point on the concrete Dockerfile for the docker build command inside the jenkins pipeline?

I am trying to give a docker build from a Jenkins pipeline, I am using a common code to run this build and would want the pipeline to access a folder where the dockerfile is. How do I let the docker know how to find this dockerfile which is in a different folder location.

答:
With sh in a declarative pipeline:

```<code>sh '''
    docker build -t '<myimagename>' \
        --file <somewhereelse>/Dockerfile .
'''
</code>```

Within a scripted pipeline:

```<code>docker.build("my-image:${env.BUILD_ID}", "-f ${dockerfile} ./dockerfiles")
</code>```

Body:
With sh in a declarative pipeline:

sh '''
    docker build -t '<myimagename>' \
        --file <somewhereelse>/Dockerfile .
'''

Within a scripted pipeline:

docker.build("my-image:${env.BUILD_ID}", "-f ${dockerfile} ./dockerfiles")


问:
Configure Spring boot for multiple DBMS and multiple profiles
I'm new to Spring Boot, and I don't know if what I want to do is possible, but I have the following problem to solve.

1 - I have an API with Spring Boot and I need to configure two DBMS (MySQL and Postgres).

2 - For each DBMS I need to configure different profiles. (Dev, Prod)

Follow my MySQL configuration classes:

```<code>@Component
@Profile("mysql")
public class ConfigMySQL {

    public ConfigMySQL() {
        System.out.println("BD MySQL");
    }
}

@Component
@Profile("dev")
public class ConfigDevMySQL extends ConfigMySQL {

    public ConfigDevMySQL() {
        System.out.println("\n\n");
        System.out.println(" ****** Configuration dev MySQL... ******");
        System.out.println("\n\n");
    }
}

@Component
@Profile("prod")
public class ConfigProdMySQL extends ConfigMySQL{

    public ConfigProdMySQL() {
        System.out.println("\n\n");
        System.out.println(" ****** Configuration prod MySQL... ******");
        System.out.println("\n\n");
    }
}

</code>```

Follow my Postgres configuration classes:

```<code>@Component
@Profile("postgres")
public class ConfigPostgres {

    public ConfigPostgres() {
        System.out.println("DB postgres");
    }
}

@Component
@Profile("dev")
public class ConfigDevPostgres extends ConfigPostgres{

    public ConfigDevPostgres() {
        System.out.println("\n\n");
        System.out.println(" ****** Configuration dev Postgres... ******");
        System.out.println("\n\n");
    }
}

@Component
@Profile("prod")
public class ConfigProdPostgres extends ConfigPostgres {

    public ConfigProdPostgres() {
        System.out.println("\n\n");
        System.out.println(" ****** Configuration prod Postgres... ******");
        System.out.println("\n\n");
    }
}

</code>```

my profile file looks like this:

Note: I'm pretty sure he's wrong, but I kept it that way for example.

```<code>spring.profiles.active=mysql
spring.profiles.active=dev

</code>```

Always keep in mind that it is a single API, with two DBMS and different profiles.

When I run my application I have this output on the console

```<code> BD MySQL

 ****** Configuration dev MySQL... ******

DB postgres

 ****** Configuration dev Postgres... ******
</code>```

I expected my exit to be:

```<code>DB MySQL

 ****** Configuration dev MySQL... ******

</code>```

Important:

When I configure the profile to connect to my MySQL Dev database, I only want to connect to it. And I want the same result, when it is the basis of MySQL's Prod.

This also applies to Postgres.

When I configure the profile to connect to my Postgres Dev database, I want to connect only to it. And I want the same result, when it is the base of Prod of Postgres.

I really don't know if this is possible and I don't even know how to do it!

Does anyone know how to do this setup, and could you help me?

I thank you for your attention.

答:
Rather than have multiple spring components with the @Profile annotation you could use config classes with @Profile(db_name) and then have the environment-specific profile activation in those classes. For example for the MySQL profile:

```<code>    @Configuration
    @Profile("mysql")
    public class MySqlConfiguration{

        public MySqlConfiguration() {
            System.out.println("BD MySQL");
        }

        @Bean
        @Profile("dev")
        public ConfigDevMySQL() {
            return new ConfigDevMySQL();
        }

        @Bean
        @Profile("prod")
        public ConfigProdMySQL () {
            return new ConfigProdMySQL();
        }
    }
</code>```

This should mean that the Configuration classes are only read when the relevant DB profile is set and the subsequent Beans only created when the relevant environment profile is set.

You'd also remove the @Component annotation from your current classes - ConfigProdMySQL etc - and instantiate them manually in the configuration classes.

Body:
I'm new to Spring Boot, and I don't know if what I want to do is possible, but I have the following problem to solve.

1 - I have an API with Spring Boot and I need to configure two DBMS (MySQL and Postgres).

2 - For each DBMS I need to configure different profiles. (Dev, Prod)

Follow my MySQL configuration classes:

@Component
@Profile("mysql")
public class ConfigMySQL {

    public ConfigMySQL() {
        System.out.println("BD MySQL");
    }
}

@Component
@Profile("dev")
public class ConfigDevMySQL extends ConfigMySQL {

    public ConfigDevMySQL() {
        System.out.println("\n\n");
        System.out.println(" ****** Configuration dev MySQL... ******");
        System.out.println("\n\n");
    }
}

@Component
@Profile("prod")
public class ConfigProdMySQL extends ConfigMySQL{

    public ConfigProdMySQL() {
        System.out.println("\n\n");
        System.out.println(" ****** Configuration prod MySQL... ******");
        System.out.println("\n\n");
    }
}

Follow my Postgres configuration classes:

@Component
@Profile("postgres")
public class ConfigPostgres {

    public ConfigPostgres() {
        System.out.println("DB postgres");
    }
}

@Component
@Profile("dev")
public class ConfigDevPostgres extends ConfigPostgres{

    public ConfigDevPostgres() {
        System.out.println("\n\n");
        System.out.println(" ****** Configuration dev Postgres... ******");
        System.out.println("\n\n");
    }
}

@Component
@Profile("prod")
public class ConfigProdPostgres extends ConfigPostgres {

    public ConfigProdPostgres() {
        System.out.println("\n\n");
        System.out.println(" ****** Configuration prod Postgres... ******");
        System.out.println("\n\n");
    }
}

my profile file looks like this:

Note: I'm pretty sure he's wrong, but I kept it that way for example.

spring.profiles.active=mysql
spring.profiles.active=dev

Always keep in mind that it is a single API, with two DBMS and different profiles.

When I run my application I have this output on the console

 BD MySQL

 ****** Configuration dev MySQL... ******

DB postgres

 ****** Configuration dev Postgres... ******

I expected my exit to be:

DB MySQL

 ****** Configuration dev MySQL... ******

Important:

When I configure the profile to connect to my MySQL Dev database, I only want to connect to it. And I want the same result, when it is the basis of MySQL's Prod.

This also applies to Postgres.

When I configure the profile to connect to my Postgres Dev database, I want to connect only to it. And I want the same result, when it is the base of Prod of Postgres.

I really don't know if this is possible and I don't even know how to do it!

Does anyone know how to do this setup, and could you help me?

I thank you for your attention.

Body:
Rather than have multiple spring components with the @Profile annotation you could use config classes with @Profile(db_name) and then have the environment-specific profile activation in those classes. For example for the MySQL profile:

    @Configuration
    @Profile("mysql")
    public class MySqlConfiguration{

        public MySqlConfiguration() {
            System.out.println("BD MySQL");
        }

        @Bean
        @Profile("dev")
        public ConfigDevMySQL() {
            return new ConfigDevMySQL();
        }

        @Bean
        @Profile("prod")
        public ConfigProdMySQL () {
            return new ConfigProdMySQL();
        }
    }

This should mean that the Configuration classes are only read when the relevant DB profile is set and the subsequent Beans only created when the relevant environment profile is set.

You'd also remove the @Component annotation from your current classes - ConfigProdMySQL etc - and instantiate them manually in the configuration classes.


问:
Proper way to setup user-item interactions data in lightfm
What is the right way to setup the data when feeding to lightfm model for cases where I have additional implicit data on additional items/products. For example, I have 100k users x 200 items interaction data, however in real application, I want the  model to provide recommendations only from 50 out of the 200 items. So how do I setup the data? I am thinking of 2 cases but I am not sure which is the right approach:

Case 1: Feed the whole matrix (100k users x 200 items) directly as interactions argument in lightfm. This way it is more collaborative learning.

Case 2: Only feed (100k users x 50 items) to interactions argument and use the (100k x 150 items) matrix as user_features. This way it's more content based learning.

Which one is correct?
Also, for case 1, is there a way for the utility functions for model evaluations(precision, recall, etc) to recommend for selected items only, for example, the top k recommended items should only be taken from the 50 items and do not recommend the other items and compute the precision, recall, etc from those.

答:
You should follow case 1. Train the model with entire interactions data.
While making predictions, you can pass the index of required(50) items as a parameter to model.predict.

From the lightfm documentation, you can see that model.predict takes item ids as parameter(which will be ids of your 50 items in this case).

https://making.lyst.com/lightfm/docs/_modules/lightfm/lightfm.html#LightFM.predict

def predict(self, user_ids, item_ids, item_features=None,
                user_features=None, num_threads=1):
        """
        Compute the recommendation score for user-item pairs.

```<code>    Arguments
    ---------

    user_ids: integer or np.int32 array of shape [n_pairs,]
         single user id or an array containing the user ids for the
         user-item pairs for which a prediction is to be computed
    item_ids: np.int32 array of shape [n_pairs,]
         an array containing the item ids for the user-item pairs for which
         a prediction is to be computed
    user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
         Each row contains that user's weights over features
    item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
         Each row contains that item's weights over features
    num_threads: int, optional
         Number of parallel computation threads to use. Should
         not be higher than the number of physical cores.
</code>```

Body:
You should follow case 1. Train the model with entire interactions data.
While making predictions, you can pass the index of required(50) items as a parameter to model.predict.

From the lightfm documentation, you can see that model.predict takes item ids as parameter(which will be ids of your 50 items in this case).

https://making.lyst.com/lightfm/docs/_modules/lightfm/lightfm.html#LightFM.predict

def predict(self, user_ids, item_ids, item_features=None,
                user_features=None, num_threads=1):
        """
        Compute the recommendation score for user-item pairs.

    Arguments
    ---------

    user_ids: integer or np.int32 array of shape [n_pairs,]
         single user id or an array containing the user ids for the
         user-item pairs for which a prediction is to be computed
    item_ids: np.int32 array of shape [n_pairs,]
         an array containing the item ids for the user-item pairs for which
         a prediction is to be computed
    user_features: np.float32 csr_matrix of shape [n_users, n_user_features], optional
         Each row contains that user's weights over features
    item_features: np.float32 csr_matrix of shape [n_items, n_item_features], optional
         Each row contains that item's weights over features
    num_threads: int, optional
         Number of parallel computation threads to use. Should
         not be higher than the number of physical cores.


问:
Keras: TypeError: 'float' object is not callable. Unable to call model.fit() or model.fit_generator() on very simple CNN model
I am workimg on MNIST Hand Sign Dataset for classification. I have my (28*28) images pixels in a numpy array as:

```<code>X_train.shape, X_val.shape
>>
((2496, 28, 28, 1), (996, 28, 28, 1))
</code>```

I have used ImageDataGenerator to make batches and train the model. I have been the following instructions:

```<code>Batch size =50, epoch=20
All filter (kernel) sizes are 3x3
Initial Conv2D layer with 64 filters
MaxPooling layer following this
Second Conv2D layer with 128 filters
Dense output layer after this
</code>```

My model is as follows:

```<code>datagen = ImageDataGenerator(preprocessing_function=1./255.0)
train_gen = datagen.flow(X_train, y_train, batch_size=50)
val_gen = datagen.flow(X_val,y_val, batch_size=50)

input_ = Input(shape=(28,28,1))
x = Conv2D(64,kernel_size=(3,3))(input_)
x = ELU()(x)
x = MaxPooling2D(pool_size=(3,3))(x)
x = Conv2D(128,kernel_size=(3,3))(input_)
x = ELU()(x)
x = Flatten()(x)
out = Dense(24,activation='softmax')(x)

model = Model(inputs=input_,outputs=out)
model.compile(loss=sparse_categorical_crossentropy,optimizer=Adam(lr=0.001),metrics=['accuracy'])

model.fit(train_gen,epochs=20,)

</code>```

I have used Sparse Categorical Cross Entropy because I have some missing class values in my y_labels. There are 24 classes from 0-24 but class=9 missing.

Can someone tell me why is that hapenning??

I think the problem is in train_gen because next(train_gen) gives me the same error.

Lower half of the error is:

```<code>/opt/conda/lib/python3.7/site-packages/keras/utils/data_utils.py in get_index(uid, i)
    404         The value at index `i`.
    405     """
--> 406     return _SHARED_SEQUENCES[uid][i]
    407
    408

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/iterator.py in __getitem__(self, idx)
     63         index_array = self.index_array[self.batch_size * idx:
     64                                        self.batch_size * (idx + 1)]
---> 65         return self._get_batches_of_transformed_samples(index_array)
     66
     67     def __len__(self):

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/numpy_array_iterator.py in _get_batches_of_transformed_samples(self, index_array)
    152             x = self.image_data_generator.apply_transform(
    153                 x.astype(self.dtype), params)
--> 154             x = self.image_data_generator.standardize(x)
    155             batch_x[i] = x
    156

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/image_data_generator.py in standardize(self, x)
    702         """
    703         if self.preprocessing_function:
--> 704             x = self.preprocessing_function(x)
    705         if self.rescale:
    706             x *= self.rescale

TypeError: 'float' object is not callable

</code>```

答:
The problem is in this part:

```<code>datagen = ImageDataGenerator(preprocessing_function=1./255.0)
</code>```

The preprocessing_function parameter expects a function, not a float value. You probably confused it with the rescale parameter:

```<code>datagen = ImageDataGenerator(rescale=1./255.0)
</code>```

Body:
I am workimg on MNIST Hand Sign Dataset for classification. I have my (28*28) images pixels in a numpy array as:

X_train.shape, X_val.shape
>>
((2496, 28, 28, 1), (996, 28, 28, 1))

I have used ImageDataGenerator to make batches and train the model. I have been the following instructions:

Batch size =50, epoch=20
All filter (kernel) sizes are 3x3
Initial Conv2D layer with 64 filters
MaxPooling layer following this
Second Conv2D layer with 128 filters
Dense output layer after this

My model is as follows:

datagen = ImageDataGenerator(preprocessing_function=1./255.0)
train_gen = datagen.flow(X_train, y_train, batch_size=50)
val_gen = datagen.flow(X_val,y_val, batch_size=50)

input_ = Input(shape=(28,28,1))
x = Conv2D(64,kernel_size=(3,3))(input_)
x = ELU()(x)
x = MaxPooling2D(pool_size=(3,3))(x)
x = Conv2D(128,kernel_size=(3,3))(input_)
x = ELU()(x)
x = Flatten()(x)
out = Dense(24,activation='softmax')(x)

model = Model(inputs=input_,outputs=out)
model.compile(loss=sparse_categorical_crossentropy,optimizer=Adam(lr=0.001),metrics=['accuracy'])

model.fit(train_gen,epochs=20,)

I have used Sparse Categorical Cross Entropy because I have some missing class values in my y_labels. There are 24 classes from 0-24 but class=9 missing.

Can someone tell me why is that hapenning??

I think the problem is in train_gen because next(train_gen) gives me the same error.

Lower half of the error is:

/opt/conda/lib/python3.7/site-packages/keras/utils/data_utils.py in get_index(uid, i)
    404         The value at index `i`.
    405     """
--> 406     return _SHARED_SEQUENCES[uid][i]
    407
    408

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/iterator.py in __getitem__(self, idx)
     63         index_array = self.index_array[self.batch_size * idx:
     64                                        self.batch_size * (idx + 1)]
---> 65         return self._get_batches_of_transformed_samples(index_array)
     66
     67     def __len__(self):

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/numpy_array_iterator.py in _get_batches_of_transformed_samples(self, index_array)
    152             x = self.image_data_generator.apply_transform(
    153                 x.astype(self.dtype), params)
--> 154             x = self.image_data_generator.standardize(x)
    155             batch_x[i] = x
    156

/opt/conda/lib/python3.7/site-packages/keras_preprocessing/image/image_data_generator.py in standardize(self, x)
    702         """
    703         if self.preprocessing_function:
--> 704             x = self.preprocessing_function(x)
    705         if self.rescale:
    706             x *= self.rescale

TypeError: 'float' object is not callable

Body:
The problem is in this part:

datagen = ImageDataGenerator(preprocessing_function=1./255.0)

The preprocessing_function parameter expects a function, not a float value. You probably confused it with the rescale parameter:

datagen = ImageDataGenerator(rescale=1./255.0)


问:
MediaQuery.of() called with a context that does not contain a MediaQuery. (emergency aid)
I deleted the 'MaterialApp' code block because I couldn't write the codes I wanted at the beginning.

Now it gives an error, how can I fix this? I have to handle this in a very short time, I have to put the codes I wrote in the "MaterialApp" block, but I can't.

Can you help me ?

```<code>class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
    return CupertinoTabScaffold(
        tabBar: CupertinoTabBar(
            items: < BottomNavigationBarItem > [
                new BottomNavigationBarItem(
                    icon: new Icon(Icons.home),
                    title: Text('Enes'),
                ),
                new BottomNavigationBarItem(
                    icon: new Icon(Icons.bluetooth),
                    title: Text('Mehmet'),
                ),
            ],
        ),
        tabBuilder: (BuildContext context, int index) {
            return CupertinoTabView(
                builder: (BuildContext context) {
                    return CupertinoPageScaffold(
                        navigationBar: CupertinoNavigationBar(
                            middle: Text('Page 1 of tab $index'),
                        ),
                        child: Center(
                            child: CupertinoButton(
                                child: const Text('Next Page'),
                                    onPressed: () {
                                        Navigator.of(context).push(
                                            CupertinoPageRoute < void > (
                                                builder: (BuildContext context) {
                                                    return CupertinoPageScaffold(
                                                        navigationBar: CupertinoNavigationBar(
                                                            middle: Text('Page 2 of tab $index'),
                                                        ),
                                                        child: Center(
                                                            child: CupertinoButton(
                                                                child: const Text('Back'),
                                                                    onPressed: () {
                                                                        Navigator.of(context).pop();
                                                                    },
                                                            ),
                                                        ),
                                                    );
                                                },
                                            ),
                                        );
                                    },
                            ),
                        ),
                    );
                },
            );
        },
    );
}
</code>```

}

答:
Not sure why it must be in the MaterialApp.  This solution is what I have deployed in the past:

In your MaterialApp, SetupStuff (could be named anything) is set as your home or initialRoute.

```<code>class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      color: Colors.yellow[100],
      debugShowCheckedModeBanner: false,
      title: 'MyApp',
      theme: currentTheme,
      home: SetupStuff(),
    );
  }
}

class SetupStuff extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //  This is the first 'context' with a MediaQuery, therefore,
    //  this is the first opportunity to set MediaQuery based values

    //Set values / do things here.

    WidgetsBinding.instance.addPostFrameCallback((_) {
      Navigator.pushReplacement(context,
          MaterialPageRoute(builder: (BuildContext context) => AlsoMyApp()));
    });

    return SafeArea(child: Material(color: Colors.yellow[300]));
  }
}
</code>```

Body:
I deleted the 'MaterialApp' code block because I couldn't write the codes I wanted at the beginning.

Now it gives an error, how can I fix this? I have to handle this in a very short time, I have to put the codes I wrote in the "MaterialApp" block, but I can't.

Can you help me ?

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
    return CupertinoTabScaffold(
        tabBar: CupertinoTabBar(
            items: < BottomNavigationBarItem > [
                new BottomNavigationBarItem(
                    icon: new Icon(Icons.home),
                    title: Text('Enes'),
                ),
                new BottomNavigationBarItem(
                    icon: new Icon(Icons.bluetooth),
                    title: Text('Mehmet'),
                ),
            ],
        ),
        tabBuilder: (BuildContext context, int index) {
            return CupertinoTabView(
                builder: (BuildContext context) {
                    return CupertinoPageScaffold(
                        navigationBar: CupertinoNavigationBar(
                            middle: Text('Page 1 of tab $index'),
                        ),
                        child: Center(
                            child: CupertinoButton(
                                child: const Text('Next Page'),
                                    onPressed: () {
                                        Navigator.of(context).push(
                                            CupertinoPageRoute < void > (
                                                builder: (BuildContext context) {
                                                    return CupertinoPageScaffold(
                                                        navigationBar: CupertinoNavigationBar(
                                                            middle: Text('Page 2 of tab $index'),
                                                        ),
                                                        child: Center(
                                                            child: CupertinoButton(
                                                                child: const Text('Back'),
                                                                    onPressed: () {
                                                                        Navigator.of(context).pop();
                                                                    },
                                                            ),
                                                        ),
                                                    );
                                                },
                                            ),
                                        );
                                    },
                            ),
                        ),
                    );
                },
            );
        },
    );
}

}

Body:
Not sure why it must be in the MaterialApp.  This solution is what I have deployed in the past:

In your MaterialApp, SetupStuff (could be named anything) is set as your home or initialRoute.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      color: Colors.yellow[100],
      debugShowCheckedModeBanner: false,
      title: 'MyApp',
      theme: currentTheme,
      home: SetupStuff(),
    );
  }
}

class SetupStuff extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //  This is the first 'context' with a MediaQuery, therefore,
    //  this is the first opportunity to set MediaQuery based values

    //Set values / do things here.

    WidgetsBinding.instance.addPostFrameCallback((_) {
      Navigator.pushReplacement(context,
          MaterialPageRoute(builder: (BuildContext context) => AlsoMyApp()));
    });

    return SafeArea(child: Material(color: Colors.yellow[300]));
  }
}


问:
How can I center align in pandas dataframe only cell that i want
```<code>writer=pd.ExcelWriter('Data.xlsx',engine='openpyxl')
emptydf.to_excel(writer,sheet_name=('Sheet1'),na_rep='-')
concat5.to_excel(writer,sheet_name=('Sheet2'),na_rep='-')
workbook=writer.book
writer.save()
</code>```

What I want is align to center only cells that "-". It is aligned to left right now.
I want to know how i could this.
Thank you.

答:
This is an openpyxl solution:

```<code>from openpyxl.styles import Alignment
from openpyxl import load_workbook

wb = load_workbook('Data.xlsx')
ws_names=wb.get_sheet_names()

for ws_name in ws_names:
    for row_cells in wb.get_sheet_by_name(ws_name):
        for cell in row_cells:
            if cell.value == '-':
                cell.alignment = Alignment(horizontal='center')

wb.save('Data.xlsx')
wb.close()
</code>```

Body:
writer=pd.ExcelWriter('Data.xlsx',engine='openpyxl')
emptydf.to_excel(writer,sheet_name=('Sheet1'),na_rep='-')
concat5.to_excel(writer,sheet_name=('Sheet2'),na_rep='-')
workbook=writer.book
writer.save()

What I want is align to center only cells that "-". It is aligned to left right now.
I want to know how i could this.
Thank you.

Body:
This is an openpyxl solution:

from openpyxl.styles import Alignment
from openpyxl import load_workbook

wb = load_workbook('Data.xlsx')
ws_names=wb.get_sheet_names()

for ws_name in ws_names:
    for row_cells in wb.get_sheet_by_name(ws_name):
        for cell in row_cells:
            if cell.value == '-':
                cell.alignment = Alignment(horizontal='center')

wb.save('Data.xlsx')
wb.close()


问:
How to extract a substring from a string in a column, that matches another string in a list in python
I have a dataframe which is as follows:

```<code>     col 1                                     col 2
0       59       538 Walton Avenue, Chester, FY6 7NP
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP
</code>```

With a list similar to:

```<code>[Stevenage, Essex, Coventry, Chester]
</code>```

Following the solution from here: How to check if Pandas rows contain any full string or substring of a list? which went like this:

```<code>city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')
</code>```

I found that some in col 2 match the strings in a list but that the col3 is the same as col2. I want col3 to be the values in the list rather the same as col3. This would be:

```<code>     col 1                                     col 2     col3
0       59       538 Walton Avenue, Chester, FY6 7NP  Chester
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT    Essex
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP Coventry
</code>```

I have tried:

```<code>pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))
</code>```

But this returned an error saying 456 inputs when expecting 1.

Also:

```<code>df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)
</code>```

But this came back with the error list index out of range.

Is there anyway to do this? df1 is around 160,000 entries with each address in col2 from different countries so there is no standard way they are written, while the city list is around 170,000 entries

Thank you

答:
Lean on an auxiliary function like this:</p>

```<code>df = pd.DataFrame({'col 1': [59, 62, 179, 180],
                   'col 2': ['538 Walton Avenue, Chester, FY6 7NP',
                             '42 Chesterton Road, Peterborough, FR7 2NY',
                             '3 Wallbridge Street, Essex, 4HG 3HT',
                             '6 Stevenage Avenue, Coventry, 7PY 9NP'
                             ]})

def aux_func(x):

    # split by comma and select the interesting part ([1])
    x = x.split(',')
    x = x[1]

    aux_list = ['Stevenage', 'Essex', 'Coventry', 'Chester']
    for v in aux_list:
        if v in x:
            return v
    return ""

df['col 3'] = [aux_func(name) for name in df['col 2']]
</code>```

Body:
I have a dataframe which is as follows:

     col 1                                     col 2
0       59       538 Walton Avenue, Chester, FY6 7NP
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP

With a list similar to:

[Stevenage, Essex, Coventry, Chester]

Following the solution from here: How to check if Pandas rows contain any full string or substring of a list? which went like this:

city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')

I found that some in col 2 match the strings in a list but that the col3 is the same as col2. I want col3 to be the values in the list rather the same as col3. This would be:

     col 1                                     col 2     col3
0       59       538 Walton Avenue, Chester, FY6 7NP  Chester
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT    Essex
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP Coventry

I have tried:

pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))

But this returned an error saying 456 inputs when expecting 1.

Also:

df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)

But this came back with the error list index out of range.

Is there anyway to do this? df1 is around 160,000 entries with each address in col2 from different countries so there is no standard way they are written, while the city list is around 170,000 entries

Thank you

Body:
Lean on an auxiliary function like this:

df = pd.DataFrame({'col 1': [59, 62, 179, 180],
                   'col 2': ['538 Walton Avenue, Chester, FY6 7NP',
                             '42 Chesterton Road, Peterborough, FR7 2NY',
                             '3 Wallbridge Street, Essex, 4HG 3HT',
                             '6 Stevenage Avenue, Coventry, 7PY 9NP'
                             ]})

def aux_func(x):

    # split by comma and select the interesting part ([1])
    x = x.split(',')
    x = x[1]

    aux_list = ['Stevenage', 'Essex', 'Coventry', 'Chester']
    for v in aux_list:
        if v in x:
            return v
    return ""

df['col 3'] = [aux_func(name) for name in df['col 2']]


问:
alignment of ggplots in a modularized shiny app
I have a modularized shiny app that displays in real time 4 variables. The monitor module takes as an input one big data frame, and displays the signal assigned. The 4 modules are stacked together in the ui:

```<code>    tabBox(id = "monitoring_tabBox",
           height = monitor_height_px,
           width = "500px",
           tabPanel(id = "layout1",
             title = "Layout 1",
             monitorModuleUI("sbto2"),
             monitorModuleUI("icp"),
             monitorModuleUI("map"),
             monitorModuleUI("ptio2")
           )
    ),
</code>```

The problem is the following: the plots are not perfectly aligned across modules. Mainly because the y ticks values have different ranges (see how the icp and the ptio2 are aligned because both signals have two digits, without decimals)

I've seen several techniques to align ggplots but you need to take as an input the 4 plots, and then merge them all in a single plot / render. I would like to avoid this step to keep the modularized structure of the app.

Is there any way I can align those plots without having to marge them together? (i.e by constraining the length of the y ticks)

Thank you in advance !

Screenshot:

screenshot showing the 4 modules and the misalignment issue

Reproducible example:

```<code>library(shiny)
library(dplyr)
library(ggplot2)
library(tidyr)

# Sample Data

df <- data.frame(timestamp = seq(as.POSIXct("2020-06-01 10:00:00"), as.POSIXct("2020-06-01 12:00:00"), "1 min"),
                 sbto2 = round(10000*rnorm(121, 0, 2), 1),
                 map = round(100*rnorm(121, 0, 2), 1),
                 icp = round(10*rnorm(121, 0, 1.5), 1),
                 ptio2 = round(1000*rnorm(121, 0, 1.2), 1))

# monitorModule

monitorModuleUI <- function(id){

  ns <- NS(id)

  fluidRow(
    column(8,
           plotOutput(ns("monitoring_plot"),
                      height = "150px")
    ),
    column(2,
           uiOutput(ns("monitoring_text"))
    )
  )

}

monitorModule <- function(input, output, server, variable_name, df){

  output$monitoring_plot <- renderPlot({
    p()
  })

  p <- reactive({
    df %>%
      gather("var", "value",seq(2,5)) %>%
      filter(var == variable_name) %>%
      ggplot(aes(x = timestamp, y = value)) + geom_line() -> p

    return(p)
  })

  output$monitoring_text <- renderUI({
    value <- p()$data$value[nrow(p()$data)]
    h1(strong(paste(value)), style = "font-size:90;")
  })

}

# APP

ui <- shinyServer(fluidPage(

  monitorModuleUI("sbto2"),
  monitorModuleUI("icp"),
  monitorModuleUI("ptio2"),
  monitorModuleUI("map")

))

server <- shinyServer(function(input, output, session){

  callModule(monitorModule, "sbto2", "sbto2", df)
  callModule(monitorModule, "icp", "icp", df)
  callModule(monitorModule, "ptio2", "ptio2", df)
  callModule(monitorModule, "map", "map", df)

})

shinyApp(ui=ui,server=server)

</code>```

答:
One alternative would be to return a reactive plot from each module and then to organize them with the package {patchwork}.

Here's an example:

```<code>library(shiny)
library(dplyr)
library(ggplot2)
library(tidyr)
library(patchwork)

# Sample Data

df <- data.frame(timestamp = seq(as.POSIXct("2020-06-01 10:00:00"), as.POSIXct("2020-06-01 12:00:00"), "1 min"),
                 sbto2 = round(10000*rnorm(121, 0, 2), 1),
                 map = round(100*rnorm(121, 0, 2), 1),

                              icp = round(10*rnorm(121, 0, 1.5), 1),
                 ptio2 = round(1000*rnorm(121, 0, 1.2), 1))

# monitorModule

monitorModuleUI <- function(id){
  # ns <- NS(id)
  # plotOutput(ns("monitoring_plot"),
  #            height = "150px")
}

monitorModule <- function(input, output, server, variable_name, df){

  test <- reactive({
    df %>%
      gather("var", "value",seq(2,5)) %>%
      filter(var == variable_name) %>%
      ggplot(aes(x = timestamp, y = value)) + geom_line() -> p

    return(p)
  })

}

# APP

ui <- fluidPage(

  monitorModuleUI("sbto2"),
  monitorModuleUI("icp"),
  monitorModuleUI("ptio2"),
  monitorModuleUI("map"),

  plotOutput("all_plots")

)

server <- function(input, output, session){

  plot_1 <- callModule(monitorModule, "sbto2", "sbto2", df)
  plot_2 <- callModule(monitorModule, "icp", "icp", df)
  plot_3 <- callModule(monitorModule, "ptio2", "ptio2", df)
  plot_4 <- callModule(monitorModule, "map", "map", df)

  output$all_plots <- renderPlot({
    plot_1() / plot_2() / plot_3() / plot_4()
 })

}

shinyApp(ui=ui,server=server)
</code>```

Body:
I have a modularized shiny app that displays in real time 4 variables. The monitor module takes as an input one big data frame, and displays the signal assigned. The 4 modules are stacked together in the ui:

    tabBox(id = "monitoring_tabBox",
           height = monitor_height_px,
           width = "500px",
           tabPanel(id = "layout1",
             title = "Layout 1",
             monitorModuleUI("sbto2"),
             monitorModuleUI("icp"),
             monitorModuleUI("map"),
             monitorModuleUI("ptio2")
           )
    ),

The problem is the following: the plots are not perfectly aligned across modules. Mainly because the y ticks values have different ranges (see how the icp and the ptio2 are aligned because both signals have two digits, without decimals)

I've seen several techniques to align ggplots but you need to take as an input the 4 plots, and then merge them all in a single plot / render. I would like to avoid this step to keep the modularized structure of the app.

Is there any way I can align those plots without having to marge them together? (i.e by constraining the length of the y ticks)

Thank you in advance !

Screenshot:

screenshot showing the 4 modules and the misalignment issue

Reproducible example:

library(shiny)
library(dplyr)
library(ggplot2)
library(tidyr)

# Sample Data

df <- data.frame(timestamp = seq(as.POSIXct("2020-06-01 10:00:00"), as.POSIXct("2020-06-01 12:00:00"), "1 min"),
                 sbto2 = round(10000*rnorm(121, 0, 2), 1),
                 map = round(100*rnorm(121, 0, 2), 1),
                 icp = round(10*rnorm(121, 0, 1.5), 1),
                 ptio2 = round(1000*rnorm(121, 0, 1.2), 1))

# monitorModule

monitorModuleUI <- function(id){

  ns <- NS(id)

  fluidRow(
    column(8,
           plotOutput(ns("monitoring_plot"),
                      height = "150px")
    ),
    column(2,
           uiOutput(ns("monitoring_text"))
    )
  )

}

monitorModule <- function(input, output, server, variable_name, df){

  output$monitoring_plot <- renderPlot({
    p()
  })

  p <- reactive({
    df %>%
      gather("var", "value",seq(2,5)) %>%
      filter(var == variable_name) %>%
      ggplot(aes(x = timestamp, y = value)) + geom_line() -> p

    return(p)
  })

  output$monitoring_text <- renderUI({
    value <- p()$data$value[nrow(p()$data)]
    h1(strong(paste(value)), style = "font-size:90;")
  })

}

# APP

ui <- shinyServer(fluidPage(

  monitorModuleUI("sbto2"),
  monitorModuleUI("icp"),
  monitorModuleUI("ptio2"),
  monitorModuleUI("map")

))

server <- shinyServer(function(input, output, session){

  callModule(monitorModule, "sbto2", "sbto2", df)
  callModule(monitorModule, "icp", "icp", df)
  callModule(monitorModule, "ptio2", "ptio2", df)
  callModule(monitorModule, "map", "map", df)

})

shinyApp(ui=ui,server=server)

Body:
One alternative would be to return a reactive plot from each module and then to organize them with the package {patchwork}.

Here's an example:

library(shiny)
library(dplyr)
library(ggplot2)
library(tidyr)
library(patchwork)

# Sample Data

df <- data.frame(timestamp = seq(as.POSIXct("2020-06-01 10:00:00"), as.POSIXct("2020-06-01 12:00:00"), "1 min"),
                 sbto2 = round(10000*rnorm(121, 0, 2), 1),
                 map = round(100*rnorm(121, 0, 2), 1),

                              icp = round(10*rnorm(121, 0, 1.5), 1),
                 ptio2 = round(1000*rnorm(121, 0, 1.2), 1))

# monitorModule

monitorModuleUI <- function(id){
  # ns <- NS(id)
  # plotOutput(ns("monitoring_plot"),
  #            height = "150px")
}

monitorModule <- function(input, output, server, variable_name, df){

  test <- reactive({
    df %>%
      gather("var", "value",seq(2,5)) %>%
      filter(var == variable_name) %>%
      ggplot(aes(x = timestamp, y = value)) + geom_line() -> p

    return(p)
  })

}

# APP

ui <- fluidPage(

  monitorModuleUI("sbto2"),
  monitorModuleUI("icp"),
  monitorModuleUI("ptio2"),
  monitorModuleUI("map"),

  plotOutput("all_plots")

)

server <- function(input, output, session){

  plot_1 <- callModule(monitorModule, "sbto2", "sbto2", df)
  plot_2 <- callModule(monitorModule, "icp", "icp", df)
  plot_3 <- callModule(monitorModule, "ptio2", "ptio2", df)
  plot_4 <- callModule(monitorModule, "map", "map", df)

  output$all_plots <- renderPlot({
    plot_1() / plot_2() / plot_3() / plot_4()
 })

}

shinyApp(ui=ui,server=server)


问:
Browser not maintaining correct history in React Application
I am going in between pages in React Application, but on going back in the browser it skip some pages. Not taking to the right page when doing back. I am handling routing in my application like this:

```<code><BrowserRouter>
      <Route path="/dir/page1/" exact component={page1} />
      <Route path="/dir/page1" exact component={page2} />
      <Route path="/dir/page3" exact component={page3} />
      <Route path="/dir/:query" exact component={page4} />
      <Route path="/faq/" exact component={Faq} />
      <Route path="/about/" exact component={AboutUs} />
      <Route path="/terms/" exact component={Terms} />
      <Route path="/" exact component={Home} />
</BrowserRouter>
</code>```

How can i make my browser to follow correct back history and not skipping pages.

答: I was using window.location.replace(url); which was making it skip the page in the history. I changed it with window.location.href = url;

Body:
I am going in between pages in React Application, but on going back in the browser it skip some pages. Not taking to the right page when doing back. I am handling routing in my application like this:

<BrowserRouter>
      <Route path="/dir/page1/" exact component={page1} />
      <Route path="/dir/page1" exact component={page2} />
      <Route path="/dir/page3" exact component={page3} />
      <Route path="/dir/:query" exact component={page4} />
      <Route path="/faq/" exact component={Faq} />
      <Route path="/about/" exact component={AboutUs} />
      <Route path="/terms/" exact component={Terms} />
      <Route path="/" exact component={Home} />
</BrowserRouter>

How can i make my browser to follow correct back history and not skipping pages.


问:
Create new file from templates with bash script
I have to create conf files and init.d which are very similar. These files permit to deploy new HTTP service on my servers. These files are the same and only some parameters change from one file to another (listen_port, domain, and path on server.)

As any error in these files leads to dysfunction of service I would like to create these files using a bash script.

For example:

```<code>generate_new_http_service.sh 8282 subdomain.domain.example /home/myapp/rootOfHTTPService
</code>```

I am looking for a kind of templating module that I could use with bash. This templating module would use some generic conf and init.d scripts to create new ones.

Could I could use python templating engine?

答:
You can do this using a heredoc. e.g.

generate.sh:

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

#define parameters which are passed in.
PORT=$1
DOMAIN=$2

#define the template.
cat  << EOF
This is my template.
Port is $PORT
Domain is $DOMAIN
EOF
</code>```

Output:

```<code>$ generate.sh 8080 domain.example

This is my template.
Port is 8080
Domain is domain.example
</code>```

or save it to a file:

```<code>$ generate.sh 8080 domain.example > result
</code>```

Body:
I have to create conf files and init.d which are very similar. These files permit to deploy new HTTP service on my servers. These files are the same and only some parameters change from one file to another (listen_port, domain, and path on server.)

As any error in these files leads to dysfunction of service I would like to create these files using a bash script.

For example:

generate_new_http_service.sh 8282 subdomain.domain.example /home/myapp/rootOfHTTPService

I am looking for a kind of templating module that I could use with bash. This templating module would use some generic conf and init.d scripts to create new ones.

Could I could use python templating engine?

Body:
You can do this using a heredoc. e.g.

generate.sh:

#!/bin/sh

#define parameters which are passed in.
PORT=$1
DOMAIN=$2

#define the template.
cat  << EOF
This is my template.
Port is $PORT
Domain is $DOMAIN
EOF

Output:

$ generate.sh 8080 domain.example

This is my template.
Port is 8080
Domain is domain.example

or save it to a file:

$ generate.sh 8080 domain.example > result


问:
How to use uniqueConstraint on referenced table column with JPA
How can I include a referenced table column in a unique constraint? I want to create a unique constraint for table Survey for columns toEmail, receipt.receiptSeries and receipt.receiptNum.

See entities below please:

Receipt

```<code>@Entity
@Table(name = "RECEIPT")
public class Receipt {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "ID")
  private Long id;

  @Column(name = "RECEIPT_SERIES")
  private String receiptSeries;

  @Column(name = "RECEIPT_NUM")
  private String receiptNum;
}
</code>```

Survey

```<code>@Entity
@Table(name = "SURVEY"}
public class Survey {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "ID")
  private Long id;

  @ManyToOne(optional = false)
  @JoinColumn(name = "RECEIPT_ID")
  private Receipt receipt;

  @Column(name = "TO_EMAIL")
  private String toEmail;
}
</code>```

I've tried using the approach below with no success:

```<code>@Table(name = "SURVEY", uniqueConstraints = {
    @UniqueConstraint(columnNames = {"TO_EMAIL", "RECEIPT.RECEIPT_SERIES", "RECEIPT.RECEIPT_NUM"})})
</code>```

Using a composite primary key with receiptSeries and receiptNum for Receipt is not an option.

答:
Try something like this </p>

```<code>@Table(name="notification_status", uniqueConstraints=
       arrayOf(UniqueConstraint(columnNames= arrayOf("external_user_id",
                                                     "external_organization_id",
                                                     "notification_id"))))
</code>```

Body:
How can I include a referenced table column in a unique constraint? I want to create a unique constraint for table Survey for columns toEmail, receipt.receiptSeries and receipt.receiptNum.

See entities below please:

Receipt

@Entity
@Table(name = "RECEIPT")
public class Receipt {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "ID")
  private Long id;

  @Column(name = "RECEIPT_SERIES")
  private String receiptSeries;

  @Column(name = "RECEIPT_NUM")
  private String receiptNum;
}

Survey

@Entity
@Table(name = "SURVEY"}
public class Survey {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "ID")
  private Long id;

  @ManyToOne(optional = false)
  @JoinColumn(name = "RECEIPT_ID")
  private Receipt receipt;

  @Column(name = "TO_EMAIL")
  private String toEmail;
}

I've tried using the approach below with no success:

@Table(name = "SURVEY", uniqueConstraints = {
    @UniqueConstraint(columnNames = {"TO_EMAIL", "RECEIPT.RECEIPT_SERIES", "RECEIPT.RECEIPT_NUM"})})

Using a composite primary key with receiptSeries and receiptNum for Receipt is not an option.

Body:
Try something like this

@Table(name="notification_status", uniqueConstraints=
       arrayOf(UniqueConstraint(columnNames= arrayOf("external_user_id",
                                                     "external_organization_id",
                                                     "notification_id"))))