问:
MongoDB C# driver CancellationToken
Does anyone know what the CancellationToken does if you add it with a parameter in the for example

```<code>public static UpdateResult UpdateMany<TDocument>(
    this IMongoCollection<TDocument> collection,
    Expression<Func<TDocument, bool>> filter,
    UpdateDefinition<TDocument> update,
    UpdateOptions options = null,
    CancellationToken cancellationToken = null
)
</code>```

https://mongodb.github.io/mongo-csharp-driver/2.3/apidocs/html/M_MongoDB_Driver_IMongoCollectionExtensions_UpdateMany__1.htm

Is it a rollback? Or what does it do?

答:
A CancellationToken is generally used while writing asynchronous I/O code through the mongodb driver (InsertOneAsync for example). Lets take the following scenario into consideration. You are making breakfast. Example taken from here.

```<code>static async Task Main(string[] args)
{
    //Find eggs and bacon in database
    Task<List<Egg>> eggTask = FindEggsAsync(2);
    Task<List<Bacon>> baconTask = FindBaconAsync(3);

    Coffee cup = PourCoffee();
    Console.WriteLine("coffee is ready");

    Juice oj = PourOJ();
    Console.WriteLine("oj is ready");

    List<Egg> eggs = await eggTask;
    List<Bacon> bacon = await baconTask;

    FryEggs(eggs);
    Console.WriteLine("eggs are ready");

    FryBacon(bacon);
    Console.WriteLine("bacon is ready");

    Console.WriteLine("Breakfast is ready!");
}
</code>```

This is good asynchronous code right ? We are awaiting our tasks only when we need the result from them.

We first need to find our eggs and bacon via I/O , lets imagine our eggs and bacon are stored in a mongodb as opposed to the pantry. So we send your 2 imaginary children with two tasks to find the eggs and bacon from the pantry(database).

While they find you pour yourself a cup of OJ and coffee that was already on hand(Basically Any CPU work).

With coffee and juice in hand you realize you are ready to prepare your ingredients , so you await the return of both tasks given to your kids and FryEggs and FryBacon.

Great breakfast is done - but lets assume you are a grumpy person and had a terrible morning , your coffee spills and this puts you completely off breakfast entirely(absurd I know), you need to tell your kids with tasks to stop searching. Lets amend the above code to integrate this.

```<code>static async Task Main(string[] args)
{
     var cancellationToken = new CancellationTokenSource();
    //Find eggs and bacon in database
    Task<List<Egg>> eggTask = FindEggsAsync(2,cancellationToken.Token);
    Task<List<Bacon>> baconTask = FindBaconAsync(3,cancellationToken.Token);

    Coffee cup = PourCoffee();
    if(cup.IsSpilled())
    {
        //Freak out and cancel tasks
        cancellationToken.Cancel();
        //Quit
        Environment.Exit(0)
    }
    Console.WriteLine("coffee is ready");

    Juice oj = PourOJ();
    Console.WriteLine("oj is ready");

    List<Egg> eggs = await eggTask;
    List<Bacon> bacon = await baconTask;

    FryEggs(eggs);
    Console.WriteLine("eggs are ready");

    FryBacon(bacon);
    Console.WriteLine("bacon is ready");

    Console.WriteLine("Breakfast is ready!");
    //Dispose of token
    cancellationToken.Dispose();
}
</code>```

The cancellation token itself will be passed to the async version of the mongodb driver method in Question. FindAsync will be called in the case of our two find methods and our cancellation token is passed in. If the task has not yet completed it will cancel the I/O operation accordingly.

Title: MongoDB C# driver CancellationToken

Body:
Does anyone know what the CancellationToken does if you add it with a parameter in the for example

public static UpdateResult UpdateMany<TDocument>(
    this IMongoCollection<TDocument> collection,
    Expression<Func<TDocument, bool>> filter,
    UpdateDefinition<TDocument> update,
    UpdateOptions options = null,
    CancellationToken cancellationToken = null
)

https://mongodb.github.io/mongo-csharp-driver/2.3/apidocs/html/M_MongoDB_Driver_IMongoCollectionExtensions_UpdateMany__1.htm

Is it a rollback? Or what does it do?

Body:
A CancellationToken is generally used while writing asynchronous I/O code through the mongodb driver (InsertOneAsync for example). Lets take the following scenario into consideration. You are making breakfast. Example taken from here.

static async Task Main(string[] args)
{
    //Find eggs and bacon in database
    Task<List<Egg>> eggTask = FindEggsAsync(2);
    Task<List<Bacon>> baconTask = FindBaconAsync(3);

    Coffee cup = PourCoffee();
    Console.WriteLine("coffee is ready");

    Juice oj = PourOJ();
    Console.WriteLine("oj is ready");

    List<Egg> eggs = await eggTask;
    List<Bacon> bacon = await baconTask;

    FryEggs(eggs);
    Console.WriteLine("eggs are ready");

    FryBacon(bacon);
    Console.WriteLine("bacon is ready");

    Console.WriteLine("Breakfast is ready!");
}

This is good asynchronous code right ? We are awaiting our tasks only when we need the result from them.

We first need to find our eggs and bacon via I/O , lets imagine our eggs and bacon are stored in a mongodb as opposed to the pantry. So we send your 2 imaginary children with two tasks to find the eggs and bacon from the pantry(database).

While they find you pour yourself a cup of OJ and coffee that was already on hand(Basically Any CPU work).

With coffee and juice in hand you realize you are ready to prepare your ingredients , so you await the return of both tasks given to your kids and FryEggs and FryBacon.

Great breakfast is done - but lets assume you are a grumpy person and had a terrible morning , your coffee spills and this puts you completely off breakfast entirely(absurd I know), you need to tell your kids with tasks to stop searching. Lets amend the above code to integrate this.

static async Task Main(string[] args)
{
     var cancellationToken = new CancellationTokenSource();
    //Find eggs and bacon in database
    Task<List<Egg>> eggTask = FindEggsAsync(2,cancellationToken.Token);
    Task<List<Bacon>> baconTask = FindBaconAsync(3,cancellationToken.Token);

    Coffee cup = PourCoffee();
    if(cup.IsSpilled())
    {
        //Freak out and cancel tasks
        cancellationToken.Cancel();
        //Quit
        Environment.Exit(0)
    }
    Console.WriteLine("coffee is ready");

    Juice oj = PourOJ();
    Console.WriteLine("oj is ready");

    List<Egg> eggs = await eggTask;
    List<Bacon> bacon = await baconTask;

    FryEggs(eggs);
    Console.WriteLine("eggs are ready");

    FryBacon(bacon);
    Console.WriteLine("bacon is ready");

    Console.WriteLine("Breakfast is ready!");
    //Dispose of token
    cancellationToken.Dispose();
}

The cancellation token itself will be passed to the async version of the mongodb driver method in Question. FindAsync will be called in the case of our two find methods and our cancellation token is passed in. If the task has not yet completed it will cancel the I/O operation accordingly.


来源: stackexchange

问:
Recommended way to move elements of array to top level in Javascript
Say I have an array: [['TEST1'], ['TEST2'], ['TEST3'], ['TEST4'], ['TEST5']] and I want to move all the elements to the "top" level of the array, so it would end up like so:

```<code>['TEST1', 'TEST2', 'TEST3', 'TEST4', 'TEST5']
</code>```

I have a few mockups below, but I'm wondering what the recommended route might be.

```<code>var test = [['TEST1'], ['TEST2'], ['TEST3'], ['TEST4'], ['TEST5']];
var testarr = [];

test.forEach(function(e){
  testarr.push(e[0]);
})
console.log(testarr);
</code>```

Or

```<code>var test = [['TEST1'], ['TEST2'], ['TEST3'], ['TEST4'], ['TEST5']];

for (i = 0; n = test.length, i < n; i++){
  test[i] = test[i][0]
}
console.log(test);
</code>```

Output of both:

```<code>[ 'TEST1', 'TEST2', 'TEST3', 'TEST4', 'TEST5' ]
</code>```

答:
You can try the below method

const input = [
  ['TEST1'],
  ['TEST2'],
  ['TEST3'],
  ['TEST4'],
  ['TEST5']
]
function flattenDeep(input) {
    return input.reduce((accu, val) => Array.isArray(val) ? accu.concat(flattenDeep(val)):accu.concat(val), []);
}

console.log(flattenDeep(input));```

ContentLicense: CC BY-SA 3.0

Body:
Say I have an array: [['TEST1'], ['TEST2'], ['TEST3'], ['TEST4'], ['TEST5']] and I want to move all the elements to the "top" level of the array, so it would end up like so:

['TEST1', 'TEST2', 'TEST3', 'TEST4', 'TEST5']

I have a few mockups below, but I'm wondering what the recommended route might be.

var test = [['TEST1'], ['TEST2'], ['TEST3'], ['TEST4'], ['TEST5']];
var testarr = [];

test.forEach(function(e){
  testarr.push(e[0]);
})
console.log(testarr);

Or

var test = [['TEST1'], ['TEST2'], ['TEST3'], ['TEST4'], ['TEST5']];

for (i = 0; n = test.length, i < n; i++){
  test[i] = test[i][0]
}
console.log(test);

Output of both:

[ 'TEST1', 'TEST2', 'TEST3', 'TEST4', 'TEST5' ]

ContentLicense: CC BY-SA 4.0


问:
ImportError: cannot import name ConnectionPool
While testing my application using nosetests. I am getting some error related to import error:

The command I am using on Linux CLI is: nosetests -m test_file

```<code>======================================================================
ERROR: Failure: ImportError (cannot import name ConnectionPool)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/usr/lib/ckan/default/src/ckan/ckan/tests/views/test_admin.py", line 10, in <module>
    import ckan.tests.helpers as helpers
  File "/usr/lib/ckan/default/src/ckan/ckan/tests/helpers.py", line 32, in <module>
    import rq
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/rq/__init__.py", line 6, in <module>
    from .connections import (Connection, get_current_connection, pop_connection,
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/rq/connections.py", line 7, in <module>
    from redis import StrictRedis
  File "/usr/lib/ckan/default/src/ckan/ckan/lib/redis.py", line 15, in <module>
    from redis import ConnectionPool, Redis
ImportError: cannot import name ConnectionPool
-------------------- >> begin captured logging << --------------------
pyutilib.component.core.pca: DEBUG: Creating PluginEnvironment 'pca'
pyutilib.component.core.<default>: DEBUG: Creating PluginEnvironment '<default>'
pyutilib.component.core.<default>: DEBUG: Pushing environment '<default>' on the PluginGlobals stack
pyutilib.component.core.pca: DEBUG: Pushing environment 'pca' on the PluginGlobals stack
pyutilib.component.core.pca: DEBUG: Pushing environment 'pca' on the PluginGlobals stack
pyutilib.component.core.pca: INFO: Adding service IgnorePluginPlugins to environment pca
pyutilib.component.core.pca: INFO: Adding service IgnorePluginPlugins to environment pca
pyutilib.component.core.pca: DEBUG: Popping environment 'pca' from the PluginGlobals stack
passlib.utils.compat: DEBUG: loaded lazy attr 'BytesIO': <built-in function StringIO>
passlib.registry: DEBUG: registered 'pbkdf2_sha512' handler: <class 'passlib.handlers.pbkdf2.pbkdf2_sha512'>
--------------------- >> end captured logging << ---------------------

----------------------------------------------------------------------
Ran 1 test in 0.001s
</code>```

I had a searched for it and found that my redis.py is I guess being accessed before the redis module.

For more reference: https://gist.github.com/camfindlay/a8c080435960fe87388474839418f0f0#file-gistfile1-txt-L154

So, for this I had set my PYTHONPATH and PATH.

The Output of echo $PATH is as follows:

```<code>echo $PATH
/usr/lib/ckan/default/bin:/home/ubuntu64/bin:/home/ubuntu64/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/bin/python
</code>```

But I am still not able to resolve the issue.

Update 1:
Attaching the error logs appearing on screen:

答:
It looks like the file at /ckan/lib/redis.py is conflicting with your redis package.

Can you use a virtual environment and install all dependencies?

After you are done with it, you can use following code -

```<code>from .redis import *  #For importing something from your redis.py
from redis import ConnectionPool  #For importing from redis module
</code>```

Hope this helps.
Cheers.

Body:
While testing my application using nosetests. I am getting some error related to import error:

The command I am using on Linux CLI is: nosetests -m test_file

======================================================================
ERROR: Failure: ImportError (cannot import name ConnectionPool)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/usr/lib/ckan/default/src/ckan/ckan/tests/views/test_admin.py", line 10, in <module>
    import ckan.tests.helpers as helpers
  File "/usr/lib/ckan/default/src/ckan/ckan/tests/helpers.py", line 32, in <module>
    import rq
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/rq/__init__.py", line 6, in <module>
    from .connections import (Connection, get_current_connection, pop_connection,
  File "/usr/lib/ckan/default/local/lib/python2.7/site-packages/rq/connections.py", line 7, in <module>
    from redis import StrictRedis
  File "/usr/lib/ckan/default/src/ckan/ckan/lib/redis.py", line 15, in <module>
    from redis import ConnectionPool, Redis
ImportError: cannot import name ConnectionPool
-------------------- >> begin captured logging << --------------------
pyutilib.component.core.pca: DEBUG: Creating PluginEnvironment 'pca'
pyutilib.component.core.<default>: DEBUG: Creating PluginEnvironment '<default>'
pyutilib.component.core.<default>: DEBUG: Pushing environment '<default>' on the PluginGlobals stack
pyutilib.component.core.pca: DEBUG: Pushing environment 'pca' on the PluginGlobals stack
pyutilib.component.core.pca: DEBUG: Pushing environment 'pca' on the PluginGlobals stack
pyutilib.component.core.pca: INFO: Adding service IgnorePluginPlugins to environment pca
pyutilib.component.core.pca: INFO: Adding service IgnorePluginPlugins to environment pca
pyutilib.component.core.pca: DEBUG: Popping environment 'pca' from the PluginGlobals stack
passlib.utils.compat: DEBUG: loaded lazy attr 'BytesIO': <built-in function StringIO>
passlib.registry: DEBUG: registered 'pbkdf2_sha512' handler: <class 'passlib.handlers.pbkdf2.pbkdf2_sha512'>
--------------------- >> end captured logging << ---------------------

----------------------------------------------------------------------
Ran 1 test in 0.001s

I had a searched for it and found that my redis.py is I guess being accessed before the redis module.

For more reference: https://gist.github.com/camfindlay/a8c080435960fe87388474839418f0f0#file-gistfile1-txt-L154

So, for this I had set my PYTHONPATH and PATH.

The Output of echo $PATH is as follows:

echo $PATH
/usr/lib/ckan/default/bin:/home/ubuntu64/bin:/home/ubuntu64/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/bin/python

But I am still not able to resolve the issue.

Update 1:
Attaching the error logs appearing on screen:

Body:
It looks like the file at /ckan/lib/redis.py is conflicting with your redis package.

Can you use a virtual environment and install all dependencies?

After you are done with it, you can use following code -

from .redis import *  #For importing something from your redis.py
from redis import ConnectionPool  #For importing from redis module

Hope this helps.
Cheers.


问:
Multiple check box options in ReactJS
I'm pretty new with react and I was having problems with creating check boxes for my application. I was able to setup something that works for only one checkbox option, however the problem I have now is for multiple check box options.

Whenever I click on one checkbox, it automatically selects all other check boxes

Here's the code I'm currently working on.

```<code>import React, { Component, } from 'react';

export default class Checkbox extends Component {
    constructor(props) {
        super();

        let initialState = {
            options: [{ id: 1, answer: 'Apple' }, { id: 2, answer: 'Bananas' }, { id: 3, answer: 'Oranges' }],
            isChecked: false,
        };
        this.state = initialState;
    }

    handleCheckbox() {
        this.setState({
            isChecked: !this.state.isChecked
        })
    }

    render() {
        return (
            <div>
                {
                    [...this.state.options].map((e, i) => {
                        return (
                            <label key={e.id}>
                                <input type="checkbox"

                                    disabled={this.props.disabled}

                                    onChange={() => this.handleCheckbox()}

                                    checked={this.state.isChecked}

                                    key={e.id}
                                />

                                {e.answer}
                          </label>
                        )
                    })
                }
            </div>
        )

    }

}
</code>```

答:
You need move isChecked inside options:

```<code>import React, { Component, } from 'react';

export default class Checkbox extends Component {
    constructor(props) {
        super();

        let initialState = {
            options: [{ id: 1, answer: 'Apple', isChecked:false }, { id: 2, answer: 'Bananas', isChecked:false }, { id: 3, answer: 'Oranges', isChecked:false }],
        };
        this.state = initialState;
    }

    handleCheckbox(ind) {
        const newOptions = [...this.state.options];

        newOptions[ind].isChecked = !newOptions[ind].isChecked;

        this.setState({
            options: newOptions
        })
    }

    render() {
        return (
            <div>
                {
                    [...this.state.options].map((e, i) => {
                        return (
                            <label key={e.id}>
                                <input type="checkbox"

                                    disabled={this.props.disabled}

                                    onChange={() => this.handleCheckbox(i)}

                                    checked={e.isChecked}

                                    key={e.id}
                                />

                                {e.answer}
                          </label>
                        )
                    })
                }
            </div>
        )

    }

}

</code>```

Title: Multiple check box options in ReactJS

Body:
I'm pretty new with react and I was having problems with creating check boxes for my application. I was able to setup something that works for only one checkbox option, however the problem I have now is for multiple check box options.

Whenever I click on one checkbox, it automatically selects all other check boxes

Here's the code I'm currently working on.

import React, { Component, } from 'react';

export default class Checkbox extends Component {
    constructor(props) {
        super();

        let initialState = {
            options: [{ id: 1, answer: 'Apple' }, { id: 2, answer: 'Bananas' }, { id: 3, answer: 'Oranges' }],
            isChecked: false,
        };
        this.state = initialState;
    }

    handleCheckbox() {
        this.setState({
            isChecked: !this.state.isChecked
        })
    }

    render() {
        return (

                {
                    [...this.state.options].map((e, i) => {
                        return (

                                <input type="checkbox"

                                    disabled={this.props.disabled}

                                    onChange={() => this.handleCheckbox()}

                                    checked={this.state.isChecked}

                                    key={e.id}
                                />

                                {e.answer}

                        )
                    })
                }

        )

    }

}

Body:
You need move isChecked inside options:

import React, { Component, } from 'react';

export default class Checkbox extends Component {
    constructor(props) {
        super();

        let initialState = {
            options: [{ id: 1, answer: 'Apple', isChecked:false }, { id: 2, answer: 'Bananas', isChecked:false }, { id: 3, answer: 'Oranges', isChecked:false }],
        };
        this.state = initialState;
    }

    handleCheckbox(ind) {
        const newOptions = [...this.state.options];

        newOptions[ind].isChecked = !newOptions[ind].isChecked;

        this.setState({
            options: newOptions
        })
    }

    render() {
        return (
            <div>
                {
                    [...this.state.options].map((e, i) => {
                        return (
                            <label key={e.id}>
                                <input type="checkbox"

                                    disabled={this.props.disabled}

                                    onChange={() => this.handleCheckbox(i)}

                                    checked={e.isChecked}

                                    key={e.id}
                                />

                                {e.answer} &nbsp;
                          </label>
                        )
                    })
                }
            </div>
        )

    }

}


问:
Find duplicate for a combination of rows - Oracle SQL
I have a table:

table1

```<code>unique_id       user_id   user_seq      col_name            value_val    position
1               100       1             test1               100          1
1               100       1             test2               123          1
1               100       1             test1               a            2
1               100       1             test2               text         2
1               100       1             test3               1Rw          2
1               100       1             test4               1Tes         2

2               101       1             test1               1            1
2               101       1             test2               1            1
2               101       1             test3               1            1
2               101       1             test4               1            1
2               101       1             test5               1            1

3               100       1             test1               100          1
3               100       1             test2               123          1
3               100       1             test1               a            2
3               100       1             test2               text         2
3               100       1             test3               1Rw          2
3               100       1             test4               1Tes         2

4               101       1             test1               1            1
4               101       1             test2               1            1
4               101       1             test3               1            1
4               101       1             test4               1            1
</code>```

I need to find duplicate based on the following:

user_id, user_seq, col_name, value_val and position should be exactly same for different unique_id.

In the above example, unique_id - 1 and 3 are EXACTLY same, so they should be returned as output.

For unique_id = 2 and 4, there is a difference of test5 not available for unique_id = 4, so it won't be captured.

Output would be:

```<code>unique_id
1
3
</code>```

Also, my dataset is huge, around 50 million records, so need an optimized solution. Any help?

EDIT

My table structure:

```<code>Name        Null? Type
----------- ----- --------------
UNIQUE_ID          NUMBER
USER_SEQ           VARCHAR2(100)
COL_NAME           VARCHAR2(263)
VALUE_VAL          VARCHAR2(4000)
POSITION           NUMBER
USER_ID            NUMBER
</code>```

No indexes available.

答:
Here's one way of doing it:

```<code>with sample_data as (select 1 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, '100' value_val, 1 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, '123' value_val, 1 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, 'a' value_val, 2 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, 'text' value_val, 2 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test3' col_name, '1Rw' value_val, 2 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test4' col_name, '1Tes' value_val, 2 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test1' col_name, '1' value_val, 1 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test2' col_name, '1' value_val, 1 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test3' col_name, '1' value_val, 1 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test4' col_name, '1' value_val, 1 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test5' col_name, '1' value_val, 1 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, '100' value_val, 1 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, '123' value_val, 1 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, 'a' value_val, 2 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, 'text' value_val, 2 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test3' col_name, '1Rw' value_val, 2 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test4' col_name, '1Tes' value_val, 2 position from dual union all
                     select 4 unique_id, 101 user_id, 1 user_seq, 'test1' col_name, '1' value_val, 1 position from dual union all
                     select 4 unique_id, 101 user_id, 1 user_seq, 'test2' col_name, '1' value_val, 1 position from dual union all
                     select 4 unique_id, 101 user_id, 1 user_seq, 'test3' col_name, '1' value_val, 1 position from dual union all
                     select 4 unique_id, 101 user_id, 1 user_seq, 'test4' col_name, '1' value_val, 1 position from dual union all
                     select 6 unique_id, 101 user_id, 1 user_seq, 'test1' col_name, '1' value_val, 1 position from dual union all
                     select 6 unique_id, 101 user_id, 1 user_seq, 'test2' col_name, '1' value_val, 1 position from dual union all
                     select 6 unique_id, 101 user_id, 1 user_seq, 'test3' col_name, '1' value_val, 1 position from dual union all
                     select 6 unique_id, 101 user_id, 1 user_seq, 'test4' col_name, '1' value_val, 1 position from dual union all
                     select 7 unique_id, 101 user_id, 1 user_seq, 'test1' col_name, '1' value_val, 1 position from dual union all
                     select 7 unique_id, 101 user_id, 1 user_seq, 'test2' col_name, '1' value_val, 1 position from dual union all
                     select 7 unique_id, 101 user_id, 1 user_seq, 'test3' col_name, '1' value_val, 1 position from dual union all
                     select 7 unique_id, 101 user_id, 1 user_seq, 'test4' col_name, '1' value_val, 1 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, '100' value_val, 1 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, '123' value_val, 1 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, 'a' value_val, 2 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, 'text' value_val, 2 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test3' col_name, '1Rw' value_val, 2 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test4' col_name, '1Tes' value_val, 2 position from dual),
            cnts as (select unique_id,
                            user_id,
                            user_seq,
                            col_name,
                            value_val,
                            position,
                            count(*) over (partition by unique_id) cnt
                     from   sample_data),
             res as (select distinct sd1.unique_id id1,
                                     sd2.unique_id id2,
                                     sd1.cnt,
                                     count(*) over (partition by sd1.unique_id, sd2.unique_id) total_id1_rows_cnt
                     from   cnts sd1
                            inner join cnts sd2 on sd1.unique_id < sd2.unique_id
                                                   and sd1.user_id = sd2.user_id
                                                   and sd1.user_seq = sd2.user_seq
                                                   and sd1.col_name = sd2.col_name
                                                   and sd1.value_val = sd2.value_val
                                                   and sd1.position = sd2.position
                                                   and sd1.cnt = sd2.cnt)
select id1||','||listagg(id2, ',') within group (order by id2) grouped_unique_ids
from   res
where  id1 not in (select id2
                   from   res)
and    cnt = total_id1_rows_cnt
group by id1
order by grouped_unique_ids;
</code>```

And here's the db<>fiddle to prove it works

Body:
I have a table:

table1

unique_id       user_id   user_seq      col_name            value_val    position
1               100       1             test1               100          1
1               100       1             test2               123          1
1               100       1             test1               a            2
1               100       1             test2               text         2
1               100       1             test3               1Rw          2
1               100       1             test4               1Tes         2

2               101       1             test1               1            1
2               101       1             test2               1            1
2               101       1             test3               1            1
2               101       1             test4               1            1
2               101       1             test5               1            1

3               100       1             test1               100          1
3               100       1             test2               123          1
3               100       1             test1               a            2
3               100       1             test2               text         2
3               100       1             test3               1Rw          2
3               100       1             test4               1Tes         2

4               101       1             test1               1            1
4               101       1             test2               1            1
4               101       1             test3               1            1
4               101       1             test4               1            1

I need to find duplicate based on the following:

user_id, user_seq, col_name, value_val and position should be exactly same for different unique_id.

In the above example, unique_id - 1 and 3 are EXACTLY same, so they should be returned as output.

For unique_id = 2 and 4, there is a difference of test5 not available for unique_id = 4, so it won't be captured.

Output would be:

unique_id
1
3

Also, my dataset is huge, around 50 million records, so need an optimized solution. Any help?

EDIT

My table structure:

Name        Null? Type
----------- ----- --------------
UNIQUE_ID          NUMBER
USER_SEQ           VARCHAR2(100)
COL_NAME           VARCHAR2(263)
VALUE_VAL          VARCHAR2(4000)
POSITION           NUMBER
USER_ID            NUMBER

No indexes available.

Body:
Here's one way of doing it:

with sample_data as (select 1 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, '100' value_val, 1 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, '123' value_val, 1 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, 'a' value_val, 2 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, 'text' value_val, 2 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test3' col_name, '1Rw' value_val, 2 position from dual union all
                     select 1 unique_id, 100 user_id, 1 user_seq, 'test4' col_name, '1Tes' value_val, 2 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test1' col_name, '1' value_val, 1 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test2' col_name, '1' value_val, 1 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test3' col_name, '1' value_val, 1 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test4' col_name, '1' value_val, 1 position from dual union all
                     select 2 unique_id, 101 user_id, 1 user_seq, 'test5' col_name, '1' value_val, 1 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, '100' value_val, 1 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, '123' value_val, 1 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, 'a' value_val, 2 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, 'text' value_val, 2 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test3' col_name, '1Rw' value_val, 2 position from dual union all
                     select 3 unique_id, 100 user_id, 1 user_seq, 'test4' col_name, '1Tes' value_val, 2 position from dual union all
                     select 4 unique_id, 101 user_id, 1 user_seq, 'test1' col_name, '1' value_val, 1 position from dual union all
                     select 4 unique_id, 101 user_id, 1 user_seq, 'test2' col_name, '1' value_val, 1 position from dual union all
                     select 4 unique_id, 101 user_id, 1 user_seq, 'test3' col_name, '1' value_val, 1 position from dual union all
                     select 4 unique_id, 101 user_id, 1 user_seq, 'test4' col_name, '1' value_val, 1 position from dual union all
                     select 6 unique_id, 101 user_id, 1 user_seq, 'test1' col_name, '1' value_val, 1 position from dual union all
                     select 6 unique_id, 101 user_id, 1 user_seq, 'test2' col_name, '1' value_val, 1 position from dual union all
                     select 6 unique_id, 101 user_id, 1 user_seq, 'test3' col_name, '1' value_val, 1 position from dual union all
                     select 6 unique_id, 101 user_id, 1 user_seq, 'test4' col_name, '1' value_val, 1 position from dual union all
                     select 7 unique_id, 101 user_id, 1 user_seq, 'test1' col_name, '1' value_val, 1 position from dual union all
                     select 7 unique_id, 101 user_id, 1 user_seq, 'test2' col_name, '1' value_val, 1 position from dual union all
                     select 7 unique_id, 101 user_id, 1 user_seq, 'test3' col_name, '1' value_val, 1 position from dual union all
                     select 7 unique_id, 101 user_id, 1 user_seq, 'test4' col_name, '1' value_val, 1 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, '100' value_val, 1 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, '123' value_val, 1 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test1' col_name, 'a' value_val, 2 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test2' col_name, 'text' value_val, 2 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test3' col_name, '1Rw' value_val, 2 position from dual union all
                     select 5 unique_id, 100 user_id, 1 user_seq, 'test4' col_name, '1Tes' value_val, 2 position from dual),
            cnts as (select unique_id,
                            user_id,
                            user_seq,
                            col_name,
                            value_val,
                            position,
                            count(*) over (partition by unique_id) cnt
                     from   sample_data),
             res as (select distinct sd1.unique_id id1,
                                     sd2.unique_id id2,
                                     sd1.cnt,
                                     count(*) over (partition by sd1.unique_id, sd2.unique_id) total_id1_rows_cnt
                     from   cnts sd1
                            inner join cnts sd2 on sd1.unique_id < sd2.unique_id
                                                   and sd1.user_id = sd2.user_id
                                                   and sd1.user_seq = sd2.user_seq
                                                   and sd1.col_name = sd2.col_name
                                                   and sd1.value_val = sd2.value_val
                                                   and sd1.position = sd2.position
                                                   and sd1.cnt = sd2.cnt)
select id1||','||listagg(id2, ',') within group (order by id2) grouped_unique_ids
from   res
where  id1 not in (select id2
                   from   res)
and    cnt = total_id1_rows_cnt
group by id1
order by grouped_unique_ids;

And here's the db<>fiddle to prove it works


问:
How to turn around strings in dataframe
I have a name, something like Robin the Bruyne or Victor from the Loo
These names are in a dataframe in my session. I need to change these names into:

<lastname, firstname middlename(s)>,

so they are turn arouned. But I don't know how to do this.

I know I can use things like separate() or map() with PURR (of tidyverse).

Data:

```<code>  ~nr,            ~name,        ~prodno,
  2019001,       "Piet de Boer", "lux_zwez",
  2019002,       "Elly Hamstra",  "zuv_vla",
  2019003, "Sue Ellen Schilder",  "zuv_vla",
  2019004,      "Truus Janssen", "zuv_vmlk",
  2019005,  "Evelijne de Vries", "lux_zwez",
  2019006,     "Berend Boersma", "lux_gras",
  2019007,   "Marius van Asten",  "zuv_vla",
  2019008,     "Corneel Jansen", "lux_gras",
  2019009,     "Joke Timmerman",  "zuv_vla",
  2019010, "Jan Willem de Jong", "lux_zwez",
  2019011,   "Frederik Janssen", "zuv_vmlk",
  2019012,   "Antonia de Jongh", "zuv_vmlk",
  2019013,   "Lena van der Loo",  "zuv_qrk",
  2019014,   "Johanna Haanstra", "lux_gras"
</code>```

答:
We can try using sub here:

```<code>names <- c("Robin the Bruyne", "Victor from the Loo")
output <- sub("^(.*) ([A-Z][a-z]+)$", "\\2, \\1", names)
output

[1] "Bruyne, Robin the"    "Loo, Victor from the"
</code>```

This approach uses the following pattern:

```<code>^(.*)          capture everything from the start until the last space
([A-Z][a-z]+)$ capture the last name, which starts with a capital
</code>```

Then, we replace with the last name and first/middle names swapped, separated by a comma.

Title: How to turn around strings in dataframe

Body:
I have a name, something like Robin the Bruyne or Victor from the Loo
These names are in a dataframe in my session. I need to change these names into:

<lastname, firstname middlename(s)>,

so they are turn arouned. But I don't know how to do this.

I know I can use things like separate() or map() with PURR (of tidyverse).

Data:

  ~nr,            ~name,        ~prodno,
  2019001,       "Piet de Boer", "lux_zwez",
  2019002,       "Elly Hamstra",  "zuv_vla",
  2019003, "Sue Ellen Schilder",  "zuv_vla",
  2019004,      "Truus Janssen", "zuv_vmlk",
  2019005,  "Evelijne de Vries", "lux_zwez",
  2019006,     "Berend Boersma", "lux_gras",
  2019007,   "Marius van Asten",  "zuv_vla",
  2019008,     "Corneel Jansen", "lux_gras",
  2019009,     "Joke Timmerman",  "zuv_vla",
  2019010, "Jan Willem de Jong", "lux_zwez",
  2019011,   "Frederik Janssen", "zuv_vmlk",
  2019012,   "Antonia de Jongh", "zuv_vmlk",
  2019013,   "Lena van der Loo",  "zuv_qrk",
  2019014,   "Johanna Haanstra", "lux_gras"

Body:
We can try using sub here:

names <- c("Robin the Bruyne", "Victor from the Loo")
output <- sub("^(.*) ([A-Z][a-z]+)$", "\\2, \\1", names)
output

[1] "Bruyne, Robin the"    "Loo, Victor from the"

This approach uses the following pattern:

^(.*)          capture everything from the start until the last space
([A-Z][a-z]+)$ capture the last name, which starts with a capital

Then, we replace with the last name and first/middle names swapped, separated by a comma.


问:
ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems
ReSharper Code cleanup feature (with "reorder members" and "reformat code" enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template.

Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc. ? Is there a chance that it causes many undesired conflicts ?

Thank you.

答:
It definitely could cause conflicts.

If you want to use this in a multi-user environment then the configuration of Resharper needs to format your code to a set of standards which are enforced in your organization regardless of whether users make use of Resharper or not.

That way you are using the tool to ensure your own code meets the standards, not blanket applying your preferences to the whole codebase.

OwnerDisplayName: Romain Verdier

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Sarcastic


问:
Subversion: Tag and commit modified files at once
I want to do something like this from within Eclipse: http://svn.collab.net/viewvc/svn?view=rev&revision=33845

I use Subversive 0.7.5 with the Native JavaHL 1.5.3 (r33570) Connector.

I tried to change something in a my working copy of a branch i'd like to tag and creating a Tag with Team -> Tag... But I got the error message:

Tag operation for some of selected resources failed.

A path under version control is needed for this operation

I tried only a tag name and one with full repository path. Both resulted in the same error.
This is the error I get:

```<code>*** Tag
svn copy "C:/workspace/some_branch" "http://server:8080/svn/project/tags/TagWithChange" -r WORKING -m "TagWithChange" --username "masi"
A path under version control is needed for this operation
</code>```

Is it possible from within Eclipse?

How would you do something like this from the command line? See my own answer.

Though if I use the following at the command line I get an error:

```<code>svn copy "C:/workspace/some_branch" "http://server:8080/svn/project/tags/TagWithChange" -r WORKING -m "TagWithChange" --username "masi"
</code>```

Error:

svn: Syntax error in revision argument 'WORKING'

I'm using the svn client 1.5.4.

答:
I've found this same error when I used the Native JavaHL.  You can do two things to make your tag.

A. Tag From SVN Respository Exploring Perspective

SVN Repositories View

Right click on the trunk you'd like to tag, New -> Tag.

B. Update SVN Connector

SVN Kit (SVN/1.5.5 SVNKit/1.2.2 (http://svnkit.com/) r5428)

Install SVN Kit through software updates.

Window -> Prefs -> Team -> SVN -> SVN Connector -> SVN Connector

OwnerDisplayName: masi

Body:
I want to do something like this from within Eclipse: http://svn.collab.net/viewvc/svn?view=rev&revision=33845

I use Subversive 0.7.5 with the Native JavaHL 1.5.3 (r33570) Connector.

I tried to change something in a my working copy of a branch i'd like to tag and creating a Tag with Team -> Tag... But I got the error message:

Tag operation for some of selected resources failed.

A path under version control is needed for this operation

I tried only a tag name and one with full repository path. Both resulted in the same error.
This is the error I get:

*** Tag
svn copy "C:/workspace/some_branch" "http://server:8080/svn/project/tags/TagWithChange" -r WORKING -m "TagWithChange" --username "masi"
A path under version control is needed for this operation

Is it possible from within Eclipse?

How would you do something like this from the command line? See my own answer.

Though if I use the following at the command line I get an error:

svn copy "C:/workspace/some_branch" "http://server:8080/svn/project/tags/TagWithChange" -r WORKING -m "TagWithChange" --username "masi"

Error:

svn: Syntax error in revision argument 'WORKING'

I'm using the svn client 1.5.4.

LastEditorDisplayName: masi


问:
How to navigate to detail page using Flatlist
I'm building an app using react-native (expo) firebase and flamelink as cms and I need to create a project list with some landing pages on project.I used flatlist to render my list of project but now I need to navigate from a project card to a detail page. What am I doing wrong ?

```<code>import React from 'react';
import {
    Image,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    TextInput,
    FlatList,
    Button,
    Alert,
    CameraRoll,
    TouchableHighlight,
} from 'react-native';
import {
    widthPercentageToDP as wp,
    heightPercentageToDP as hp
} from 'react-native-responsive-screen';
import * as firebase from 'firebase';
import {NavigationAction,StackNavigator, withNavigation} from 'react-navigation';

class secondScreen extends React.Component {

    static navigationOptions = {
        tabBarLabel:'Axian et les ODDD'
    }

    state = {
        item:[]
    }

    componentDidMount() {
        firebase.database().ref('databaseRefFitHere').once("value", snapshot => {
            const item = [];
            snapshot.forEach(function (childSnapshot) {
                var data = childSnapshot.val();
                item.push(data);
            });
            this.setState({
                item
            });
        });
    }

renderRow ({ item }) {

    return (
      <TouchableHighlight style={styles.container}  onPress={()=> {this.props.navigation.navigate("Details")}}>
      <View>
       <Image
            style={{width:wp('90%'), height: 150}}
                        source= {{uri:item.imgUrl}}
                    />
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.sum}>{item.summary}</Text>
        </View>
      </TouchableHighlight>
    );
}

    render(){
        return(
            <View style={{
                flex:1,
                justifyContent:'center',
                alignItems:'center',
                backgroundColor: '#C80F2D'

            }}>
            <FlatList
                data={this.state.item}
                renderItem={this.renderRow}
                keyExtractor={item => item.title}
            />
            </View>
        )
    }

}
export default withNavigation(secondScreen);

const styles = StyleSheet.create({

    container: {
        flexDirection: 'column',
        marginVertical: 20,
        marginHorizontal: wp('5%'),
        backgroundColor:'#FFF',
        width:wp('90%'),
        shadowColor: "#000",
            shadowOffset: {
                width: 0,
                height: 2,
            },
            shadowOpacity: 0.25,
            shadowRadius: 3.84,

            elevation: 5,

    },
    title:{
        fontFamily: 'circular-bold',
        fontSize: 20,
        marginHorizontal: 10,
        marginTop:10,
        color: '#000',
    },
    sum:{
        fontFamily: 'circular-mono',
        fontSize:14,
        color: '#000',
        margin:10,
    }

});
</code>```

I've got the classic undefined is not an object (evaluating 'this3.props.navigation') as an response.

答:
Make it arrow function:

```<code>renderRow = ({ item }) => {
return (
  <TouchableHighlight style={styles.container}  onPress={()=> {this.props.navigation.navigate("Details")}}>
  <View>
   <Image
        style={{width:wp('90%'), height: 150}}
                    source= {{uri:item.imgUrl}}
                />
    <Text style={styles.title}>{item.title}</Text>
    <Text style={styles.sum}>{item.summary}</Text>
    </View>
  </TouchableHighlight>
);
}
</code>```

and The FlatList:

```<code><FlatList
      data={this.state.item}
      renderItem={ ({item, index}) => this.renderRow(item)}
      keyExtractor={item => item.title}
/>
</code>```

Body:
I'm building an app using react-native (expo) firebase and flamelink as cms and I need to create a project list with some landing pages on project.I used flatlist to render my list of project but now I need to navigate from a project card to a detail page. What am I doing wrong ?

import React from 'react';
import {
    Image,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    TextInput,
    FlatList,
    Button,
    Alert,
    CameraRoll,
    TouchableHighlight,
} from 'react-native';
import {
    widthPercentageToDP as wp,
    heightPercentageToDP as hp
} from 'react-native-responsive-screen';
import * as firebase from 'firebase';
import {NavigationAction,StackNavigator, withNavigation} from 'react-navigation';

class secondScreen extends React.Component {

    static navigationOptions = {
        tabBarLabel:'Axian et les ODDD'
    }

    state = {
        item:[]
    }

    componentDidMount() {
        firebase.database().ref('databaseRefFitHere').once("value", snapshot => {
            const item = [];
            snapshot.forEach(function (childSnapshot) {
                var data = childSnapshot.val();
                item.push(data);
            });
            this.setState({
                item
            });
        });
    }

renderRow ({ item }) {

    return (
      <TouchableHighlight style={styles.container}  onPress={()=> {this.props.navigation.navigate("Details")}}>
      <View>
       <Image
            style={{width:wp('90%'), height: 150}}
                        source= {{uri:item.imgUrl}}
                    />
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.sum}>{item.summary}</Text>
        </View>
      </TouchableHighlight>
    );
}

    render(){
        return(
            <View style={{
                flex:1,
                justifyContent:'center',
                alignItems:'center',
                backgroundColor: '#C80F2D'

            }}>
            <FlatList
                data={this.state.item}
                renderItem={this.renderRow}
                keyExtractor={item => item.title}
            />
            </View>
        )
    }

}
export default withNavigation(secondScreen);

const styles = StyleSheet.create({

    container: {
        flexDirection: 'column',
        marginVertical: 20,
        marginHorizontal: wp('5%'),
        backgroundColor:'#FFF',
        width:wp('90%'),
        shadowColor: "#000",
            shadowOffset: {
                width: 0,
                height: 2,
            },
            shadowOpacity: 0.25,
            shadowRadius: 3.84,

            elevation: 5,

    },
    title:{
        fontFamily: 'circular-bold',
        fontSize: 20,
        marginHorizontal: 10,
        marginTop:10,
        color: '#000',
    },
    sum:{
        fontFamily: 'circular-mono',
        fontSize:14,
        color: '#000',
        margin:10,
    }

});

I've got the classic undefined is not an object (evaluating 'this3.props.navigation') as an response.

Body:
Make it arrow function:

renderRow = ({ item }) => {
return (
  <TouchableHighlight style={styles.container}  onPress={()=> {this.props.navigation.navigate("Details")}}>
  <View>
   <Image
        style={{width:wp('90%'), height: 150}}
                    source= {{uri:item.imgUrl}}
                />
    <Text style={styles.title}>{item.title}</Text>
    <Text style={styles.sum}>{item.summary}</Text>
    </View>
  </TouchableHighlight>
);
}

and The FlatList:

<FlatList
      data={this.state.item}
      renderItem={ ({item, index}) => this.renderRow(item)}
      keyExtractor={item => item.title}
/>


问:
Invalid identifier: ORA ORA-00904; Hibernate ignoring Intellij-IDEA generated @Column (name="") annotation on getter
I have a Spring boot application (2.1.5) using Hibernate (5.1), as my JPA provider, accessing an Oracle 11.2.0.4 DB, with Hibernate Dialect Oracle10gDialect

I have created a repo like this

```<code>@Repository
public interface VehStoRepository extends CrudRepository<VehStoEntity, Long>
{
}
</code>```

and my Entity is as follows

```<code>@Entity @Table(name = "VEH_STO", schema = "MySchema")
public class  VehStoEntity
{
  @Id
  private long eventNo;
  private Long stoType;

  Basic @Column(name = "STO_TYPE", nullable = true, precision = 0)
  public Long getStoType()
  {
    return stoType;
  }

  public void setStoType(Long stoType)
  {
    this.stoType = stoType;
  }
...
}
</code>```

With many other fields etc, that I have excluded for brevity. I had the persistence mapping generated by Intellj Idea.

Now, when calling
vehStoRepository.findAll();

I get the following error:

Caused by:
  org.springframework.dao.InvalidDataAccessResourceUsageException: could
  not extract ResultSet; SQL [n/a]; nested exception is
  org.hibernate.exception.SQLGrammarException: could not extract ResultSet

...

Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "VEHSTOENT0_"."STOTYPE": invalid identifier

My SQL statement as the logs show it is:

Hibernate: select vehstoent0_.stoType as stoType25_0_ from MYSCHEMA.VEH_STO vehstoent0_

My question is: does hibernate actually add ent0 to the entity name or is this just weird logging, or is this the cause of the error? Is this because I have not generated an ORM mapping schema for all tables, just for the one I needed? What am I doing wrong?

答:
It was this:

My sql table was a view, so I assume that's why Intellij didn't create an @Id annotation.
So i created the @Id manually over the field, but Intellij had the  @Column (name="")

annotation on the getter, which Hibernate then ignored.

I have solved the problem by moving all annotations to the fields instead.

Body:
I have a Spring boot application (2.1.5) using Hibernate (5.1), as my JPA provider, accessing an Oracle 11.2.0.4 DB, with Hibernate Dialect Oracle10gDialect

I have created a repo like this

@Repository
public interface VehStoRepository extends CrudRepository<VehStoEntity, Long>
{
}

and my Entity is as follows

@Entity @Table(name = "VEH_STO", schema = "MySchema")
public class  VehStoEntity
{
  @Id
  private long eventNo;
  private Long stoType;

  Basic @Column(name = "STO_TYPE", nullable = true, precision = 0)
  public Long getStoType()
  {
    return stoType;
  }

  public void setStoType(Long stoType)
  {
    this.stoType = stoType;
  }
...
}

With many other fields etc, that I have excluded for brevity. I had the persistence mapping generated by Intellj Idea.

Now, when calling
vehStoRepository.findAll();

I get the following error:

Caused by:
  org.springframework.dao.InvalidDataAccessResourceUsageException: could
  not extract ResultSet; SQL [n/a]; nested exception is
  org.hibernate.exception.SQLGrammarException: could not extract ResultSet

...

Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "VEHSTOENT0_"."STOTYPE": invalid identifier

My SQL statement as the logs show it is:

Hibernate: select vehstoent0_.stoType as stoType25_0_ from MYSCHEMA.VEH_STO vehstoent0_

My question is: does hibernate actually add ent0 to the entity name or is this just weird logging, or is this the cause of the error? Is this because I have not generated an ORM mapping schema for all tables, just for the one I needed? What am I doing wrong?


问:
How to remove any unicode repeating letter?
In english, sometimes you have repeating letter like this :
hello my hero hhhhhhhhhhh that's for h, but I want to remove all kinds of letters repeating like this 2 or more times and replace them with a space in unicode letter. I have arabic here. I only have one letter I can remove, this is my code:

```<code>#remove laughing
def remove_laughs(self, text):
    text=re.sub("ه{2,}", "", text)
    return text
</code>```

答:
any duplicated character

```<code>import re
re.sub(r'(.)\1+', ' ', 'مرحبا هههههههههه')
# 'مرحبا  '
</code>```

only letter characters

```<code>import regex
regex.sub(r'(\pL)\1+', ' ', 'مرحبا هههههههههه')
</code>```

Body:
In english, sometimes you have repeating letter like this :
hello my hero hhhhhhhhhhh that's for h, but I want to remove all kinds of letters repeating like this 2 or more times and replace them with a space in unicode letter. I have arabic here. I only have one letter I can remove, this is my code:

#remove laughing
def remove_laughs(self, text):
    text=re.sub("ه{2,}", "", text)
    return text

Body:
any duplicated character

import re
re.sub(r'(.)\1+', ' ', 'مرحبا هههههههههه')
# 'مرحبا  '

only letter characters

import regex
regex.sub(r'(\pL)\1+', ' ', 'مرحبا هههههههههه')


问:
PHP: allow_url_include
Quick...possibly stupid question.

When allow_url_include is set to off, does that prohibit other computers from remotely including the files on my site, or does it say that I'm not allowed to remotely include files from other sites?

答:
It's always impossible to include PHP code from properly installed server, no matter of this configuration setting.

At the same time no PHP configuration setting can forbid HTTP clients from requesting resources from your HTTP server.

Title: PHP: allow_url_include


问:
Retrieve the numbers from the file corresponding to the given regions specified in the file
The below is my dataframe :

```<code> Sno       Name    Region         Num
0    1      Rubin    Indore  79744001550
1    2      Rahul     Delhi  89824304549
2    3      Rohit     Noida  91611611478
3    4     Chirag     Delhi  85879761557
4    5       Shan    Bharat  95604535786
5    6      Jordi    Russia  80777784005
6    7         El    Russia  70008700104
7    8       Nino     Spain  87707101233
8    9       Mark       USA  98271377772
9   10  Pattinson  Hawk Eye  87888888889
</code>```

Retrieve the numbers and store it region wise from the given CSV file.

```<code>delhi_list = []

for i in range(len(data)):
   if data.loc[i]['Region'] == 'Delhi':
     delhi_list.append(data.loc[i]['Num'])

delhi_list = []

for i in range(len(data)):
   if data.loc[i]['Region'] == 'Delhi':
     delhi_list.append(data.loc[i]['Num'])
</code>```

I am getting the results, but I want to achieve the data by the use of dictionary in python. Can I use it?

Body:
The below is my dataframe :

 Sno       Name    Region         Num
0    1      Rubin    Indore  79744001550
1    2      Rahul     Delhi  89824304549
2    3      Rohit     Noida  91611611478
3    4     Chirag     Delhi  85879761557
4    5       Shan    Bharat  95604535786
5    6      Jordi    Russia  80777784005
6    7         El    Russia  70008700104
7    8       Nino     Spain  87707101233
8    9       Mark       USA  98271377772
9   10  Pattinson  Hawk Eye  87888888889

Retrieve the numbers and store it region wise from the given CSV file.

delhi_list = []

for i in range(len(data)):
   if data.loc[i]['Region'] == 'Delhi':
     delhi_list.append(data.loc[i]['Num'])

delhi_list = []

for i in range(len(data)):
   if data.loc[i]['Region'] == 'Delhi':
     delhi_list.append(data.loc[i]['Num'])

I am getting the results, but I want to achieve the data by the use of dictionary in python. Can I use it?

Body:
IIUC, you can use groupby, apply the list aggregation then use to_dict:

data.groupby('Region')['Num'].apply(list).to_dict()

[out]

{'Bharat': [95604535786],
 'Delhi': [89824304549, 85879761557],
 'Hawk Eye': [87888888889],
 'Indore': [79744001550],
 'Noida': [91611611478],
 'Russia': [80777784005, 70008700104],
 'Spain': [87707101233],
 'USA': [98271377772]}


问:
Spring not seen environment variables from systemd service
I'm trying to run spring boot app with systemd service of ubuntu.
In my service file, I have ExecStart variable

ExecStart=/bla/run.sh

And variables:

```<code>Environment="DB_HOSTNAME=ip"
Environment="DB_PORT=5432"
...
</code>```

(I have tried both variants: with and without braces)

My sh file looks like:

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

echo jdbc:postgresql://${DB_HOSTNAME}:${DB_PORT}/${DB_NAME}
sudo /usr/bin/java -jar bla.jar
</code>```

Inside sh variables are available as well, but spring application does not deal with them. The same with the active profile variable.

I thought that the problem is about the scope of variables and I tried to pass them to another sh from the main one. But in another script they are available, so the problem only with spring app.

Update
Trick with export does not help

答:
Maybe it will helpful for somebody.
The main problem was using sudo for starting java app.
After removing sudo variables become available.</p>

Body:
I'm trying to run spring boot app with systemd service of ubuntu.
In my service file, I have ExecStart variable

ExecStart=/bla/run.sh

And variables:

Environment="DB_HOSTNAME=ip"
Environment="DB_PORT=5432"
...

(I have tried both variants: with and without braces)

My sh file looks like:

#!/bin/sh

echo jdbc:postgresql://${DB_HOSTNAME}:${DB_PORT}/${DB_NAME}
sudo /usr/bin/java -jar bla.jar

Inside sh variables are available as well, but spring application does not deal with them. The same with the active profile variable.

I thought that the problem is about the scope of variables and I tried to pass them to another sh from the main one. But in another script they are available, so the problem only with spring app.

Update
Trick with export does not help


问:
How to properly setup activities in a Masstransit statemachine saga?
I've been fighting a lot with this problem for a couple of days, but cannot find a way that actually works.

My scenario is that I have a state machine saga where I want to do stuff in the same transaction (Entity Framework) as the saga is running in, so that the state and business things goes together.

Now, I've understood that the state machine itself should not have any dependencies, and hence there's this Activity(x => x.OfInstanceType<MyActivity>) activity that can be added which is resolved from the DI container and can have whatever dependencies (services etc) in it. So far so good...

My problem is that whatever I execute in the activity I just cannot get it to work as it should. It gets resolved from the container and the Execute method is called, but then it somehow just quits.

It appears there's some exception thrown, but that apparently doesn't bubble up to the test harness.

I'm using Microsofts' dotnet core Dependency Injection library.

Here's some code

public class MyStateMachine : MassTransitStateMachine<SagaInstance>
{
    public MyStateMachine()
    {
        InstanceState(instance => instance.CurrentState);

        Event(() => Start, x => x.CorrelateBy(saga => saga.CorrelationId, context => context.Message.CorrelationId));

        Initially(
            When(Start)
                .Activity(c => c.OfType<MyActivity>())
                .TransitionTo(Running)
                .Publish(new Started())
        );
    }

    Event<Run> Start { get; set;}
    State Running { get; set; }
}

public class MyActivity : Activity<SagaInstance, Run>
{
    private readonly IMyService _service;
    public MyActivity(IMyService service)
    {
        _service = service;
    }

    public async Task Execute(BehaviorContext<SagaInstance, Run> context, Behavior<SagaInstance, Run> next)
    {
        //throw new Exception("BOO"); // uncommenting this line doesn't throw anywhere
        _service.DoThatThing();
        await next.Execute(context).ConfigureAwait(false);
    }
}

[Fact]
public async Task RunMessageSent_NonexistingSaga_StateIsRunning()
{
    var harness = new InMemoryTestHarness();
    var machine = new MyStateMachine();

    var collection = new ServiceCollection();
    collection.AddMassTransit();
    collection.RegisterInMemorySagaRepository<SagaInstance>();
    collection.RegisterSagaStateMachine<MyStateMachine, SagaInstance>();
    collection.AddScoped<MyActivity>();
    collection.AddScoped<MyService>();

    var provider = collection.BuildServiceProvider();

    harness.OnConfigureInMemoryReceiveEndpoint += cfg => cfg.StateMachineSaga(machine, provider);

    await harness.Start();

    try
    {
        var guid = CorrelationId = Guid.NewGuid();
        await harness.InputQueueSendEndpoint.Send(new Run({CorrelationId = guid}));

        var repo = provider.GetService<ISagaRepository<SagaInstance>>() as InMemorySagaRepository<SagaInstance>;
        var saga = await repo.ShouldContainSaga(s => s.Serial == serial, timeout: TimeSpan.FromSeconds(1));

        Assert.NotNull(saga);
        // this Equal fails saying the saga is in state Initial
        Assert.Equal(machine.Running.Name, repo[saga.Value].Instance.CurrentState);
    }
    finally
    {
        await harness.Stop();
    }
}
```

答:
I was running on dotnet core 2.1 and after a lot of googling and browsing through the Masstransit repo I realized that there are better APIs for the Dependency Injection framework in the latest (5.3) Masstransit, which I didn't want to upgrade to at first to avoid having to also upgrade the dotnet runtime dependency to 2.2.

After doing the upgrade I started realizing that there has to be some async problem as I sometime got it working randomly. Then I realized that there was another method on the in mem repo, called ShouldContainSagaInState.

So by using this line instead, I got it working!

var saga = await repo.ShouldContainSagaInState(guid, machine, x => x.Running, TimeSpan.FromSeconds(1));
```

Also running the code the way I intended to do, using the Request/Response pattern, potential exceptions are sent as Fault messages back to the caller. In the test harness this message is somehow available, but I haven't looked into a proper way to check it yet.

Body:
I was running on dotnet core 2.1 and after a lot of googling and browsing through the Masstransit repo I realized that there are better APIs for the Dependency Injection framework in the latest (5.3) Masstransit, which I didn't want to upgrade to at first to avoid having to also upgrade the dotnet runtime dependency to 2.2.

After doing the upgrade I started realizing that there has to be some async problem as I sometime got it working randomly. Then I realized that there was another method on the in mem repo, called ShouldContainSagaInState.

So by using this line instead, I got it working!

var saga = await repo.ShouldContainSagaInState(guid, machine, x => x.Running, TimeSpan.FromSeconds(1));

Also running the code the way I intended to do, using the Request/Response pattern, potential exceptions are sent as Fault messages back to the caller. In the test harness this message is somehow available, but I haven't looked into a proper way to check it yet.


问:
Display QString (Qt5) content in Visual Studio 2013 debugging?
I used to google a lot about it.

I enabled Debugging -> Edit and Continue in Native Only options

I was trying to add Visualizers to Visual Studio 2013\Visualizers

vstools project on codeplex is not for 2013 seems like

but so far nothing helps...

答:
I know this question is a while back but if relevant, for VS 2013 then go to

```<code>"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Packages\Debugger\Visualizers"
</code>```

and add Code from below link in a text file and name it qt5.natvis.
For VS 2019 the location would be:

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\Packages\Debugger\Visualizers"
</code>```

Hope this helps.

pastebin code for seeing qt variables in visual studio

Body:
I know this question is a while back but if relevant, for VS 2013 then go to

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Packages\Debugger\Visualizers"

and add Code from below link in a text file and name it qt5.natvis.
For VS 2019 the location would be:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\Packages\Debugger\Visualizers"

Hope this helps.

pastebin code for seeing qt variables in visual studio


问:
Swap elements in array without creating new array
I was asked for a method to return the arr if element == 5 to be pushed to the end of the array and if its not 5 to be pushed to the beginning of the arr have to do this without creating new array
could you please help me solve this one time with iterating .each
and another without .each
Using ruby

Ruby please

end

puts put_num5_last([5,3,5,2,5,1,4])

答:
You can use the sort_by! method of Array.

In ruby there is a naming convention that methods ending with ! are either inplace or destructive, that is they modify the receiver.

sort_by will return a new array (sorted), sort_by! will sort the array inplace.

input = [6, 5, 3, 5, 2, 5, 1, 4]

output = input.sort_by! do |a, b|
  if a == 5
    1
  else
    -1
  end
end

p input     #=> [4, 2, 1, 6, 3, 5, 5, 5]
p output    #=> [4, 2, 1, 6, 3, 5, 5, 5]
p input.object_id   #=> 70191237292740
p output.object_id  #=> 70191237292740
p input.object_id == output.object_id #=> true
```


问:
git commit metrics
I want to determine git commit metrics  using  bash script.

But I never use bash script.

The idea is to have the number of commit wich are not referenced in their status during a specific time

(i.e.: not closed or no #nnnn reference where n is a number, because we use Redmine to show the reference of open commit)

the algorithm is:

```<code>fonction (initial date, final date)
  read initial date
  read final date
  int n=0
  while (initial date<date<final date) do
    if (status!=closed or status!= #nnnn) //where #nnnn is a reference and n a number
      n=+1
    end if
  end while
  echo "the number of none referenced commit is"
  echo n
  return 0
</code>```

If there is a specific git command or other idea, please leave a response, it will help me a lot. thank you

答:
Update After the comments:

It seems you really are helped by the much simpler

```<code>git log --oneline | egrep -ivw 'closed|#[0123456789]+'
</code>```

filtering out just common patterns from commit messages. If you wanted a count of that

```<code>git log --oneline | egrep -ivwc 'closed|#[0123456789]+'
</code>```

You can add from the original answer flags to reduce the output of git log, like so

```<code>git log --oneline --after=2011-01-01 --until=today | egrep -ivwc 'closed|#[0123456789]+'
</code>```

Original answer:

Come again. This question does not parse. "wich are not referenced in their status" What status? A commit doesn't normally have one. Are you using commit notes?

I'm getting the impression you want to find certain information that was not mentioned in git commit messages during a specific period of time? If so, give examples of what kind of commit messages you use, and how the list of 'relation ids' to look for is stored. E.g.:

```<code>from="3 months ago"
until="1 week ago"

lookforids=( '#bug3' '#update4' '#featureY' )
for lookfor in "${lookforids[@]}";
do
    commitcount=$(git log --no-merges --oneline --after="$from" --until="$until" --all -i --grep="$lookfor" | wc -l)

    if [ "$commitcount" -le 1 ]; then echo "Not referenced: $lookfor"; fi
done
</code>```

Of course you should mix and match to your needs, altering the output to your liking. from/until can of course be absolute date literals if you like.

Title: git commit metrics

Body:
I want to determine git commit metrics  using  bash script.

But I never use bash script.

The idea is to have the number of commit wich are not referenced in their status during a specific time

(i.e.: not closed or no #nnnn reference where n is a number, because we use Redmine to show the reference of open commit)

the algorithm is:

fonction (initial date, final date)
  read initial date
  read final date
  int n=0
  while (initial date<date<final date) do
    if (status!=closed or status!= #nnnn) //where #nnnn is a reference and n a number
      n=+1
    end if
  end while
  echo "the number of none referenced commit is"
  echo n
  return 0

If there is a specific git command or other idea, please leave a response, it will help me a lot. thank you

Body:
Update After the comments:

It seems you really are helped by the much simpler

git log --oneline | egrep -ivw 'closed|#[0123456789]+'

filtering out just common patterns from commit messages. If you wanted a count of that

git log --oneline | egrep -ivwc 'closed|#[0123456789]+'

You can add from the original answer flags to reduce the output of git log, like so

git log --oneline --after=2011-01-01 --until=today | egrep -ivwc 'closed|#[0123456789]+'

Original answer:

Come again. This question does not parse. "wich are not referenced in their status" What status? A commit doesn't normally have one. Are you using commit notes?

I'm getting the impression you want to find certain information that was not mentioned in git commit messages during a specific period of time? If so, give examples of what kind of commit messages you use, and how the list of 'relation ids' to look for is stored. E.g.:

from="3 months ago"
until="1 week ago"

lookforids=( '#bug3' '#update4' '#featureY' )
for lookfor in "${lookforids[@]}";
do
    commitcount=$(git log --no-merges --oneline --after="$from" --until="$until" --all -i --grep="$lookfor" | wc -l)

    if [ "$commitcount" -le 1 ]; then echo "Not referenced: $lookfor"; fi
done

Of course you should mix and match to your needs, altering the output to your liking. from/until can of course be absolute date literals if you like.


问:
HttpControllerContext.Configuration is sometimes null during Content negotiation
We are setting up a ASP.NET 4.6.2 Web Api host and noticing that some requests fail because of the following error:

```<code>HttpControllerContext.Configuration must not be null.
</code>```

I've been unable to reproduce the issue and wanted to ask if anybody could steer me in the right direction?

This is the stack trace:

```
[0] System.InvalidOperationException "HttpControllerContext.Configuration must not be null."
   at System.Web.Http.Results.NegotiatedContentResult`1.ApiControllerDependencyProvider.EnsureResolved()
   at System.Web.Http.Results.NegotiatedContentResult`1.ApiControllerDependencyProvider.get_ContentNegotiator()
   at System.Web.Http.Results.BadRequestErrorMessageResult.Execute()
   at System.Web.Http.Results.BadRequestErrorMessageResult.ExecuteAsync(CancellationToken cancellationToken)
   at System.Web.Http.Controllers.ApiControllerActionInvoker.d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()
```

答:
A similar error occurred in my tests when adding headers to a BadRequestErrorMessageResult. The fix only required to initialize the controller's Configuration.
...and subsequently initialize the Request.

So my test's setup ended up looking something like

```<code>public class FooControllerTest
{
    private FooController _sut;

    [Setup]
    public void Setup()
    {
        _sut = new FooController();
        _sut.Configuration = new System.Web.Http.HttpConfiguration();
        _sut.Request = new System.Net.Http.HttpRequestMessage();
    }
}
</code>```

Hope that helps.

Body:
We are setting up a ASP.NET 4.6.2 Web Api host and noticing that some requests fail because of the following error:

HttpControllerContext.Configuration must not be null.

I've been unable to reproduce the issue and wanted to ask if anybody could steer me in the right direction?

This is the stack trace:

[0] System.InvalidOperationException "HttpControllerContext.Configuration must not be null."
   at System.Web.Http.Results.NegotiatedContentResult`1.ApiControllerDependencyProvider.EnsureResolved()
   at System.Web.Http.Results.NegotiatedContentResult`1.ApiControllerDependencyProvider.get_ContentNegotiator()
   at System.Web.Http.Results.BadRequestErrorMessageResult.Execute()
   at System.Web.Http.Results.BadRequestErrorMessageResult.ExecuteAsync(CancellationToken cancellationToken)
   at System.Web.Http.Controllers.ApiControllerActionInvoker.d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()

Body:
A similar error occurred in my tests when adding headers to a BadRequestErrorMessageResult. The fix only required to initialize the controller's Configuration.
...and subsequently initialize the Request.

So my test's setup ended up looking something like

public class FooControllerTest
{
    private FooController _sut;

    [Setup]
    public void Setup()
    {
        _sut = new FooController();
        _sut.Configuration = new System.Web.Http.HttpConfiguration();
        _sut.Request = new System.Net.Http.HttpRequestMessage();
    }
}

Hope that helps.


问:
items in ng-repeat disappear after a second or so in IE 11?
This only happens in IE/Edge and works as expected in Chrome/Firefox. However, in IE, the tables items display for a second and then disappear. Here is my HTML:</p>

```<code><table md-table md-row-select ng-model="upLoaders">
                    <thead md-head md-order="query.tom" md-on-reorder="getIds">
                    <tr md-row>
                        <th md-column><span>Username</span></th>
                        <th md-column>Role</th>
                        <th md-column>Approved</th>
                    </tr>
                </thead>
                <tbody md-body>
                    <tr md-row ng-repeat="user in filtered = (users | filterArray:uploadedUsers)">
                        <td md-cell>{{user.username}}</td>
                        <td md-cell>{{user.role}}</td>
                        <td md-cell>{{user.approved}}</td>
                    </tr>
                </tbody>
</table>
</code>```

答: Try updating Angularjs version to 1.7.2 above </p>

Body:
This only happens in IE/Edge and works as expected in Chrome/Firefox. However, in IE, the tables items display for a second and then disappear. Here is my HTML:

                        Username
                        Role
                        Approved

                        {{user.username}}
                        {{user.role}}
                        {{user.approved}}


问:
Running SonarQube Scanner on a Jenkins remote slave
I have a Docker container running Jenkins (2.150.1) and another Docker container running SonarQube (7.4). Jenkins is using the SonarQube Scanner for Jenkins plugin and the scanning is done on the Jenkins container. The Jenkinsfile for the project looks like this:

```<code>pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        echo 'building...'
      }
    }
    stage('Test') {
      steps {
        echo 'testing...'
        withSonarQubeEnv ('SonarQube') {
          sh '/var/jenkins_home/sonar-scanner/sonar-scanner-3.2.0.1227-linux/bin/sonar-scanner'
        }
        echo 'really finished testing2'
      }
    }
    stage("Quality Gate") {
        steps {
            timeout(time: 1, unit: 'MINUTES') {
              waitForQualityGate abortPipeline: true
            }
        }
    }
    stage('Deployment') {
      steps {
        echo 'deploying...'
      }
    }
  }
}
</code>```

To get the scanning to work as part of a Jenkins pipeline job, I manually installed sonar-scanner on the Jenkins container by downloading the zip file and unzipping it to: /var/jenkins_home/sonar-scanner/sonar-scanner-3.2.0.1227-linux

This is working well, but I want to improve it by:

taking out the harcoded path to sonar-scanner from my Jenkinsfile

specify a non local location of sonar-scanner because I now need to run the scan on another VM/container instead of on the Jenkins container

I tried using Manage Jenkins > Global Tool Configuration > SonarQube Scanner and updated my Jenkinsfile to use SONAR_RUNNER_HOME instead of the hard coded path, but that didn't work and I got an error that sonar-scanner can't be found.

答:
In Manage Jenkins > Global Tool Configuration > SonarQube Scanner check install automatically.

Then go to Manage Jenkins > Configure System and add the following

The Name should be the same as the parameter in the line in your Jenkinsfile: withSonarQubeEnv('SonarQube')

Body:
I have a Docker container running Jenkins (2.150.1) and another Docker container running SonarQube (7.4). Jenkins is using the SonarQube Scanner for Jenkins plugin and the scanning is done on the Jenkins container. The Jenkinsfile for the project looks like this:

pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        echo 'building...'
      }
    }
    stage('Test') {
      steps {
        echo 'testing...'
        withSonarQubeEnv ('SonarQube') {
          sh '/var/jenkins_home/sonar-scanner/sonar-scanner-3.2.0.1227-linux/bin/sonar-scanner'
        }
        echo 'really finished testing2'
      }
    }
    stage("Quality Gate") {
        steps {
            timeout(time: 1, unit: 'MINUTES') {
              waitForQualityGate abortPipeline: true
            }
        }
    }
    stage('Deployment') {
      steps {
        echo 'deploying...'
      }
    }
  }
}

To get the scanning to work as part of a Jenkins pipeline job, I manually installed sonar-scanner on the Jenkins container by downloading the zip file and unzipping it to: /var/jenkins_home/sonar-scanner/sonar-scanner-3.2.0.1227-linux

This is working well, but I want to improve it by:

taking out the harcoded path to sonar-scanner from my Jenkinsfile

specify a non local location of sonar-scanner because I now need to run the scan on another VM/container instead of on the Jenkins container

I tried using Manage Jenkins > Global Tool Configuration > SonarQube Scanner and updated my Jenkinsfile to use SONAR_RUNNER_HOME instead of the hard coded path, but that didn't work and I got an error that sonar-scanner can't be found.


问:
Azure DevOps migration how to fix error VS403300
Trying to migrate from TFS to Azure DevOps, the collection is too big to import using a DACPAC, so I have created a VM in Azure as per the guidance, but when I try to import I get the following error:

[Error] VS403300: It appears that your Azure VM is located in SUK. It’s required that customers targeting UKS for import must have their
  Azure VMs in UKS. Please move or create an Azure VM in UKS and
  re-queue the import.

I am trying to migrate to UK South and the VM is in that region.

答: The error message was a bug in the import tool, Microsoft issued a fix on 27th May 2019. If you try again it should behave as expected now.</p>


问:
haskell check for user input errors
Im writing app in haskell and I would like to know that is the best way to check if users input is ok for example is it int when Im asking for int or if its date when asking for well formed date ?

Thanks for help

答:
I would allow for trailing whitespaces like that:</p>

```<code>import Data.Maybe
import Data.Char

maybeRead :: Read a => String -> Maybe a
maybeRead = fmap fst . listToMaybe . filter (null . dropWhile isSpace . snd) . reads
</code>```

Title: haskell check for user input errors

Body:
I would allow for trailing whitespaces like that:

import Data.Maybe
import Data.Char

maybeRead :: Read a => String -> Maybe a
maybeRead = fmap fst . listToMaybe . filter (null . dropWhile isSpace . snd) . reads


问:
Nodejs expressjs make npm package available throughout the project
I've this folder structure.

```<code>/app.js
/src
 /routes
 /controllers
</code>```

In routes folder, I've bunch of js files. All of these files need to require passport js package like this

```<code>const passport = require('passport');
</code>```

Instead of doing this, can I require the package in one place (Most probably in app.js) and somehow pass that to each and every file in the routes folder instead of requiring it on every file.

答: No matter how often you require() a module, it will be loaded just once. There is nothing wrong with requiring one module in multiple files, actually this is basically the way the module system is designed to work.

Body:
I've this folder structure.

/app.js
/src
 /routes
 /controllers

In routes folder, I've bunch of js files. All of these files need to require passport js package like this

const passport = require('passport');

Instead of doing this, can I require the package in one place (Most probably in app.js) and somehow pass that to each and every file in the routes folder instead of requiring it on every file.


问:
What is the meaning of assert(0 == pthread_mutex_destroy(&lock));
I was debugging a piece of code and encountered a statement:

```<code>assert(0 == pthread_mutex_destroy(&lock));
</code>```

Can anyone explain me what is the interpretation of this statement.

My understanding is that , the assert will terminate the program if pthread_mutex_destroy() method doesn't return a zero.

Can anyone tell me if my understanding is correct

答:
If successful, pthread_mutex_destroy() will return zero, otherwise, an error number will be returned to indicate the error.

This will assert if mutex_destroy() is not a success.

pthread_mutex_destroy() will fail for this reason:

[EINVAL]: The value specified by mutex is invalid.

[EBUSY] : Mutex is locked.

Body:
I was debugging a piece of code and encountered a statement:

assert(0 == pthread_mutex_destroy(&lock));

Can anyone explain me what is the interpretation of this statement.

My understanding is that , the assert will terminate the program if pthread_mutex_destroy() method doesn't return a zero.

Can anyone tell me if my understanding is correct


答:
There may be a passport/Express-specific solution (e.g., installing passport once as middleware), but answering the question about modules in general:

Requiring a module in a module that uses it is standard practice and clearly expresses the dependencies between modules, so it's not usually something you want to avoid doing.

Instead of doing this, can I require the package in one place (Most probably in app.js) and somehow pass that to each and every file in the routes folder instead of requiring it on every file.

You have a couple of options:

If all of those files have other things they're also all importing, you can create a rollup module that requires all of those things and then makes them available as exports. Then your files would do:

```<code>const {passport, anotherThing, yetAnotherThing} = require("./the-rollup-module");
</code>```

instead of

```<code>const passport = require("passport");
const anotherThing = require("another-thing");
const yetAnotherThing = require("yet-another-thing");
</code>```

The rollup would look like this:

```<code>module.exports.passport = require("passport");
module.exports.anotherThing = require("another-thing");
module.exports.yetAnotherThing = require("yet-another-thing");
</code>```

(I don't recommend this.) You can make it a global by putting this in your entry script:

```<code>global.passport = require("passport");
</code>```

That exposes passport as a global variable, so your modules could just use passport without requireing it. (The default global variable is a reference to the global object, like window on browsers, so any property you create on it becomes a global variable.)

I don't recommend it because then the dependencies between your modules are no longer clearly defined.

Title: Nodejs expressjs make npm package available throughout the project

Body:
There may be a passport/Express-specific solution (e.g., installing passport once as middleware), but answering the question about modules in general:

Requiring a module in a module that uses it is standard practice and clearly expresses the dependencies between modules, so it's not usually something you want to avoid doing.

Instead of doing this, can I require the package in one place (Most probably in app.js) and somehow pass that to each and every file in the routes folder instead of requiring it on every file.

You have a couple of options:

If all of those files have other things they're also all importing, you can create a rollup module that requires all of those things and then makes them available as exports. Then your files would do:

const {passport, anotherThing, yetAnotherThing} = require("./the-rollup-module");

instead of

const passport = require("passport");
const anotherThing = require("another-thing");
const yetAnotherThing = require("yet-another-thing");

The rollup would look like this:

module.exports.passport = require("passport");
module.exports.anotherThing = require("another-thing");
module.exports.yetAnotherThing = require("yet-another-thing");

(I don't recommend this.) You can make it a global by putting this in your entry script:

global.passport = require("passport");

That exposes passport as a global variable, so your modules could just use passport without requireing it. (The default global variable is a reference to the global object, like window on browsers, so any property you create on it becomes a global variable.)

I don't recommend it because then the dependencies between your modules are no longer clearly defined.


问:
iPhone: How to programmatically convert String entered by user into Init caps?
I have a textbox where in user enters the string.

I want to programmatically convert this string to init caps.

How can I do that?

答:
Try </p>

```<code>  myString = [myTextField.text capitalizedString];
</code>```

Body:
Try

  myString = [myTextField.text capitalizedString];


问:
Decode http response in Angular - JSON.parse issue
After quite a bit of messing around, I've got to the point where I can recieve the following body in a 404 error response from my backend. I'm struggling to parse the content into angular so I can use it. I'm know this is simple stuff, so sorry to ask such a basic question. The _body looks like this.

```<code> _body: "{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}"
</code>```

These are fine:

```<code>console.log("Err = ", err);
Err =  Response {_body: "
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}", status: 404, ok: false, statusText: "OK", headers: Headers, …}
</code>```

and:

```<code>console.log("Err Body : ", err._body);
Err Body :
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}
</code>```

But this doesn't work:

```<code>let errorObject = eval(errorString);
Uncaught (in promise): SyntaxError: Invalid or unexpected token
</code>```

...

```<code>var errBody = JSON.parse(errorString);
console.log("JS err body", errBody);
Error: Uncaught (in promise): SyntaxError: Unexpected token \ in JSON at position 1
</code>```

But I can't figure out how to get the individual fields out. I'm aware that the above efforts are naive and wrong. I'm sure anyone with JS or angular skills can solve this in a minute.

PS cut me some slack. I'm a hardware designer. I'm here because I don't know something, which is always the best reason to ask a question.

Edit:

Thanks for the answers. JSON.parse does not work for me!?

```<code>SyntaxError: Unexpected token \ in JSON at position 1
</code>```

I looked more closely at what you had success with, and I agree it works fine in the console. But it does not work for me in Angular. What did work was:

```<code>let errBody = JSON.parse("\"" + err._body + "\"");
</code>```

Although it seems ridiculous to do. Especially since, afterwards, the result is not quite right:

```<code>err body {"httpStatus":404,"errorType":"NotFound","message":"Device does not exist!"}
</code>```

If I then try to get at errBody.message, it's undefined!... This is totally absurd. What am I doing wrong? How do you guys do this for a living? It's killing me!

答:
I came back to this recently. And finally managed to figure it out. I needed to remove some unwanted backslashes in the body before trying JSON Parse.  </p>

```<code>const errorStringReplaced = err._body.replace(/\\/g, '');
const errBody = JSON.parse(errorStringReplaced);
this.outcomeMessage = errBody.message;
</code>```

<p>Having done that, I could then grab the innards properly. I'd still prefer to send the object properly in the first place, but this will have to do for now. </p>

Body:
After quite a bit of messing around, I've got to the point where I can recieve the following body in a 404 error response from my backend. I'm struggling to parse the content into angular so I can use it. I'm know this is simple stuff, so sorry to ask such a basic question. The _body looks like this.

 _body: "{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}"

These are fine:

console.log("Err = ", err);
Err =  Response {_body: "
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}", status: 404, ok: false, statusText: "OK", headers: Headers, …}

and:

console.log("Err Body : ", err._body);
Err Body :
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}

But this doesn't work:

let errorObject = eval(errorString);
Uncaught (in promise): SyntaxError: Invalid or unexpected token

...

var errBody = JSON.parse(errorString);
console.log("JS err body", errBody);
Error: Uncaught (in promise): SyntaxError: Unexpected token \ in JSON at position 1

But I can't figure out how to get the individual fields out. I'm aware that the above efforts are naive and wrong. I'm sure anyone with JS or angular skills can solve this in a minute.

PS cut me some slack. I'm a hardware designer. I'm here because I don't know something, which is always the best reason to ask a question.

Edit:

Thanks for the answers. JSON.parse does not work for me!?

SyntaxError: Unexpected token \ in JSON at position 1

I looked more closely at what you had success with, and I agree it works fine in the console. But it does not work for me in Angular. What did work was:

let errBody = JSON.parse("\"" + err._body + "\"");

Although it seems ridiculous to do. Especially since, afterwards, the result is not quite right:

err body {"httpStatus":404,"errorType":"NotFound","message":"Device does not exist!"}

If I then try to get at errBody.message, it's undefined!... This is totally absurd. What am I doing wrong? How do you guys do this for a living? It's killing me!

Body:
I came back to this recently. And finally managed to figure it out. I needed to remove some unwanted backslashes in the body before trying JSON Parse.

const errorStringReplaced = err._body.replace(/\\/g, '');
const errBody = JSON.parse(errorStringReplaced);
this.outcomeMessage = errBody.message;

Having done that, I could then grab the innards properly. I'd still prefer to send the object properly in the first place, but this will have to do for now.


问:
The code is correct yet it needs try-catch.. why is that?
I am very new to programming and I saw this code that runs perfect with try/catch.

I thought then try/catch is not necessary, as all I know that it just for checking errors and to change the message of the compile when in error.

But when I removed it the code renders many errors and refuse to compile.  So what is try/catch is really doing here? because

The code:

import java.io.FileWriter;

public class html {

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

    try{
       FileWriter fw=new FileWriter("E:\\rrr.html");
       fw.write("Welcome to javaTpoint.");
       fw.close();
      }catch(Exception e){System.out.println(e);}
      System.out.println("Success...");
 }
</code>```

答:
The FileWriter class always throws an exception i.e, 'IOException',
  Hence, whenever you use it IOException needs to be handled, so the
  try-catch block is mandatory while using FileWriter.

What is an IOException?

An IOException is any unexpected problem the JVM encounters while attempting to run a program. Possible problems that it may encounter are:

attempting to read from a file that does not exist

attempting to write to a file that has an invalid name (a slash or a question mark in the title should do it)

attempting to read the next token in a file when there are no more tokens.

When an IOException is thrown, it means that whatever is throwing the exception (perhaps a try{}-catch block that reads data from a file) can throw an IOException, for example if the file is not found, corrupted, etc, or when the file is otherwise unable to be read, or any other of a list of issues that can occur with the IO package and it's extensions.

Body:
I am very new to programming and I saw this code that runs perfect with try/catch.

I thought then try/catch is not necessary, as all I know that it just for checking errors and to change the message of the compile when in error.

But when I removed it the code renders many errors and refuse to compile.  So what is try/catch is really doing here? because

The code:

import java.io.FileWriter;

public class html {

public static void main(String[] args) {

    try{
       FileWriter fw=new FileWriter("E:\\rrr.html");
       fw.write("Welcome to javaTpoint.");
       fw.close();
      }catch(Exception e){System.out.println(e);}
      System.out.println("Success...");
 }