问:
PermissionError trying to use subprocess to call other program in Python
I want to make a interface, so I just tried to use subprocess module to call my program:

```<code>import subprocess
subprocess.call('/Users/TsuAngChou/MasterProject/Practice/try_test/TEST5.py')
</code>```

I tried to run it, but there was an error:

```<code>PermissionError: [Errno 13] Permission denied.
</code>```

What's going on in my code?

答:
You don't have permission to execute the script - probably because the script file does not have executable permission set for it.

Perhaps also it is missing the #!/usr/bin/env python (aka "shebang") at the top of test.py.

Try using chmod to set executable on the file:

```<code>$ chmod +x test.py
</code>```

and add the shebang at the top. Then makes sure that you can execute it from the command line:

```<code>$ ./test.py
</code>```

Also, it is often possible, and better, to import the code into your script and call the functions within it it.

Body:
I want to make a interface, so I just tried to use subprocess module to call my program:

import subprocess
subprocess.call('/Users/TsuAngChou/MasterProject/Practice/try_test/TEST5.py')

I tried to run it, but there was an error:

PermissionError: [Errno 13] Permission denied.

What's going on in my code?

Body:
You don't have permission to execute the script - probably because the script file does not have executable permission set for it.

Perhaps also it is missing the #!/usr/bin/env python (aka "shebang") at the top of test.py.

Try using chmod to set executable on the file:

$ chmod +x test.py

and add the shebang at the top. Then makes sure that you can execute it from the command line:

$ ./test.py

Also, it is often possible, and better, to import the code into your script and call the functions within it it.


来源: stackexchange

问:
new never fails?
In C++, we usually see and write code like,

```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

But in C#, I rarely see this: (at least I've never seen this)

```<code>Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}
</code>```

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

答:
I rarely see it in C++

It doesn't make sense in C#, because it simply will just throw an Exception

ContentLicense: CC BY-SA 2.5

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.


问:
yii redirect with array
```<code>$this->redirect(array($redirect, 'error' => $error, 'msg' => $msg, 'details' => $details));
</code>```

How can we pass array as a parameter?
I have tried during redirection.

Returning:

Error 400 Your request is invalid.

Any help would be appreciated.

答:
If redirect to different page

```<code>$this->redirect(array('YourController/YourFunction','error'=>$error,'msg'=>$msg,'details'=>$details));
</code>```

If in the same controller you just need to put your function on the array.
hope this can help

ContentLicense: CC BY-SA 3.0

Title: yii redirect with array

Body:
$this->redirect(array($redirect, 'error' => $error, 'msg' => $msg, 'details' => $details));

How can we pass array as a parameter?
I have tried during redirection.

Returning:

Error 400 Your request is invalid.

Any help would be appreciated.

Body:
If redirect to different page

$this->redirect(array('YourController/YourFunction','error'=>$error,'msg'=>$msg,'details'=>$details));

If in the same controller you just need to put your function on the array.
hope this can help


问:
Use find command but exclude files in two directories
I want to find files that end with _peaks.bed, but exclude files in the tmp and scripts folders.

My command is like this:

```<code> find . -type f \( -name "*_peaks.bed" ! -name "*tmp*" ! -name "*scripts*" \)
</code>```

But it didn't work. The files in tmp and script folder will still be displayed.

Does anyone have ideas about this?

答:
You can try below:

```<code>find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'
</code>```

Body:
I want to find files that end with _peaks.bed, but exclude files in the tmp and scripts folders.

My command is like this:

 find . -type f \( -name "*_peaks.bed" ! -name "*tmp*" ! -name "*scripts*" \)

But it didn't work. The files in tmp and script folder will still be displayed.

Does anyone have ideas about this?

Body:
You can try below:

find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'


问:
Merge Two Javascript Objects with Multiple Matches Per Key
I have two objects which I am trying to merge. I am almost successfully worked with answer from this question (Merge two unordered objects with different keys but same value?).

The issue is that in my "transpatterns" object, I have two patterns that match "Intercom" key. However, in my output, it only takes the second one. I need it to list both under the same key.

Here is my code:

var hash = {};

var partitions = [{
        '$': {
            uuid: '{0F314A21-B066-B597-BCFA-6EC88CF8813B}'
        },
        name: ['AllPhones']
    },
    {
        '$': {
            uuid: '{4DCF3A89-ADA1-2770-4154-F6E0204D9A71}'
        },
        name: ['Unity_Connection']
    },
    {
        '$': {
            uuid: '{B653BC00-2D90-790C-AE0D-16C3DD2F8EDD}'
        },
        name: ['LAB-Tansform-Calling']
    },
    {
        '$': {
            uuid: '{148C8971-87E4-49D3-1536-69B6C95293B3}'
        },
        name: ['Blocked']
    },
    {
        '$': {
            uuid: '{25534E0F-F69A-FDDB-2FAD-34312BB6CEFC}'
        },
        name: ['LAB-PSTN-Sim-911']
    },
    {
        '$': {
            uuid: '{EC1E144B-2C8C-22CC-F1F5-423CF0343367}'
        },
        name: ['LAB-PSTN-Sim-Local']
    },
    {
        '$': {
            uuid: '{9C7F3223-AE2D-7605-C642-0CEAB81CD555}'
        },
        name: ['LAB-PSTN-Sim-LD']
    },
    {
        '$': {
            uuid: '{15AFADC3-859B-2806-B9D1-5678CE035E3D}'
        },
        name: ['LAB-PSTN-Sim-Intl']
    },
    {
        '$': {
            uuid: '{5DD43CF0-5FB0-A6A0-A71D-D284265F37C7}'
        },
        name: ['Agents']
    },
    {
        '$': {
            uuid: '{7FDE7E11-F821-2491-BB08-E6A41DAB205D}'
        },
        name: ['UCCX']
    },
    {
        '$': {
            uuid: '{17500618-9567-92B9-8C15-95D794094A3F}'
        },
        name: ['Intercom']
    },
    {
        '$': {
            uuid: '{77049844-AB06-F899-26D0-C0940E20D4D5}'
        },
        name: ['Netech_Managers']
    },
    {
        '$': {
            uuid: '{A9DD47E0-1C4A-AAB9-E859-E6EEDB26E6B0}'
        },
        name: ['Assistant_Route_Point']
    }
];

var transpatterns = [{
        '$': {
            uuid: '{3FF82ECB-7364-41DB-176B-65D28885339F}'
        },
        pattern: ['9.19005554444'],
        description: ['Sample Outbound Call Block'],
        routePartitionName: ['Blocked']
    },
    {
        '$': {
            uuid: '{18C2C829-AFAE-DB28-A003-5F1731907D85}'
        },
        pattern: ['555555XXXX'],
        description: ['Inbound DID Range'],
        routePartitionName: ['AllPhones']
    },
    {
        '$': {
            uuid: '{465EFEF8-C405-8D30-2C97-4BF9907C92C6}'
        },
        pattern: ['3100'],
        description: ['Intercom Xlate'],
        routePartitionName: ['Intercom']
    },
    {
        '$': {
            uuid: '{C17E117C-41C7-D459-8CD1-B1D3C4EDC40D}'
        },
        pattern: ['3101'],
        description: ['Intercom Xlate'],
        routePartitionName: ['Intercom']
    }
];

// TESTING NEW
// COMBINE OBJECTS - CREATE HASH
function classify(e) {
    if (hash[e.name] || hash[e.routePartitionName]) {
        Object.keys(e).forEach(function (c) {
            hash[e.name || e.routePartitionName][c] = e[c];
        });
    } else {
        hash[e.routePartitionName || e.name] = e;
    }
}

// COMBINE OBJECTS - ADD VARS to HASH
partitions.forEach(classify);
transpatterns.forEach(classify);

// COMBINE OBJECTS - ITERATE HASH + REMOVE ANY FIELDS
var combo = Object.keys(hash).map(function (e) {
    delete hash[e]['routePartitionName'];
    return hash[e];
});

console.log(combo);```

答:
I was able to solve my problem. I determined that I needed to collapse the object with multiple items associated with the same key before I merged the two objects. I was able to use the answer from this question to help me do this.
How to combine JSON object with same key and add their other corresponding values?

Here is the code I came up with that seems to work nicely.

// DEFINE VARIABLES
var partitions = [{
        '$': {
            uuid: '{0F314A21-B066-B597-BCFA-6EC88CF8813B}'
        },
        name: ['AllPhones']
    },
    {
        '$': {
            uuid: '{4DCF3A89-ADA1-2770-4154-F6E0204D9A71}'
        },
        name: ['Unity_Connection']
    },
    {
        '$': {
            uuid: '{B653BC00-2D90-790C-AE0D-16C3DD2F8EDD}'
        },
        name: ['LAB-Tansform-Calling']
    },
    {
        '$': {
            uuid: '{148C8971-87E4-49D3-1536-69B6C95293B3}'
        },
        name: ['Blocked']
    },
    {
        '$': {
            uuid: '{25534E0F-F69A-FDDB-2FAD-34312BB6CEFC}'
        },
        name: ['LAB-PSTN-Sim-911']
    },
    {
        '$': {
            uuid: '{EC1E144B-2C8C-22CC-F1F5-423CF0343367}'
        },
        name: ['LAB-PSTN-Sim-Local']
    },
    {
        '$': {
            uuid: '{9C7F3223-AE2D-7605-C642-0CEAB81CD555}'
        },
        name: ['LAB-PSTN-Sim-LD']
    },
    {
        '$': {
            uuid: '{15AFADC3-859B-2806-B9D1-5678CE035E3D}'
        },
        name: ['LAB-PSTN-Sim-Intl']
    },
    {
        '$': {
            uuid: '{5DD43CF0-5FB0-A6A0-A71D-D284265F37C7}'
        },
        name: ['Agents']
    },
    {
        '$': {
            uuid: '{7FDE7E11-F821-2491-BB08-E6A41DAB205D}'
        },
        name: ['UCCX']
    },
    {
        '$': {
            uuid: '{17500618-9567-92B9-8C15-95D794094A3F}'
        },
        name: ['Intercom']
    },
    {
        '$': {
            uuid: '{77049844-AB06-F899-26D0-C0940E20D4D5}'
        },
        name: ['Netech_Managers']
    },
    {
        '$': {
            uuid: '{A9DD47E0-1C4A-AAB9-E859-E6EEDB26E6B0}'
        },
        name: ['Assistant_Route_Point']
    }
];

var transpatterns = [{
        '$': {
            uuid: '{3FF82ECB-7364-41DB-176B-65D28885339F}'
        },
        pattern: ['9.19005554444'],
        description: ['Sample Outbound Call Block'],
        routePartitionName: ['Blocked']
    },
    {
        '$': {
            uuid: '{18C2C829-AFAE-DB28-A003-5F1731907D85}'
        },
        pattern: ['555555XXXX'],
        description: ['Inbound DID Range'],
        routePartitionName: ['AllPhones']
    },
    {
        '$': {
            uuid: '{465EFEF8-C405-8D30-2C97-4BF9907C92C6}'
        },
        pattern: ['3100'],
        description: ['Intercom Xlate'],
        routePartitionName: ['Intercom']
    },
    {
        '$': {
            uuid: '{C17E117C-41C7-D459-8CD1-B1D3C4EDC40D}'
        },
        pattern: ['3101'],
        description: ['Intercom Xlate'],
        routePartitionName: ['Intercom']
    }
];

var hash = {};

// FUNCTION - COMBINE ITEMS WITHIN OBJECT - WITH SAME KEY:routePartitionName
function combine(arr) {
    var combined = arr.reduce(function (result, item) {
        var current = result[item.routePartitionName];

        result[item.routePartitionName] = !current ? item : {
            pattern: current.pattern + ',' + item.pattern,
            description: item.description,
            routePartitionName: item.routePartitionName
        };

        return result;
    }, {});

    return Object.keys(combined).map(function (key) {
        return combined[key];
    });
}

// FUNCTION - COMBINE ITEMS WITHIN OBJECT - RUN
var result = combine(transpatterns);

// FUNCTION - COMBINE OBJECTS - CREATE HASH
function classify(e) {
    if (hash[e.name] || hash[e.routePartitionName]) {
        Object.keys(e).forEach(function (c) {
            hash[e.name || e.routePartitionName][c] = e[c];
        });
    } else {
        hash[e.routePartitionName || e.name] = e;
    }
}

// FUNCTION - COMBINE OBJECTS - ADD VARS to HASH
partitions.forEach(classify);
result.forEach(classify);

// FUNCTION - COMBINE OBJECTS - ITERATE HASH + REMOVE ANY FIELDS
var combo = Object.keys(hash).map(function (e) {
    delete hash[e]['routePartitionName'];
    delete hash[e]['$'];
    return hash[e];
});

console.log(combo);```


问:
High Quality Audio Recording in Web Browser
One line version:

What open source software (WAMI-Recorder)/web browser (via getUserMedia) will give me the best quality audio recordings?

High quality would be defined as (44.1 or 48 sample rate) and 16 bit sample size.

More Information:

So currently my solution is WAMI-Recorder, but I am wondering if the HTML5 specification has matured to a point in browser such that I can record without Flash and get equal or higher quality audio recordings. Currently it looks like WAMI maxes out at 22050.

I do not need cross browser support as this is for internal business use.

A non-Flash solution would also be preferred.

答:
If you use Chrome Web Browser, and as you ask for High Quality Audio Recording, you probably be better to build a native client module, you may take a look here (chrome developper native client dev guide):

Selecting a sample frame count for an audio stream involves a tradeoff between latency and CPU usage. If you want your module to have short audio latency so that it can rapidly change what’s playing in the audio stream, you should request a small sample frame count.

[...]

After the module obtains a sample frame count, it can create an audio
configuration resource. Currently the Pepper audio API supports audio
streams with the configuration settings shown above

And here you will find audio configuration which fit your requirements

The Pepper audio API currently lets Native Client modules play audio streams with the following configurations:

sample rate: 44,100 Hz or 48,000 Hz

bit depth: 16

channels: 2 (stereo)

This official link could be also helpful.

Regards


问:
Need two return an activerecord relation from two queries
I have this two queries on my database

```<code>incidents = Incident.arel_table

Incident.where(incidents[:client_id].in(client_ids_including_descendants(false)))

Incident.joins(:incident_support_requests)
        .where(incident_support_requests: {
                 provider_type: 'SocProvider',
                 provider_id: self.soc_provider_ids,
                 state: 'opened'})
</code>```

And I need to join in one ActiveRecord::Relation, without calculating intermediate queries (ie with a +) I followed the answers from here
How do I combine results from two queries on the same model?

when trying to join this two queries with should be an or the results from one plus the results form the other I always get couldn't visis active record relation

but I couldn't get it

答:
What about?</p>

```<code>incid1 = ...
incid2 = ...

incids = Incident.where(id: incid1.pluck(&:id) + incid2.pluck(&:id))
</code>```

Body:
I have this two queries on my database

incidents = Incident.arel_table

Incident.where(incidents[:client_id].in(client_ids_including_descendants(false)))

Incident.joins(:incident_support_requests)
        .where(incident_support_requests: {
                 provider_type: 'SocProvider',
                 provider_id: self.soc_provider_ids,
                 state: 'opened'})

And I need to join in one ActiveRecord::Relation, without calculating intermediate queries (ie with a +) I followed the answers from here
How do I combine results from two queries on the same model?

when trying to join this two queries with should be an or the results from one plus the results form the other I always get couldn't visis active record relation

but I couldn't get it

Body:
What about?

incid1 = ...
incid2 = ...

incids = Incident.where(id: incid1.pluck(&:id) + incid2.pluck(&:id))


问:
ggplot2 labeling scatter points in R
Trying to Label my scatter points in R. This is my first plot, very straight forward but can't seem to figure out adding text. I've looked at some of the other posts in here and they partially make sense but i just don't understand the lingo yet.  </p>

```<code>stats <- read.csv(file.choose())
qplot(data=stats, x=Avg.of.FD.Points, y=Avg.FD.Dev)
text(x, y, label=Home.Skater)

Home.Skater   Avg.of.FD.Points  Avg.FD.Dev
A.J. Greer    |   4.27        | 2.84
Aaron Ekblad  |   12.40       | 6.22
Aaron Ness    |   5.60        | 4.00
</code>```

答:
Here is a simple scatterplot example with geom_text based on your sample data.

```<code>df <- read.table(text =
    "Home.Skater      Avg.FD.PTS   Avg.FD.Dev
    A.J._Greer       4.27       2.84
    Aaron_Ekblad     12.40      6.22
    Aaron_Ness       5.60       4.00", header = T);

require(ggplot2);
ggplot(df, aes(x = Avg.FD.PTS, y = Avg.FD.Dev, label = Home.Skater)) +
    geom_point() +
    geom_text(hjust = 0, nudge_x = 0.05) +
    xlim(0, 15);
</code>```

To avoid cluttering of (many) labels, you may want to consider the R library ggrepel.

Title: ggplot2 labeling scatter points in R

Body:
Trying to Label my scatter points in R. This is my first plot, very straight forward but can't seem to figure out adding text. I've looked at some of the other posts in here and they partially make sense but i just don't understand the lingo yet.

stats <- read.csv(file.choose())
qplot(data=stats, x=Avg.of.FD.Points, y=Avg.FD.Dev)
text(x, y, label=Home.Skater)

Home.Skater   Avg.of.FD.Points  Avg.FD.Dev
A.J. Greer    |   4.27        | 2.84
Aaron Ekblad  |   12.40       | 6.22
Aaron Ness    |   5.60        | 4.00

Body:
Here is a simple scatterplot example with geom_text based on your sample data.

df <- read.table(text =
    "Home.Skater      Avg.FD.PTS   Avg.FD.Dev
    A.J._Greer       4.27       2.84
    Aaron_Ekblad     12.40      6.22
    Aaron_Ness       5.60       4.00", header = T);

require(ggplot2);
ggplot(df, aes(x = Avg.FD.PTS, y = Avg.FD.Dev, label = Home.Skater)) +
    geom_point() +
    geom_text(hjust = 0, nudge_x = 0.05) +
    xlim(0, 15);

To avoid cluttering of (many) labels, you may want to consider the R library ggrepel.


问:
Is it possible to use tox with conda-based Python installations?
The Python testing tool tox seems to be designed to work with virtualenv. Can it also work on conda/anaconda-based Python installations?

答:
I made tox and conda work together in Windows by:

Installing virtualenv with conda in the environment which I use tox:

conda install virtualenv

Creating "Directory Junction" symlinks from C:\PythonXY to my actual environment path. This gets around the InterpreterNotFound-error:

mklink /J C:\PythonXY C:\real\path\to\myPythonXYenv

I have installed Anaconda in E:\Anaconda3\, and all my environments in E:\Anaconda3\envs\, e.g. E:\Anaconda3\envs\py27\

(See below for a script to make this quick and easy.)

Step 1 - Create environments with conda:

```<code>E:\dev> conda create -n py27 python=2.7 --yes
E:\dev> conda create -n py33 python=3.3 --yes
...
E:\dev> conda create -n py36 python=3.6 --yes
</code>```

Step 2 - Create all the symlinks:

```<code>E:\dev> mklink /J C:\Python27 E:\Anaconda3\envs\py27
E:\dev> mklink /J C:\Python33 E:\Anaconda3\envs\py33
...
E:\dev> mklink /J C:\Python36 E:\Anaconda3\envs\py36
</code>```

Note: I call conda create from a directory on the E-drive, so the --prefix/-p option is not required in order to install new environments in E:\Anaconda3\envs\.

An Easier Way:

Instead of going through the cumbersome process of setting this up for each environment/python version, one can use the ToxEnvMatcher-class added further down in this manner:

```<code>my_envs = os.path.join('E:\\', 'Anaconda3', 'envs')
tem = ToxEnvMatcher(my_envs)
for version in '27,34,35,36'.split(','):
    tem.make(version)
</code>```

Edit: To make the script easier to use, I've added a new section to the file, (here assumed to be tox_with_conda.py,) so it can be called from cmd.exe:

```<code>C:\dev> python tox_with_conda.py E:\Anaconda3\envs 27 34 35 36 37
</code>```

Edit 2: Can also be installed with pip: pip install tox_with_conda and used as:

```<code>C:\dev> python -m tox_with_conda E:\Anaconda3\envs 27 34 35 36 37
</code>```

I'm using Python 3.6.3 and tox 2.9.1, but I don't know when/if earlier versions work too.

Defence:
I assume that to some, this seems like a too cumbersome process (it's really not, though), or to much of a hack. But keep in mind that being able to use Anaconda/conda also reduces waste of time spent trying to install libraries, packages, ++++.

Please note:

I use tox with pytest, and have not noticed any impacts on my tests.

My tests are simple, and there is a chance I just haven't been exposed to issues yet.

Assumable, there are things I haven't thought of that might be relevant for others.

The class (also available here):

```<code>from subprocess import run
from os.path import join

DEFAULT_BASE = join('C:\\', 'Python')

class ToxEnvMatcher:
    """
    Utility to make conda environments work with tox.

    Conda envs might be in other locations than where `tox <https://tox.readthedocs.io>`_ expects them to be.

    A symbolic link 'Directory Junction' is created from expected location to the actual location.
    Intended for Windows to get around the ``InterpreterNotFound``-error.

    E.g.: tox expects to find Python 2.7 in ``C:\Python27``,
    but may actually be installed in another drive and location.

    Examples of use:

    .. code-block:: python

        my_envs = join('E:\\', 'Anaconda3', 'envs')
        tem = ToxEnvMatcher(my_envs)
        for version in '27,34,35,36'.split(','):
            tem.make(version)

    The class is utilized through ``argsparse`` so it can also be used from cmd.exe.

    Examples of use of th of using ``ToxEnvMatcher`` from cmd.exe:

    .. code-block:: none

        E:\dev> tox_with_conda.py E:\Anaconda3\envs 27 34 35 36 37

    It's possible to use the ``-b``/``--base`` option to override the default base location (``C:\Python``):

    .. code-block:: none

        E:\dev> tox_with_conda.py E:\Anaconda3\envs 27 34 35 36 37 --base D:\Python

    :param str envs_dir: The path to where new conda environments will be created
    :param str default_base: The base of the 'default' location. Usually it's ``C:\Python``
    """
    def __init__(self, envs_dir, default_base=DEFAULT_BASE):
        self.envs_dir = envs_dir
        self.default_base = default_base

    def __repr__(self):
        return '{}({})'.format(self.__class__.__name__, self.envs_dir)

    def make(self, version):
        """
        Take version and create conda environment with symlink from 'default tox location'.

        E.g.: given version='27' and environment folder ``{self.envs_dir}``:

         - ``conda create -p {self.envs_dir}\py27 python=2.7``
         - ``mklink /J C:\Python27 {self.envs_dir}\py27``

        :param str version: A string on the form 'XY', e.g. '27' or '36'
        :return: None
        :rtype: NoneType
        """
        if len(version) != 2 or not int(version):
            raise ValueError("Parameter 'version' must be on the form 'XY', and not '{}'".format(version))
        conda_cmd = self._create_cmd_args(version)
        symlink_cmd = self._create_symlink_args(version)
        run(conda_cmd, shell=True)
        run(symlink_cmd, shell=True)

    def _get_env_folder(self, version):
        return join(self.envs_dir, 'py{}'.format(version))

    def _create_cmd_args(self, version):
        env_dir = self._get_env_folder(version)
        python_version = '.'.join(version)
        conda_create = 'conda create -p {} python={} --yes'.format(env_dir, python_version)
        return conda_create.split(' ')

    def _create_symlink_args(self, version):
        env_dir = self._get_env_folder(version)
        return 'mklink /J {}{} {}'.format(self.default_base, version, env_dir).split(' ')
</code>```

The added code for making it work from cmd is:

```<code>if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("env_dir",
                        help="The folder where conda environments should be installed.")
    parser.add_argument("versions", nargs='*',
                        help="The list of versions, formatted 'XY' where X is major and Y minor. E.g. '27 35 36'")
    parser.add_argument("-b", "--base", default=DEFAULT_BASE,
                        help="Base of the path which tox expects to find Python installed. "
                             "Default: {}.".format(DEFAULT_BASE))
    args = parser.parse_args()

    print('env_dir: ', args.env_dir)
    print('versions: ', args.versions)
    print('--base: ', args.base)

    tem = ToxEnvMatcher(args.env_dir, default_base=args.base)
    for version in args.versions:
        tem.make(version)
</code>```

Body:
I made tox and conda work together in Windows by:

Installing virtualenv with conda in the environment which I use tox:

conda install virtualenv

Creating "Directory Junction" symlinks from C:\PythonXY to my actual environment path. This gets around the InterpreterNotFound-error:

mklink /J C:\PythonXY C:\real\path\to\myPythonXYenv

I have installed Anaconda in E:\Anaconda3\, and all my environments in E:\Anaconda3\envs\, e.g. E:\Anaconda3\envs\py27\

(See below for a script to make this quick and easy.)

Step 1 - Create environments with conda:

E:\dev> conda create -n py27 python=2.7 --yes
E:\dev> conda create -n py33 python=3.3 --yes
...
E:\dev> conda create -n py36 python=3.6 --yes

Step 2 - Create all the symlinks:

E:\dev> mklink /J C:\Python27 E:\Anaconda3\envs\py27
E:\dev> mklink /J C:\Python33 E:\Anaconda3\envs\py33
...
E:\dev> mklink /J C:\Python36 E:\Anaconda3\envs\py36

Note: I call conda create from a directory on the E-drive, so the --prefix/-p option is not required in order to install new environments in E:\Anaconda3\envs\.

An Easier Way:

Instead of going through the cumbersome process of setting this up for each environment/python version, one can use the ToxEnvMatcher-class added further down in this manner:

my_envs = os.path.join('E:\\', 'Anaconda3', 'envs')
tem = ToxEnvMatcher(my_envs)
for version in '27,34,35,36'.split(','):
    tem.make(version)

Edit: To make the script easier to use, I've added a new section to the file, (here assumed to be tox_with_conda.py,) so it can be called from cmd.exe:

C:\dev> python tox_with_conda.py E:\Anaconda3\envs 27 34 35 36 37

Edit 2: Can also be installed with pip: pip install tox_with_conda and used as:

C:\dev> python -m tox_with_conda E:\Anaconda3\envs 27 34 35 36 37

I'm using Python 3.6.3 and tox 2.9.1, but I don't know when/if earlier versions work too.

Defence:
I assume that to some, this seems like a too cumbersome process (it's really not, though), or to much of a hack. But keep in mind that being able to use Anaconda/conda also reduces waste of time spent trying to install libraries, packages, ++++.

Please note:

I use tox with pytest, and have not noticed any impacts on my tests.

My tests are simple, and there is a chance I just haven't been exposed to issues yet.

Assumable, there are things I haven't thought of that might be relevant for others.

The class (also available here):

from subprocess import run
from os.path import join

DEFAULT_BASE = join('C:\\', 'Python')

class ToxEnvMatcher:
    """
    Utility to make conda environments work with tox.

    Conda envs might be in other locations than where `tox <https://tox.readthedocs.io>`_ expects them to be.

    A symbolic link 'Directory Junction' is created from expected location to the actual location.
    Intended for Windows to get around the ``InterpreterNotFound``-error.

    E.g.: tox expects to find Python 2.7 in ``C:\Python27``,
    but may actually be installed in another drive and location.

    Examples of use:

    .. code-block:: python

        my_envs = join('E:\\', 'Anaconda3', 'envs')
        tem = ToxEnvMatcher(my_envs)
        for version in '27,34,35,36'.split(','):
            tem.make(version)

    The class is utilized through ``argsparse`` so it can also be used from cmd.exe.

    Examples of use of th of using ``ToxEnvMatcher`` from cmd.exe:

    .. code-block:: none

        E:\dev> tox_with_conda.py E:\Anaconda3\envs 27 34 35 36 37

    It's possible to use the ``-b``/``--base`` option to override the default base location (``C:\Python``):

    .. code-block:: none

        E:\dev> tox_with_conda.py E:\Anaconda3\envs 27 34 35 36 37 --base D:\Python

    :param str envs_dir: The path to where new conda environments will be created
    :param str default_base: The base of the 'default' location. Usually it's ``C:\Python``
    """
    def __init__(self, envs_dir, default_base=DEFAULT_BASE):
        self.envs_dir = envs_dir
        self.default_base = default_base

    def __repr__(self):
        return '{}({})'.format(self.__class__.__name__, self.envs_dir)

    def make(self, version):
        """
        Take version and create conda environment with symlink from 'default tox location'.

        E.g.: given version='27' and environment folder ``{self.envs_dir}``:

         - ``conda create -p {self.envs_dir}\py27 python=2.7``
         - ``mklink /J C:\Python27 {self.envs_dir}\py27``

        :param str version: A string on the form 'XY', e.g. '27' or '36'
        :return: None
        :rtype: NoneType
        """
        if len(version) != 2 or not int(version):
            raise ValueError("Parameter 'version' must be on the form 'XY', and not '{}'".format(version))
        conda_cmd = self._create_cmd_args(version)
        symlink_cmd = self._create_symlink_args(version)
        run(conda_cmd, shell=True)
        run(symlink_cmd, shell=True)

    def _get_env_folder(self, version):
        return join(self.envs_dir, 'py{}'.format(version))

    def _create_cmd_args(self, version):
        env_dir = self._get_env_folder(version)
        python_version = '.'.join(version)
        conda_create = 'conda create -p {} python={} --yes'.format(env_dir, python_version)
        return conda_create.split(' ')

    def _create_symlink_args(self, version):
        env_dir = self._get_env_folder(version)
        return 'mklink /J {}{} {}'.format(self.default_base, version, env_dir).split(' ')

The added code for making it work from cmd is:

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("env_dir",
                        help="The folder where conda environments should be installed.")
    parser.add_argument("versions", nargs='*',
                        help="The list of versions, formatted 'XY' where X is major and Y minor. E.g. '27 35 36'")
    parser.add_argument("-b", "--base", default=DEFAULT_BASE,
                        help="Base of the path which tox expects to find Python installed. "
                             "Default: {}.".format(DEFAULT_BASE))
    args = parser.parse_args()

    print('env_dir: ', args.env_dir)
    print('versions: ', args.versions)
    print('--base: ', args.base)

    tem = ToxEnvMatcher(args.env_dir, default_base=args.base)
    for version in args.versions:
        tem.make(version)

ContentLicense: CC BY-SA 4.0


问:
Spring Boot not able to read data at server startup with Postgres DB connection
I am having a very simple REST application based on Spring Boot that displays all the employees in the employee table when you hit the http://localhost:8080/api/employees endpoint.

The application gets the data from Postgres DB and displays it. Works fine with H2 but as soon as switched to Postgres DB I am getting this error at server startup.

Error (at server startup)

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at com.example.demo.EmployeeServiceApplication.main(EmployeeServiceApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [id] in table [employee]; found [int4 (Types#INTEGER)], but expecting [numeric(19,0) (Types#BIGINT)]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateColumnType(SchemaValidatorImpl.java:105) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:92) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:50) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:91) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:475) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        ... 23 common frames omitted

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.283 s
[INFO] Finished at: 2017-12-05T14:34:54-05:00
[INFO] Final Memory: 24M/437M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project employee-service-w-postgres: Could not exec java: Application finished with exit code: 1 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
</code>```

pom.xml

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

application.properties

```<code>spring.datasource.url=jdbc:postgresql://192.168.99.100:5432/emp-db
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=validate
</code>```

schema.sql

```<code>drop table if exists employee;
create table employee (
    id integer primary key not null,
    name varchar(20) not null
);
</code>```

data.sql

```<code>insert into employee(id, name) values(1, 'Jack');
insert into employee(id, name) values(2, 'Jill');
</code>```

domain/Employee.java

```<code>@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Size(min = 3, max = 20)
    private String name;

    public Employee(String name) {
        this.name = name;
    }

}
</code>```

controller/EmployeeRestController.java

```<code>@RestController
@RequestMapping("/api")
public class EmployeeRestController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/employees")
    public List<Employee> getAllEmployees() {
        return employeeService.getAllEmployees();
    }

}
</code>```

答:
@Akli REGUIG is right. For autoincremented fields you should use serial or bigserial types. From Postgres doc:

The data types serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases)

Body:
I am having a very simple REST application based on Spring Boot that displays all the employees in the employee table when you hit the http://localhost:8080/api/employees endpoint.

The application gets the data from Postgres DB and displays it. Works fine with H2 but as soon as switched to Postgres DB I am getting this error at server startup.

Error (at server startup)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at com.example.demo.EmployeeServiceApplication.main(EmployeeServiceApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [id] in table [employee]; found [int4 (Types#INTEGER)], but expecting [numeric(19,0) (Types#BIGINT)]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateColumnType(SchemaValidatorImpl.java:105) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:92) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:50) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:91) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:475) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        ... 23 common frames omitted

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.283 s
[INFO] Finished at: 2017-12-05T14:34:54-05:00
[INFO] Final Memory: 24M/437M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project employee-service-w-postgres: Could not exec java: Application finished with exit code: 1 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties

spring.datasource.url=jdbc:postgresql://192.168.99.100:5432/emp-db
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=validate

schema.sql

drop table if exists employee;
create table employee (
    id integer primary key not null,
    name varchar(20) not null
);

data.sql

insert into employee(id, name) values(1, 'Jack');
insert into employee(id, name) values(2, 'Jill');

domain/Employee.java

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Size(min = 3, max = 20)
    private String name;

    public Employee(String name) {
        this.name = name;
    }

}

controller/EmployeeRestController.java

@RestController
@RequestMapping("/api")
public class EmployeeRestController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/employees")
    public List<Employee> getAllEmployees() {
        return employeeService.getAllEmployees();
    }

}


问:
Xamarin.Forms ListView ViewCell issue on iOS
I've been trying to get this looking right in Xaml (x.forms) but can't make it work. Any possibly way this can be solved in Xaml without a custom cell renderer?

Here is how it's supposed to look on native iOS:

What I'm getting so far in Xaml:

Here's my Xaml:

```<code><ScrollView>
    <StackLayout>
        <ActivityIndicator IsRunning="{Binding IsFetching}" />
        <ListView ItemsSource="{Binding Events}" Header="2015" Footer="">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell Height="55">
                        <ViewCell.View>
                            <StackLayout Orientation="Horizontal" Padding="5" BackgroundColor="White">
                                <StackLayout>
                                    <BoxView WidthRequest="44"
                                         HeightRequest="5"
                                         BackgroundColor="Purple"
                                         />
                                    <Label Text="AUG" FontSize="12" HeightRequest="13" HorizontalOptions="Center" VerticalOptions="Start" FontAttributes="Bold"/>
                                    <Label Text="31" FontSize="13" VerticalOptions="StartAndExpand" HorizontalOptions="Center" />
                                </StackLayout>
                                <StackLayout Orientation="Vertical"
                                             HorizontalOptions="StartAndExpand">
                                    <Label Text="Relay For Life of" FontSize="14" VerticalOptions="End" TextColor="Gray"/>
                                    <Label Text="Hope City" FontSize="16" FontAttributes="Bold" VerticalOptions="StartAndExpand"/>
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ScrollView>
</code>```

答: Set HasUnevenRows="True" on the ListView</p>

Body:
I've been trying to get this looking right in Xaml (x.forms) but can't make it work. Any possibly way this can be solved in Xaml without a custom cell renderer?

Here is how it's supposed to look on native iOS:

What I'm getting so far in Xaml:

Here's my Xaml:

<ScrollView>
    <StackLayout>
        <ActivityIndicator IsRunning="{Binding IsFetching}" />
        <ListView ItemsSource="{Binding Events}" Header="2015" Footer="">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell Height="55">
                        <ViewCell.View>
                            <StackLayout Orientation="Horizontal" Padding="5" BackgroundColor="White">
                                <StackLayout>
                                    <BoxView WidthRequest="44"
                                         HeightRequest="5"
                                         BackgroundColor="Purple"
                                         />

                                </StackLayout>
                                <StackLayout Orientation="Vertical"
                                             HorizontalOptions="StartAndExpand">

                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ScrollView>


问:
Return a list of similar authors
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

```<code>authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}
</code>```

And the function I came up with is this:

```<code>def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]
</code>```

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

```<code>get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
</code>```

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

答:
One way is using list comprehension + itertools.chain

```<code>from itertools import chain

def get_similar(author_list, author):
     return sorted(set(chain(*[v for k,v in authors.items() if k in authors[author]])))

get_similar(authors, 'Harlan Ellison')
#['Chris Moore', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut', 'Neil Stephenson', 'Terry Pratchett', 'Tom Robbins']
</code>```

Title: Return a list of similar authors

Body:
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

And the function I came up with is this:

def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

Body:
One way is using list comprehension + itertools.chain

from itertools import chain

def get_similar(author_list, author):
     return sorted(set(chain(*[v for k,v in authors.items() if k in authors[author]])))

get_similar(authors, 'Harlan Ellison')
#['Chris Moore', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut', 'Neil Stephenson', 'Terry Pratchett', 'Tom Robbins']


问:
Upgraded Firebase - Getting error on FirebaseApp.configure()
I upgraded Firebase today and now I am having a very unusual problem

Use of unresolved identifier FirebaseApp.

I have done everything as per the documentation provided by firebase here. I have insert GoogleService-Info.plist on my project and pod i have install are as follows:

```<code>pod 'Firebase/Core
pod 'Firebase/Database
pod 'Firebase/Messaging
</code>```

I am using XCode 7.3.1 and my deployment target is 9.0

Any insight you can give is greatly appreciated! Thank you!

答:
I had a similar issue. Try deleting and uploading you Google file this way:

Instead of dragging the Google file directly into your Xcode project, right click the folder (inside your Xcode project) that you would like to save the Google file and click "Add Files to '[App Name]'..." and add GoogleService-info.plist that way. Also make sure the file is called "GoogleService-info.plist".

Body:
I upgraded Firebase today and now I am having a very unusual problem

Use of unresolved identifier FirebaseApp.

I have done everything as per the documentation provided by firebase here. I have insert GoogleService-Info.plist on my project and pod i have install are as follows:

pod 'Firebase/Core
pod 'Firebase/Database
pod 'Firebase/Messaging

I am using XCode 7.3.1 and my deployment target is 9.0

Any insight you can give is greatly appreciated! Thank you!


问:
Capturing the finished installing event for ActiveX
At the moment I have a custom ActiveX plugin that drops down the usual yellow bar with the install button if the user doesn't have it. When they finish installing, however, I need the page to automatically refresh. Is there a way to detect that the plugin has been successfully installed that isn't constantly polling for the plugin's presence. That is to say, not doing this:

```<code>function checkForPlugin() {
    try {
            control = new ActiveXObject('Object.One');
            //refresh
    } catch (e) {
            setTimeout("checkForPlugin()" ,2000);
    }
}
</code>```

This doesn't seem terribly professional and I'm curious if there is a better approach I could be taking. Come to think of it...I'm not exactly sure how I'd refresh there anyway, does anyone have insight on that as well? Thanks.

Update -- I have it working using the above method and even solved the refresh issue. I'm really not thrilled with this as an implementation though. It just feels wrong to leave the browser sitting there constantly polling in the background until it gets what it wants. It's not terrible I guess but I wish there was a more clean approach. Does anyone have any ideas?

答:
I think, capturing ActiveX install finish event is a kind of misconception.

Basically web pages run in single thread. There are no asynchronous processing such as a background installing.

In a life time of a web page, you will have the already installed ActiveX control or nothing. If control = new ActiveXObject throws, never you can instantiate the ActiveX control in this life time of the page.

That is, if the ActiveX control is not installed already you need to refresh the page to use the newly installed ActiveX control. This refresh is done automatically by the IE.

Body:
At the moment I have a custom ActiveX plugin that drops down the usual yellow bar with the install button if the user doesn't have it. When they finish installing, however, I need the page to automatically refresh. Is there a way to detect that the plugin has been successfully installed that isn't constantly polling for the plugin's presence. That is to say, not doing this:

function checkForPlugin() {
    try {
            control = new ActiveXObject('Object.One');
            //refresh
    } catch (e) {
            setTimeout("checkForPlugin()" ,2000);
    }
}

This doesn't seem terribly professional and I'm curious if there is a better approach I could be taking. Come to think of it...I'm not exactly sure how I'd refresh there anyway, does anyone have insight on that as well? Thanks.

Update -- I have it working using the above method and even solved the refresh issue. I'm really not thrilled with this as an implementation though. It just feels wrong to leave the browser sitting there constantly polling in the background until it gets what it wants. It's not terrible I guess but I wish there was a more clean approach. Does anyone have any ideas?


问:
Show Duplicate Values
I Have a table (#tempX) below.

```<code>BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
KLM222    |Melbourne
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
PQR888    |Brisbane
</code>```

I need to find the duplicate and display them.

```<code>BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
</code>```

I used the query below (you can copy and paste it to your SQL server) however it doesn't give me what I'm looking for. It gives me blank table as a result.

```<code>If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (box varchar(max) ,location varchar(max))

insert into #tempX (box,location)
values ('ABC123','Nowra'),('ABC123','Sydney'),('KLM222', 'Melbourne'),('XYZ444','Karatha'),('XYZ444','Mirabooka'),('XYZ444','Logan'),('PQR888','Brisbane')

--select * from #tempx

select distinct Box, Location, count(*) from #tempX
group by Box, Location
having count(*) > 1
</code>```

I'm using SQL Server 2012. Thanks all.

答:
Try this</p>

```<code>    create table #tmp (BoxNumber VARCHAR(25),Location  VARCHAR(25))

    INSERT INTO #tmp VALUES('ABC123','Nowra')
    INSERT INTO #tmp VALUES('ABC123','Sydney')
    INSERT INTO #tmp VALUES('KLM222','Melbourne')
    INSERT INTO #tmp VALUES('XYZ444','Karatha')
    INSERT INTO #tmp VALUES('XYZ444','Mirabooka')
    INSERT INTO #tmp VALUES('XYZ444','Logan')
    INSERT INTO #tmp VALUES('PQR888','Brisbane')

    ;with cte
    AS
    (
        SELECT ROW_NUMBER()OVER(Partition by BoxNumber order by BoxNumber) as [rank],* From #tmp
    )

    SELECT DISTINCT t.* from #tmp t
    JOIN cte c on t.BoxNumber=c.BoxNumber and c.[rank]>1

    /*

        -- OR (BELOW Query also returns the same result)

        SELECT * from #tmp
        WHERE BoxNumber in
        (
                SELECT  BoxNumber from cte where [rank]>1
        )

    */

    Drop table #tmp
</code>```

Title: Show Duplicate Values

Body:
I Have a table (#tempX) below.

BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
KLM222    |Melbourne
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
PQR888    |Brisbane

I need to find the duplicate and display them.

BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan

I used the query below (you can copy and paste it to your SQL server) however it doesn't give me what I'm looking for. It gives me blank table as a result.

If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (box varchar(max) ,location varchar(max))

insert into #tempX (box,location)
values ('ABC123','Nowra'),('ABC123','Sydney'),('KLM222', 'Melbourne'),('XYZ444','Karatha'),('XYZ444','Mirabooka'),('XYZ444','Logan'),('PQR888','Brisbane')

--select * from #tempx

select distinct Box, Location, count(*) from #tempX
group by Box, Location
having count(*) > 1

I'm using SQL Server 2012. Thanks all.

Body:
Try this

    create table #tmp (BoxNumber VARCHAR(25),Location  VARCHAR(25))

    INSERT INTO #tmp VALUES('ABC123','Nowra')
    INSERT INTO #tmp VALUES('ABC123','Sydney')
    INSERT INTO #tmp VALUES('KLM222','Melbourne')
    INSERT INTO #tmp VALUES('XYZ444','Karatha')
    INSERT INTO #tmp VALUES('XYZ444','Mirabooka')
    INSERT INTO #tmp VALUES('XYZ444','Logan')
    INSERT INTO #tmp VALUES('PQR888','Brisbane')

    ;with cte
    AS
    (
        SELECT ROW_NUMBER()OVER(Partition by BoxNumber order by BoxNumber) as [rank],* From #tmp
    )

    SELECT DISTINCT t.* from #tmp t
    JOIN cte c on t.BoxNumber=c.BoxNumber and c.[rank]>1

    /*

        -- OR (BELOW Query also returns the same result)

        SELECT * from #tmp
        WHERE BoxNumber in
        (
                SELECT  BoxNumber from cte where [rank]>1
        )

    */

    Drop table #tmp


问:
Custom content dropdown not working in PrimeNG?
I'm implementing a custom content dropdown. Is not working properly. It does not set selectedTestType value and It gives undefined value in  the onChangeTestTypes.

```<code><p-dropdown name="classTestTypeCombobox"
            [options]="TestTypes" [(ngModel)]="selectedTestType"
            [style]="{'width':'150px'}" filter="filter"
            [disabled]="this.isProdCodeDisabled"
            appendTo="body"
            required
            #classTestTypeCombobox="ngModel"
            (ngModelChange)="onChangeTestTypes($event)">
    <ng-template let-TestType pTemplate="item">
        <div class="ui-helper-clearfix" style="position: relative;height: 25px;">
            <div>{{TestType.descLong}}</div>
        </div>
    </ng-template>
</p-dropdown>
</code>```

TestTypes is an array of class object, which has the following members.

```<code>id: number;
classificationCode: string;
descLong: string;
classificationParent: string;
codeType: number;

onChangeTestTypes(TestType) {
    this.selectedTestTypeDesc = this.TestTypes.filter(x => x.priceCode == TestType)[0].descLong;
    this.price.Type = this.TestTypes.filter(x => x.priceCode == TestType)[0].Type;
}
</code>```

答:
Use optionLabel with the name of the field that you want to show in the drop down list. For example if you want to use classificationCode

```<code> <p-dropdown name="classTestTypeCombobox"
            [options]="TestTypes" [(ngModel)]="selectedTestType"
            [style]="{'width':'150px'}" filter="filter"
            [disabled]="this.isProdCodeDisabled"
            optionLabel="classificationCode"
</p-dropdown>
</code>```

Observe that optionLabel does not need [] also the assigned value is simple the name of the custom object field.

Body:
I'm implementing a custom content dropdown. Is not working properly. It does not set selectedTestType value and It gives undefined value in  the onChangeTestTypes.

    <ng-template let-TestType pTemplate="item">

{{TestType.descLong}}

    </ng-template>

TestTypes is an array of class object, which has the following members.

id: number;
classificationCode: string;
descLong: string;
classificationParent: string;
codeType: number;

onChangeTestTypes(TestType) {
    this.selectedTestTypeDesc = this.TestTypes.filter(x => x.priceCode == TestType)[0].descLong;
    this.price.Type = this.TestTypes.filter(x => x.priceCode == TestType)[0].Type;
}

Body:
Use optionLabel with the name of the field that you want to show in the drop down list. For example if you want to use classificationCode

 <p-dropdown name="classTestTypeCombobox"
            [options]="TestTypes" [(ngModel)]="selectedTestType"
            [style]="{'width':'150px'}" filter="filter"
            [disabled]="this.isProdCodeDisabled"
            optionLabel="classificationCode"
</p-dropdown>

Observe that optionLabel does not need [] also the assigned value is simple the name of the custom object field.


问:
Reading methods from a text file for Java
I am working on an assignment and was wondering how one can read a method with  a parameter stated in a text file. For example, in my assignment the addFirst method will have a string right after it (addFirst New York). Also, The addFirst method name may be all lowercase. I've been looking around the net and this is what I already worked on:

```<code>import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Assignment2 {

  static DequeUsingStacks<String> deq = new DequeUsingStacks<String>();

  public static void main(String[] args) {

    try{
        FileInputStream fstream = new FileInputStream("Assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String m;

        while((m = br.readLine()) != null){

                if(m.equalsIgnoreCase("size"))
                    System.out.println(deq.size());

                if(m.equalsIgnoreCase("addFirst")) /*I want to be able to
                                                     use the string after
                                                     the method as the new
                                                     Value. So new
                                                     Value should equal to
                                                    "New York"*/

                deq.addFirst(new value);

        }

        fstream.close();
</code>```

DequeUsingStacks is another class with all the methods. I guess I just want to know how to read a line in a textfile with multiple strings. "New Value" is the string stated after the method in the text file. For example, (addFirst New York), the string "New York" should be the "New Value". I'm thinking that the line read should be put into an array. But I am not sure how to do that.

答:
i think you may try </p>

```<code>if(m.contains("addFirst")) {

  String[] words = m.split("addFirst"); // In this case assume that do not have any others sentences after word "New York"
String result = words.get(0);

deq.addFirst(result);

}
</code>```

Body:
I am working on an assignment and was wondering how one can read a method with  a parameter stated in a text file. For example, in my assignment the addFirst method will have a string right after it (addFirst New York). Also, The addFirst method name may be all lowercase. I've been looking around the net and this is what I already worked on:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Assignment2 {

  static DequeUsingStacks<String> deq = new DequeUsingStacks<String>();

  public static void main(String[] args) {

    try{
        FileInputStream fstream = new FileInputStream("Assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String m;

        while((m = br.readLine()) != null){

                if(m.equalsIgnoreCase("size"))
                    System.out.println(deq.size());

                if(m.equalsIgnoreCase("addFirst")) /*I want to be able to
                                                     use the string after
                                                     the method as the new
                                                     Value. So new
                                                     Value should equal to
                                                    "New York"*/

                deq.addFirst(new value);

        }

        fstream.close();

DequeUsingStacks is another class with all the methods. I guess I just want to know how to read a line in a textfile with multiple strings. "New Value" is the string stated after the method in the text file. For example, (addFirst New York), the string "New York" should be the "New Value". I'm thinking that the line read should be put into an array. But I am not sure how to do that.

Body:
i think you may try

if(m.contains("addFirst")) {

  String[] words = m.split("addFirst"); // In this case assume that do not have any others sentences after word "New York"
String result = words.get(0);

deq.addFirst(result);

}


问:
Completely remove sensitive information from a git message
I accidentally included some sensitive information in a git commit message. The actual files are all fine---it's just the content of the message itself that needs to be rolled back.

How can I purge the message so that it doesn't appear anywhere, including the git reflog history?

答:
TL;DR

Make a replacement commit, then manually delete or purge the unwanted reflog entries (there are two of them).  You can then run git gc if you like, and use git show hash-id to see if that threw it out.  It might not—it might still be accessible by hash ID for up to 14 days.  See below for details and additional options.

Description

You cannot change the existing commit.

You can make a new commit that is just like the existing commit, except for _____ (fill in the blank).

There is a handy Git built-in option to git commit for doing exactly that to the most recent commit:

```<code>git commit --amend
</code>```

By default, this takes whatever is in the index right now—which, if you just made a commit that you regret making, probably still matches that commit you just made—and makes a new commit from it.  But instead of using the current commit as the new commit's parent, it uses the current commit's parents as the new commit's parents.  It also brings up your editor on the current commit's message, letting you rewrite the message.

The result is a new commit.  As always, the git commit command makes the current branch name point to the new commit just made.  But the new commit points back not to the previous tip, but to that tip's parents.  In effect, the commit you made earlier is "shoved aside":

```<code>...--o--o--X   <-- branch    # where X is the bad commit
</code>```

becomes:

```<code>          X   [abandoned]
         /
...--o--o--N   <-- branch
</code>```

Now, the problem is that despite being abandoned, the old commit persists in your repository for a while.  Any name that can find it, suffices to find it.  That includes reflog entries and any other branch and tag names that can reach the commit.

Since you just made the commit, presumably there are no such additional names.  That means there are only reflog entries: one for HEAD, and one for the branch named branch.

The easiest way to purge reflog entries is also the most (or, well, second-most) dangerous: you can run git reflog expire --expire-unreachable=now --all.  This tosses out all reflog entries that are not reachable from the tip of the reference in question, without looking at their ages as well.

The best way is probably to delete those two specific reflog entries, which are HEAD@{1} and branch@{1}, where branch is whichever branch is current.  You can run git reflog delete HEAD@{1} to delete the HEAD entry at slot 1, and similarly for the current branch's  slot-1 entry.  (You may need quotes or some such around {1} to protect it from your shell, depending on your shell.)

At this point there should be no names for the commit.  It will not show up in git log and will not even show up in git reflog.  However, one can run git fsck --unreachable or git fsck --lost-found to find unreachable objects, or if you know its raw hash ID, git show hash-id to see it.

Git normally leaves unreachable objects around for at least 14 days, in case they're only temporarily unreachable during construction.  After 14 days go by, they're probably not still needed for a Git command that has not yet finished running, so they get removed by git gc.  If you're sure there are no Git commands still running that are building things that haven't quite finished and been put on display yet, you can bypass this safety net by running git gc --prune=all.

There are cases where even this does not suffice, if the object has been packed into a protected (.keep) pack, but that won't apply to your situation.  In any case it's usually pointless to go to this much effort in the first place—if it doesn't show up in git log, most people never look any further.

Body:
TL;DR

Make a replacement commit, then manually delete or purge the unwanted reflog entries (there are two of them).  You can then run git gc if you like, and use git show hash-id to see if that threw it out.  It might not—it might still be accessible by hash ID for up to 14 days.  See below for details and additional options.

Description

You cannot change the existing commit.

You can make a new commit that is just like the existing commit, except for _____ (fill in the blank).

There is a handy Git built-in option to git commit for doing exactly that to the most recent commit:

git commit --amend

By default, this takes whatever is in the index right now—which, if you just made a commit that you regret making, probably still matches that commit you just made—and makes a new commit from it.  But instead of using the current commit as the new commit's parent, it uses the current commit's parents as the new commit's parents.  It also brings up your editor on the current commit's message, letting you rewrite the message.

The result is a new commit.  As always, the git commit command makes the current branch name point to the new commit just made.  But the new commit points back not to the previous tip, but to that tip's parents.  In effect, the commit you made earlier is "shoved aside":

...--o--o--X   <-- branch    # where X is the bad commit

becomes:

          X   [abandoned]
         /
...--o--o--N   <-- branch

Now, the problem is that despite being abandoned, the old commit persists in your repository for a while.  Any name that can find it, suffices to find it.  That includes reflog entries and any other branch and tag names that can reach the commit.

Since you just made the commit, presumably there are no such additional names.  That means there are only reflog entries: one for HEAD, and one for the branch named branch.

The easiest way to purge reflog entries is also the most (or, well, second-most) dangerous: you can run git reflog expire --expire-unreachable=now --all.  This tosses out all reflog entries that are not reachable from the tip of the reference in question, without looking at their ages as well.

The best way is probably to delete those two specific reflog entries, which are HEAD@{1} and branch@{1}, where branch is whichever branch is current.  You can run git reflog delete HEAD@{1} to delete the HEAD entry at slot 1, and similarly for the current branch's  slot-1 entry.  (You may need quotes or some such around {1} to protect it from your shell, depending on your shell.)

At this point there should be no names for the commit.  It will not show up in git log and will not even show up in git reflog.  However, one can run git fsck --unreachable or git fsck --lost-found to find unreachable objects, or if you know its raw hash ID, git show hash-id to see it.

Git normally leaves unreachable objects around for at least 14 days, in case they're only temporarily unreachable during construction.  After 14 days go by, they're probably not still needed for a Git command that has not yet finished running, so they get removed by git gc.  If you're sure there are no Git commands still running that are building things that haven't quite finished and been put on display yet, you can bypass this safety net by running git gc --prune=all.

There are cases where even this does not suffice, if the object has been packed into a protected (.keep) pack, but that won't apply to your situation.  In any case it's usually pointless to go to this much effort in the first place—if it doesn't show up in git log, most people never look any further.


问:
regular expression for @import css tag for all cases
**hello everyone,
I am doing some work with webpage source code. i need the regular expression for all possible syntax of importing .css file. for example-

```<code>1.@import url("a.css");
2.@import url('a.css');
3.@import url ("a.css");
4.@import url ('a.css');
5.@import "a.css";
6.@import 'a.css';  etc.
</code>```

i want one regular expression for all cases.please help.**

答:
like this:

const re = /(?:@import)\s(?:url\()?\s?["\'](.*?)["\']\s?\)?(?:[^;]*);?/gi;

const s='@import url("fineprint.css") print; @import url("bluish.css") projection, tv; @import \'custom.css\'; @import url("chrome://communicator/skin/"); @import "common.css" screen, projection; @import url(\'landscape.css\') screen and (orientation:landscape);';

s.replace(re, (match, g1) => console.log(match, g1));```

Body:
**hello everyone,
I am doing some work with webpage source code. i need the regular expression for all possible syntax of importing .css file. for example-

1.@import url("a.css");
2.@import url('a.css');
3.@import url ("a.css");
4.@import url ('a.css');
5.@import "a.css";
6.@import 'a.css';  etc.

i want one regular expression for all cases.please help.**


问:
How do I link up the NLTK libraries to chatterbot and then use SentimentComparison?
I've managed to download the NLTK stuff to a local chatterbox data folder, but after that I can't find any documentation on how exactly to get SentimentComparison to work, or how to initialize the VADER lexicon (which apparently gets extracted from the NLTK) and then have the chatbot use it all for the output.
Python 3.6.3
chatterbot 0.7.6
NLTK installed here ...chatterbot\data\nltk_data
Q: Can anyone provide me with examples? </p>

答:
You can use the sentiment analysis comparison by setting the statement_comparison_function for your chat bot.

For example:

```<code>from chatterbot import ChatBot
from chatterbot.comparisons import sentiment_comparison

chatbot = ChatBot(
    # ...
    statement_comparison_function=sentiment_comparison
)
</code>```

Your chat bot will download and use the NLTK data that it needs (such as the VADER lexicon) automatically.

More information about the available comparison functions can be found in the ChatterBot documentation: http://chatterbot.readthedocs.io/en/latest/comparisons.html

Body:
You can use the sentiment analysis comparison by setting the statement_comparison_function for your chat bot.

For example:

from chatterbot import ChatBot
from chatterbot.comparisons import sentiment_comparison

chatbot = ChatBot(
    # ...
    statement_comparison_function=sentiment_comparison
)

Your chat bot will download and use the NLTK data that it needs (such as the VADER lexicon) automatically.

More information about the available comparison functions can be found in the ChatterBot documentation: http://chatterbot.readthedocs.io/en/latest/comparisons.html


问:
Extend tree structure XDcoument
I'm trying to extend a tree structure based XDocument.

It should be able to add sections and parameter-value combinations as attributes

The depth of the tree is not fixed.

So the function should verify if something exists and if not add it.

```<code><Body>
 <SectionA>
   <SectionB paramB="valB" paramB2="val2">
    <SectionC paramB="valB" paramNEW="NEW">
    </SectionC>
    <SectionD>
      <SectionE>
      </SectionE>
    </SectionD>
   </SectionB>
  </SectionA>
</Body>
</code>```

So i wrote the following

```<code>    public void Create(string treenode, string parameter, string value, XDocument doc)
    {
        treenode =treenode.Replace('\\','/');
        string[] branch = treenode.Split('/');
        string tree = "";
        for (int i = 0; i < branch.Length; i++) // walk trough tree
        {
            tree = tree +"/"+ branch[i];
            bool exists = (bool)doc.XPathEvaluate("boolean("+tree+")");
            if (exists==false)  //...what goes here ?.
        }
    }
</code>```

I'm a bit confused of what functions to use after the "what goes here".
 Because the depth of the tree can vary.

答:
This can be solved using recursion. Try the following:

Entry point

```<code> void Entry()
 {
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(@"<Body>
                     <SectionA>
                       <SectionB paramB = 'valB' paramB2='val2'>
                        <SectionC paramB = 'valB' paramNEW='NEW'>
                        </SectionC>
                        <SectionD>
                          <SectionE>
                          </SectionE>
                        </SectionD>
                       </SectionB>
                      </SectionA>
                    </Body>");

    string treeNode = @"Body\SectionA\SectionB\SectionC\SectionX";
    Create(treeNode, "paramX", "valueX", doc);
  }
</code>```

Your existing code is here

```<code>public void Create(string treeNode, string parameter, string value, XmlDocument doc)
        {
            treeNode = treeNode.Replace('\\', '/');
            string[] branch = treeNode.Split('/');
            string tree = "";
            for (int i = 0; i < branch.Length; i++) // walk trough tree
            {
                tree = tree + "/" + branch[i];
                XmlNode node = CreateXPath(doc, tree, parameter, value);
                //if (exists == false)  //...what goes here ?.
            }
        }
</code>```

Recursive functions:

```<code>private XmlNode CreateXPath(XmlDocument doc, string xpath, string parameter, string value)
{
  return CreateXPath(doc, doc as XmlNode, xpath, parameter, value);
}

private XmlNode CreateXPath(XmlDocument doc, XmlNode parent, string xpath, string parameter, string value)
{
   string[] partsOfXPath = xpath.Trim('/').Split('/');
   string nextNodeInXPath = partsOfXPath.First();
   if (string.IsNullOrEmpty(nextNodeInXPath))
   {
      if (parent.Attributes[parameter] == null && parent.LocalName == xpath)
      {
        // Attribute not found, create it
        ((XmlElement)parent).SetAttribute(parameter, value);
      }
      return parent;
    }

    XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
    if (node == null)
    {
       // node not found, create it and additionally add attributes
       node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));
       ((XmlElement)node).SetAttribute(parameter, value);
    }
    // Call recursive
    string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
    return CreateXPath(doc, node, rest, parameter, value);
 }
</code>```

Got the following output:

```<code><?xml version="1.0"?>
<Body>
 <SectionA>
  <SectionB paramB2="val2" paramB="valB">
   <SectionC paramB="valB" paramNEW="NEW">
    <SectionX paramX="valueX"/>
   </SectionC>
   <SectionD>
    <SectionE/>
   </SectionD>
  </SectionB>
 </SectionA>
</Body>
</code>```

Title: Extend tree structure XDcoument

Body:
I'm trying to extend a tree structure based XDocument.

It should be able to add sections and parameter-value combinations as attributes

The depth of the tree is not fixed.

So the function should verify if something exists and if not add it.

 <SectionA>
   <SectionB paramB="valB" paramB2="val2">
    <SectionC paramB="valB" paramNEW="NEW">
    </SectionC>
    <SectionD>
      <SectionE>
      </SectionE>
    </SectionD>
   </SectionB>
  </SectionA>

So i wrote the following

    public void Create(string treenode, string parameter, string value, XDocument doc)
    {
        treenode =treenode.Replace('\\','/');
        string[] branch = treenode.Split('/');
        string tree = "";
        for (int i = 0; i < branch.Length; i++) // walk trough tree
        {
            tree = tree +"/"+ branch[i];
            bool exists = (bool)doc.XPathEvaluate("boolean("+tree+")");
            if (exists==false)  //...what goes here ?.
        }
    }

I'm a bit confused of what functions to use after the "what goes here".
 Because the depth of the tree can vary.

Body:
This can be solved using recursion. Try the following:

Entry point

 void Entry()
 {
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(@"<Body>
                     <SectionA>
                       <SectionB paramB = 'valB' paramB2='val2'>
                        <SectionC paramB = 'valB' paramNEW='NEW'>
                        </SectionC>
                        <SectionD>
                          <SectionE>
                          </SectionE>
                        </SectionD>
                       </SectionB>
                      </SectionA>
                    </Body>");

    string treeNode = @"Body\SectionA\SectionB\SectionC\SectionX";
    Create(treeNode, "paramX", "valueX", doc);
  }

Your existing code is here

public void Create(string treeNode, string parameter, string value, XmlDocument doc)
        {
            treeNode = treeNode.Replace('\\', '/');
            string[] branch = treeNode.Split('/');
            string tree = "";
            for (int i = 0; i < branch.Length; i++) // walk trough tree
            {
                tree = tree + "/" + branch[i];
                XmlNode node = CreateXPath(doc, tree, parameter, value);
                //if (exists == false)  //...what goes here ?.
            }
        }

Recursive functions:

private XmlNode CreateXPath(XmlDocument doc, string xpath, string parameter, string value)
{
  return CreateXPath(doc, doc as XmlNode, xpath, parameter, value);
}

private XmlNode CreateXPath(XmlDocument doc, XmlNode parent, string xpath, string parameter, string value)
{
   string[] partsOfXPath = xpath.Trim('/').Split('/');
   string nextNodeInXPath = partsOfXPath.First();
   if (string.IsNullOrEmpty(nextNodeInXPath))
   {
      if (parent.Attributes[parameter] == null && parent.LocalName == xpath)
      {
        // Attribute not found, create it
        ((XmlElement)parent).SetAttribute(parameter, value);
      }
      return parent;
    }

    XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
    if (node == null)
    {
       // node not found, create it and additionally add attributes
       node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));
       ((XmlElement)node).SetAttribute(parameter, value);
    }
    // Call recursive
    string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
    return CreateXPath(doc, node, rest, parameter, value);
 }

Got the following output:

<?xml version="1.0"?>
<Body>
 <SectionA>
  <SectionB paramB2="val2" paramB="valB">
   <SectionC paramB="valB" paramNEW="NEW">
    <SectionX paramX="valueX"/>
   </SectionC>
   <SectionD>
    <SectionE/>
   </SectionD>
  </SectionB>
 </SectionA>
</Body>


问:
How to input a value to textbox in iframe
I am trying to input a value from my website to another website loaded in the iframe.
For example, I loaded gmail.com in my iframe and i need to input login credentials from my website.

```<code>    var iframe = document.getElementById('content_frame');
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    var elem = document.getElementById('userEmail');
</code>```

while executing the second line, i've got the below error

```<code>SecurityError: Permission denied to access property "document" on cross-origin object
</code>```

答: You can not do that because of same-origin policy .</p>

Body:
I am trying to input a value from my website to another website loaded in the iframe.
For example, I loaded gmail.com in my iframe and i need to input login credentials from my website.

    var iframe = document.getElementById('content_frame');
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    var elem = document.getElementById('userEmail');

while executing the second line, i've got the below error

SecurityError: Permission denied to access property "document" on cross-origin object


问:
How to concatenate string variables in Bash
In PHP, strings are concatenated together as follows:

```<code>$foo = "Hello";
$foo .= " World";
</code>```

Here, $foo becomes "Hello World".

How is this accomplished in Bash?

答:
Here is a concise summary of what most answers are talking about.

Let's say we have two variables and $1 is set to 'one':

```<code>set one two
a=hello
b=world
</code>```

The table below explains the different contexts where we can combine the values of a and b to create a new variable, c.

Context                               | Expression            | Result (value of c)
--------------------------------------+-----------------------+---------------------
Two variables                         | c=$a$b                | helloworld
A variable and a literal              | c=${a}_world          | hello_world
A variable and a literal              | c=$1world             | oneworld
A variable and a literal              | c=$a/world            | hello/world
A variable, a literal, with a space   | c=${a}" world"        | hello world
A more complex expression             | c="${a}_one|${b}_2"   | hello_one|world_2
Using += operator (Bash 3.1 or later) | c=$a; c+=$b           | helloworld
Append literal with +=                | c=$a; c+=" world"     | hello world
```

A few notes:

enclosing the RHS of an assignment in double quotes is generally a good practice, though it is quite optional in many cases

+= is better from a performance standpoint if a big string is being constructed in small increments, especially in a loop

use {} around variable names to disambiguate their expansion (as in row 2 in the table above). As seen on rows 3 and 4, there is no need for {} unless a variable is being concatenated with a string that starts with a character that is a valid first character in shell variable name, that is alphabet or underscore.

See also:

BashFAQ/013 - How can I concatenate two variables?

When do we need curly braces around shell variables?

Body:
In PHP, strings are concatenated together as follows:

$foo = "Hello";
$foo .= " World";

Here, $foo becomes "Hello World".

How is this accomplished in Bash?

Body:
Here is a concise summary of what most answers are talking about.

Let's say we have two variables and $1 is set to 'one':

set one two
a=hello
b=world

The table below explains the different contexts where we can combine the values of a and b to create a new variable, c.

Context                               | Expression            | Result (value of c)
--------------------------------------+-----------------------+---------------------
Two variables                         | c=$a$b                | helloworld
A variable and a literal              | c=${a}_world          | hello_world
A variable and a literal              | c=$1world             | oneworld
A variable and a literal              | c=$a/world            | hello/world
A variable, a literal, with a space   | c=${a}" world"        | hello world
A more complex expression             | c="${a}_one|${b}_2"   | hello_one|world_2
Using += operator (Bash 3.1 or later) | c=$a; c+=$b           | helloworld
Append literal with +=                | c=$a; c+=" world"     | hello world

A few notes:

enclosing the RHS of an assignment in double quotes is generally a good practice, though it is quite optional in many cases

+= is better from a performance standpoint if a big string is being constructed in small increments, especially in a loop

use {} around variable names to disambiguate their expansion (as in row 2 in the table above). As seen on rows 3 and 4, there is no need for {} unless a variable is being concatenated with a string that starts with a character that is a valid first character in shell variable name, that is alphabet or underscore.

See also:

BashFAQ/013 - How can I concatenate two variables?

When do we need curly braces around shell variables?