问:
Yarn - remove package best practices
If you want to remove a package using Yarn should you:

run yarn remove [package]

or

delete it from package.json and run yarn install

Do both work the same? Will #2 update yarn.lock?

答:
When you remove with Yarn by running the first approach (#1).

yarn remove [package]

Both your entries from lockfile and package.json are removed. Look out for this message in the terminal.

```<code>$ yarn remove x2js
yarn remove v0.27.5
[1/2] Removing module x2js...
[2/2] Regenerating lockfile and installing missing dependencies...
success Uninstalled packages.
Done in 2.34s.
</code>```

The new file won't have the package.

If you follow the second (#2) approach and delete it from package.json and run:

yarn install

There will we no effect on your lockfile.

So it is better to remove packages using the first approach (#1).

If you have deleted some package(s) directly from package.json and don't know what was there then your lockfile is not up to date.

I would suggest you delete the yarn.lock file . and then run yarn install. This way, you will get an updated yarn.lock file.

Title: Yarn - remove package best practices

Body:
When you remove with Yarn by running the first approach (#1).

yarn remove [package]

Both your entries from lockfile and package.json are removed. Look out for this message in the terminal.

$ yarn remove x2js
yarn remove v0.27.5
[1/2] Removing module x2js...
[2/2] Regenerating lockfile and installing missing dependencies...
success Uninstalled packages.
Done in 2.34s.

The new file won't have the package.

If you follow the second (#2) approach and delete it from package.json and run:

yarn install

There will we no effect on your lockfile.

So it is better to remove packages using the first approach (#1).

If you have deleted some package(s) directly from package.json and don't know what was there then your lockfile is not up to date.

I would suggest you delete the yarn.lock file . and then run yarn install. This way, you will get an updated yarn.lock file.


来源: stackexchange

问:
Python RegEx remove new lines (that shouldn't be there)
I got some text extracted and wish to clean it up by RegEx.

I have learned basic RegEx but not sure how to build this one:

```<code>str = '''
this is
a line that has been cut.
This is a line that should start on a new line
'''
</code>```

should be converted to this:

```<code>str = '''
this is a line that has been cut.
This is a line that should start on a new line
'''
</code>```

This r'\w\n\w' seems to catch it, but not sure how to replace the new line with space and not touch the end and beginning of words

答:
You can use this lookbehind regex for re.sub:

```<code>>>> str = '''
... this is
... a line that has been cut.
... This is a line that should start on a new line
... '''
>>> print re.sub(r'(?<!\.)\n', '', str)
this is a line that has been cut.
This is a line that should start on a new line
>>>
</code>```

RegEx Demo

(?<!\.)\n matches all line breaks that are not preceded by a dot.

If you don't want a match based on presence of dot then use:

```<code>re.sub(r'(?<=\w\s)\n', '', str)
</code>```

RegEx Demo 2

ContentLicense: CC BY-SA 3.0

Body:
I got some text extracted and wish to clean it up by RegEx.

I have learned basic RegEx but not sure how to build this one:

str = '''
this is
a line that has been cut.
This is a line that should start on a new line
'''

should be converted to this:

str = '''
this is a line that has been cut.
This is a line that should start on a new line
'''

This r'\w\n\w' seems to catch it, but not sure how to replace the new line with space and not touch the end and beginning of words

Body:
You can use this lookbehind regex for re.sub:

>>> str = '''
... this is
... a line that has been cut.
... This is a line that should start on a new line
... '''
>>> print re.sub(r'(?<!\.)\n', '', str)
this is a line that has been cut.
This is a line that should start on a new line
>>>

RegEx Demo

(?<!\.)\n matches all line breaks that are not preceded by a dot.

If you don't want a match based on presence of dot then use:

re.sub(r'(?<=\w\s)\n', '', str)

RegEx Demo 2


问:
Get date from coming day and specified date in Carbon?
In Carbon, I can do

```<code>Carbon::parse("This Sunday"); // This gives me coming date for Sunday
</code>```

But I want to get date for day like get coming date of Sunday after 2018-01-01. Is it possible to achieve something like this?

答:
Yes, you can write something like this.

```<code>Carbon::parse('first sunday of January 2018')
</code>```

The documentation is here http://carbon.nesbot.com/docs/

Body:
In Carbon, I can do

Carbon::parse("This Sunday"); // This gives me coming date for Sunday

But I want to get date for day like get coming date of Sunday after 2018-01-01. Is it possible to achieve something like this?

Body:
Yes, you can write something like this.

Carbon::parse('first sunday of January 2018')

The documentation is here http://carbon.nesbot.com/docs/


问:
Dynamically view inflation error
I am creating view via XML.

But after adding view it is throwing error -

The specified child already has a parent. You must call removeView() on the child's parent first.

I am using below code -

```<code>LinearLayout main = new LinearLayout(mContext);
main.setId(R.id.main);
main.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
main.setLayoutParams(layoutParams);

LinearLayout sub1 = new LinearLayout(mContext);
sub1.setId(R.id.sub1);
sub1.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_662 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub1.setLayoutParams(layout_662);

LinearLayout sub2 = new LinearLayout(mContext);
sub2.setId(R.id.sub2);
sub2.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_943 = new  LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub2.setLayoutParams(layout_943);

for(int i=0;i<=4);i++) {

    sub1.addView(imageView[i]);
    main.addView(sub1);

    sub2.addView(imageView1[i]);
    main.addView(sub2);
}
</code>```

Any kind of help will be appreciated.

答:
Change your for statement this way:

```<code>    main.addView(sub1);
    main.addView(sub2);

    for(int i=0;i<=4);i++) {

        sub1.addView(imageView[i]);

        sub2.addView(imageView1[i]);
    }
</code>```

You have to add sub1 and sub2 only once.

Title: Dynamically view inflation error

Body:
I am creating view via XML.

But after adding view it is throwing error -

The specified child already has a parent. You must call removeView() on the child's parent first.

I am using below code -

LinearLayout main = new LinearLayout(mContext);
main.setId(R.id.main);
main.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
main.setLayoutParams(layoutParams);

LinearLayout sub1 = new LinearLayout(mContext);
sub1.setId(R.id.sub1);
sub1.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_662 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub1.setLayoutParams(layout_662);

LinearLayout sub2 = new LinearLayout(mContext);
sub2.setId(R.id.sub2);
sub2.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layout_943 = new  LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
sub2.setLayoutParams(layout_943);

for(int i=0;i<=4);i++) {

    sub1.addView(imageView[i]);
    main.addView(sub1);

    sub2.addView(imageView1[i]);
    main.addView(sub2);
}

Any kind of help will be appreciated.

Body:
Change your for statement this way:

    main.addView(sub1);
    main.addView(sub2);

    for(int i=0;i<=4);i++) {

        sub1.addView(imageView[i]);

        sub2.addView(imageView1[i]);
    }

You have to add sub1 and sub2 only once.


问:
Open Sublime Text from Terminal in macOS
In Terminal when I use .subl

It returns -bash: .subl: command not found

Anyone know how to open Sublime Text 3 from the command line in macOS?

答:
I am using mac airbook open your terminal and type

```<code> sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/bin/subl
</code>```

Then type simple subl and file name

```<code> subl index.py
</code>```

Body:
I am using mac airbook open your terminal and type

 sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/bin/subl

Then type simple subl and file name

 subl index.py


问:
Stopping index of Github pages
I have a github page from my repository   username.github.io

However I do not want Google to crawl my website and absolutely do not want it to show up on search results.

Will just using robots.txt in github pages work?     I know there are tutorials for stop indexing Github repository but what about  the actual Github page?

答:
Short answer:

You can use a robots.txt to stop indexing of your users GitHub Pages by adding it in your User Page. This robots.txt will be the active robots.txt for all your projects pages as the project pages are reachable as subdirectories (username.github.io/project) in your subdomain (username.github.io).

Longer answer:

You get your own subdomain for GitHub pages (username.github.io). According to this question on MOZ and googles reference each subdomain has/needs its own robots.txt.

This means that the valid/active robots.txt for project projectname by user username lives at username.github.io/robots.txt. You can put a robots.txtfile there by creating a GitHub Pages page for your user.

This is done by creating a new project/repository named username.github.io where username is your username. You can now create a robots.txt file in the master branch of this project/repository and it should be visible at username.github.io/robots.txt. More information about project, user and organization pages can be found here.

I have tested this with Google, confirming ownership of myusername.github.io by placing a html file in my project/repository https://github.com/myusername/myusername.github.io/tree/master, creating a robot.txt file there and then verifying that my robots.txt works by using Googles Search Console webmaster tools (googlebot-fetch). Google does indeed list it as blocked and Google Search Console webmaster tools (robots-testing-tool) confirms it.

To block robots for one projects GitHub Page:

```<code>User-agent: *
Disallow: /projectname/
</code>```

To block robots for all GitHub Pages for your user (User Page and all Project Pages):

```<code>User-agent: *
Disallow: /
</code>```

Other options

Look into the HTML meta tag

Look into custom domain (redirects) for GitHub Pages

Title: Stopping index of Github pages

Body:
Short answer:

You can use a robots.txt to stop indexing of your users GitHub Pages by adding it in your User Page. This robots.txt will be the active robots.txt for all your projects pages as the project pages are reachable as subdirectories (username.github.io/project) in your subdomain (username.github.io).

Longer answer:

You get your own subdomain for GitHub pages (username.github.io). According to this question on MOZ and googles reference each subdomain has/needs its own robots.txt.

This means that the valid/active robots.txt for project projectname by user username lives at username.github.io/robots.txt. You can put a robots.txtfile there by creating a GitHub Pages page for your user.

This is done by creating a new project/repository named username.github.io where username is your username. You can now create a robots.txt file in the master branch of this project/repository and it should be visible at username.github.io/robots.txt. More information about project, user and organization pages can be found here.

I have tested this with Google, confirming ownership of myusername.github.io by placing a html file in my project/repository https://github.com/myusername/myusername.github.io/tree/master, creating a robot.txt file there and then verifying that my robots.txt works by using Googles Search Console webmaster tools (googlebot-fetch). Google does indeed list it as blocked and Google Search Console webmaster tools (robots-testing-tool) confirms it.

To block robots for one projects GitHub Page:

User-agent: *
Disallow: /projectname/

To block robots for all GitHub Pages for your user (User Page and all Project Pages):

User-agent: *
Disallow: /

Other options

Look into the HTML meta tag

Look into custom domain (redirects) for GitHub Pages


答:
You've got

```<code>main.addView(sub1);
</code>```

inside a for-loop. So on the second loop, it's already added to the parent view.

Title: Dynamically view inflation error

Body:
You've got

main.addView(sub1);

inside a for-loop. So on the second loop, it's already added to the parent view.


问:
Pyodbc SQL Server connection doesn't work, when run as a windows service
I use the following code, to create connection to SQL Server database. When I just run my flask application, it works fine.

```<code>cnxn = pyodbc.connect(driver='{ODBC Driver 13 for SQL Server}',
                      server='my_user',
                      database='my_db',
                      username='my_username',
                      password='pass',
                      trusted_connection='yes'
                      )
</code>```

But now I've created Windows service, using nssm tool. The service just runs .bat file, that starts my service.

```<code>pyodbc.InterfaceError: ('28000', '[28000] [Microsoft][ODBC Driver 13 for SQL Server]
[SQL Server]Login failed for user \'WORKGROUP\\my_user$\'. (18456) (SQLDriverConnect);
[28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Cannot open database
"my_db" requested by the login.
The login failed. (4060); [28000] [Microsoft]
[ODBC Driver 13 for SQL Server]Invalid connection string attribute (0);
</code>```

How is it possible?

答: Run service with administrator account.</p>

Body:
I use the following code, to create connection to SQL Server database. When I just run my flask application, it works fine.

cnxn = pyodbc.connect(driver='{ODBC Driver 13 for SQL Server}',
                      server='my_user',
                      database='my_db',
                      username='my_username',
                      password='pass',
                      trusted_connection='yes'
                      )

But now I've created Windows service, using nssm tool. The service just runs .bat file, that starts my service.

pyodbc.InterfaceError: ('28000', '[28000] [Microsoft][ODBC Driver 13 for SQL Server]
[SQL Server]Login failed for user \'WORKGROUP\\my_user$\'. (18456) (SQLDriverConnect);
[28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Cannot open database
"my_db" requested by the login.
The login failed. (4060); [28000] [Microsoft]
[ODBC Driver 13 for SQL Server]Invalid connection string attribute (0);

How is it possible?

Body: Run service with administrator account.


问:
Boost::shared_ptr instantiated using this
Consider the following case:

```<code>typedef boost::shared_ptr<B> BPtr;

class A
{
public:
    A() { b_ptr = BPtr(new B); }
    void a_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class B
{
public:
    B() { b_ptr = BPtr(this); }
    void b_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class C
{
public:
    static void c_func(BPtr b_ptr) { /*...*/ }
}
</code>```

Is it ok to instantiate a shared_ptr with this?

Is it ok to have two shared_ptr objects pointing to the same object? (e.g. A::b_ptr and B::b_ptr)

If one of these two gets out of scope - would B's instance be deleted?

I'm guessing I'm doing something fundamentally wrong.

I also thought about using dependency injection of b_ptr to B's constructor, but that too seems very wrong.

UPDATE:

To clarify - Both A and B need to use C::c_func. In turn, after some processing, C needs to call a callback function in B which I haven't specified above.
Actually two cases are interesting:

If there's a requirement that C won't be stateful - then it needs to receive BPtr both from A and from B as in the code above.

If C is stateful and both A and B instantiate separate C instances, giving a BPtr in C's ctor.

答:
Is it ok to instantiate a shared_ptr with this?

No, for at least several reasons:

If you create a A or B object on the stack or statically, you end up with a shared_ptr "owning" the object created on the stack; when the object is destroyed, the shared_ptr destructor will be called, calling delete on the object, and only Bad Things Will Happen.  Further, even if the object is created dynamically, you don't know for sure what the owner of your class may do with it:  he may assign it to some other type of smart pointer like an auto_ptr, which has totally different semantics.

You end up with a circular reference.  For example, b_ptr owns the B object of which it is a member.  You have to manually .reset() it in order for the B object to be destroyed.

You can get a shared_ptr from this by using enable_shared_from_this, but there are a lot of caveats:  namely, you cannot call enable_shared_from_this in a constructor.  Even so, you don't want to store a shared_ptr to an object inside of the object itself; it doesn't make any sense.

I'm guessing I'm doing something fundamentally wrong.

Yes, but since you haven't said what, exactly, you are trying to do, it's hard to say what you should be doing instead.  You've only told us how you are trying to do this, not what you are trying to do in the first place.

ContentLicense: CC BY-SA 2.5

Body:
Consider the following case:

typedef boost::shared_ptr BPtr;

class A
{
public:
    A() { b_ptr = BPtr(new B); }
    void a_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class B
{
public:
    B() { b_ptr = BPtr(this); }
    void b_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class C
{
public:
    static void c_func(BPtr b_ptr) { /*...*/ }
}

Is it ok to instantiate a shared_ptr with this?

Is it ok to have two shared_ptr objects pointing to the same object? (e.g. A::b_ptr and B::b_ptr)

If one of these two gets out of scope - would B's instance be deleted?

I'm guessing I'm doing something fundamentally wrong.

I also thought about using dependency injection of b_ptr to B's constructor, but that too seems very wrong.

UPDATE:

To clarify - Both A and B need to use C::c_func. In turn, after some processing, C needs to call a callback function in B which I haven't specified above.
Actually two cases are interesting:

If there's a requirement that C won't be stateful - then it needs to receive BPtr both from A and from B as in the code above.

If C is stateful and both A and B instantiate separate C instances, giving a BPtr in C's ctor.


问:
AES password storing issue
I would like to AES encrypt some users profiles info.
When a user registers, I use the password he provides, I compleate it to 16 bits with  zeros to have the required key lenght (16 bit) for AES if the password does not have 16 in lenght, then I encrypt all his data profile with that key. I know that at this point my AES keys will be secure because no one knows them except the users them selves.

When a user logs in, I take his password do the same 16 bit process and decrypt his data. The problem I have is with password recovery, if the user forget his password, the data is lost forever. Is there a better way or a work around this issue?

Thanks.

答:
Your AES key "derivation" is not secure, you should use password hashing (or, to be more precise, use a password based key derivation function - PBKDF) instead of padding with zero's. A password is not the same thing as a key, which should consists of 128 or more randomized bits.

Instead of recovering the key (or password) you could encrypt your data with a random data key. Then you can in turn encrypt this data key with the key of the user. You can additionally encrypt the data key using a public (RSA) key, of which you keep the private key safe on detached storage or somewhere in the back office. The encryption of one key with another key is called key wrapping.

Some data you may want to keep private to the user, in that case simply do not encrypt with the public key in the back office. You could possibly encrypt this kind of data at the location of the user instead of on your server.

Title: AES password storing issue


问:
Vector out of bounds when assign a vector to a vector of vectors
I've typedefined a vector of integers with name List.

newList is of type vector of List.

oldList is of type List.

```<code>newList[m][n] = oldList[i];
</code>```

And I've tried

```<code>newList[m].push_back(oldList[i]);
</code>```

I dont have much experience with C++ so any help would be nice.

答: The answer is to resize newList to include the indexes your accessing.</p>

Body:
I've typedefined a vector of integers with name List.

newList is of type vector of List.

oldList is of type List.

newList[m][n] = oldList[i];

And I've tried

newList[m].push_back(oldList[i]);

I dont have much experience with C++ so any help would be nice.


问:
Real time notification in cakephp3
Hello i'm new with cakephp, and I just want to add a simple notification system for my website, I mean some sort of messaging between admin and users, I found after some research that I should use node.js or web-socket. Is there any plugin that I should add to my project? thanks for your help</p>

答:
I know, I am giving answer very late but you can try with this for your requirement.
https://github.com/bakkerij/notifier</p>

Title: Real time notification in cakephp3


问:
iPhone development - preventing leaks
When I run my app with Leaks and view the Extended Details for any of the leaks, it takes me to a particular line in my code, but I don't know what to do after that!

For instance, Leaks shows a malloc at this line

```<code>NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
</code>```

But I do not know what the problem is in the statement! Can someone please tell me how to interpret such problems and avoid leaks.

Thanks.

Edit:
Regarding the previous question I had, NSZombieEnabled makes sure no objects are deallocated and this increases the memory usage. So when testing with Leaks, make sure this setting is removed from your app. Thought this might help someone.

答: A leak in the method you mention above was supposed to be fixed for the iPhone OS 2.2 release.  Which version of the iPhone OS are you using?</p>

OwnerDisplayName: lostInTransit

Title: iPhone development - preventing leaks

Body:
When I run my app with Leaks and view the Extended Details for any of the leaks, it takes me to a particular line in my code, but I don't know what to do after that!

For instance, Leaks shows a malloc at this line

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

But I do not know what the problem is in the statement! Can someone please tell me how to interpret such problems and avoid leaks.

Thanks.

Edit:
Regarding the previous question I had, NSZombieEnabled makes sure no objects are deallocated and this increases the memory usage. So when testing with Leaks, make sure this setting is removed from your app. Thought this might help someone.

LastEditorDisplayName: lostInTransit

OwnerDisplayName: Eric Albert


问:
How to publish a react based component through npm without including react?
I have a simple component that requires react and mobx to use. When I build my library through webpack, it is including react and mobx and mobx-react in the bundle. However I would like to add them as a peer dependency and let the user of my module install the libraries.

Is this possible? My webpack config looks like this and it builds nicely into dist/build.js I just need to work out how to exclude the libraries.

```<code>module.exports = {
    entry: [ './index.js' ],
    output: {
        path: path.resolve('./dist'),
        filename: 'build.js',
        library: 'myLibrary',
        libraryTarget: 'commonjs'
    },
    module: {
        rules: loaders
    },
    plugins: [
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        })
    ]
}
</code>```

答:
There is a distinction you need to make between building for development and testing of your lib, and what will be actually used by the consumer of your lib. They most likely wont need to be using a pre-built lib

Your webpack build is likely only for your own development purposes, in which case it is perfectly fine and necessary to have react and any other dependencies bundled in the build.

When a consumer comes to use your library via npm, your package should usually point them to the source code index.js, rather a built file, and their own build will trace the dependencies via the require/imports and bundle them up itself, in which case it would use their peer dependencies rather than your libs dependencies

It would only be necessary to pre-build distributions via your own webpack config if you are wanting to make builds for consumption directly via a script tag on the web, or taget UMD commonJS specifically. In that case you can have your webpack config declare react and friends as externals https://webpack.js.org/configuration/externals

If it is only to be consumed by importing as a node module, it should be enough to add peer dependencies to your package for the modules you would like to be supplied by the consumer, and make sure the main file is referenced, so their own build knows where to import it from

```<code>"main": "./index.js", // source code entry (this is what consumer requires, at which point their build will trace deps to react etc)
"peerDependencies": {
  "react": "*",
  "mobx-react": "*" // or required min versions
}
</code>```

Body:
I have a simple component that requires react and mobx to use. When I build my library through webpack, it is including react and mobx and mobx-react in the bundle. However I would like to add them as a peer dependency and let the user of my module install the libraries.

Is this possible? My webpack config looks like this and it builds nicely into dist/build.js I just need to work out how to exclude the libraries.

module.exports = {
    entry: [ './index.js' ],
    output: {
        path: path.resolve('./dist'),
        filename: 'build.js',
        library: 'myLibrary',
        libraryTarget: 'commonjs'
    },
    module: {
        rules: loaders
    },
    plugins: [
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        })
    ]
}

Body:
There is a distinction you need to make between building for development and testing of your lib, and what will be actually used by the consumer of your lib. They most likely wont need to be using a pre-built lib

Your webpack build is likely only for your own development purposes, in which case it is perfectly fine and necessary to have react and any other dependencies bundled in the build.

When a consumer comes to use your library via npm, your package should usually point them to the source code index.js, rather a built file, and their own build will trace the dependencies via the require/imports and bundle them up itself, in which case it would use their peer dependencies rather than your libs dependencies

It would only be necessary to pre-build distributions via your own webpack config if you are wanting to make builds for consumption directly via a script tag on the web, or taget UMD commonJS specifically. In that case you can have your webpack config declare react and friends as externals https://webpack.js.org/configuration/externals

If it is only to be consumed by importing as a node module, it should be enough to add peer dependencies to your package for the modules you would like to be supplied by the consumer, and make sure the main file is referenced, so their own build knows where to import it from

"main": "./index.js", // source code entry (this is what consumer requires, at which point their build will trace deps to react etc)
"peerDependencies": {
  "react": "*",
  "mobx-react": "*" // or required min versions
}


问:
Writing to a memory mapped text file printing NULL till the end of mapped memory
In this code, Im writing some text to a memory mapped text file. Data is written to the file successfully, but when i open it with notepad, after the written data, "NULL" is repeatedly written upto the mapped memory limit which is greater than the text i have written.

What could be the possible reason?

```<code>pLogMsg = (char*)calloc(1024,sizeof(char));
printf("[INFO] entering logger writeback thread\n");

log_file = CreateFile (TEXT("one.txt"),             // Open one.txt.
                    GENERIC_READ | GENERIC_WRITE,   // Open for reading and writing
                    FILE_SHARE_WRITE,               // file share
                    NULL,                           // No security
                    OPEN_ALWAYS,                    // Open or create
                    FILE_ATTRIBUTE_NORMAL,          // Normal file
                    NULL);                          // No template file
if (log_file == INVALID_HANDLE_VALUE)
{
    printf("%d [ERR] cant open file GLE %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
hMapping = CreateFileMapping( log_file, 0, PAGE_READWRITE, 0,4096 ,0 );
if (hMapping == INVALID_HANDLE_VALUE)
{
    printf("%d [ERR] cant create file mapping %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
pFileData = (CHAR*)MapViewOfFile( hMapping, FILE_MAP_ALL_ACCESS, 0,0, 0 );
if (pFileData == NULL)
{
    printf("%d [ERR] cant mapview of file %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
pLogMsg = LogPrint();//returns a null terminated string
memcpy(pFileData,pLogMsg,strlen(pLogMsg));
pFileData += strlen(pLogMsg);
free(pLogMsg);
</code>```

答:
You cannot set the end-of-file marker through a file mapping. The end-of-file marker does not physically exist in a file. It is a flag raised by the OS when reading past the end of a file.

To set the size of a file you will have to call SetFilePointer followed by SetEndOfFile on the file object used to create the file mapping.

Body:
In this code, Im writing some text to a memory mapped text file. Data is written to the file successfully, but when i open it with notepad, after the written data, "NULL" is repeatedly written upto the mapped memory limit which is greater than the text i have written.

What could be the possible reason?

pLogMsg = (char*)calloc(1024,sizeof(char));
printf("[INFO] entering logger writeback thread\n");

log_file = CreateFile (TEXT("one.txt"),             // Open one.txt.
                    GENERIC_READ | GENERIC_WRITE,   // Open for reading and writing
                    FILE_SHARE_WRITE,               // file share
                    NULL,                           // No security
                    OPEN_ALWAYS,                    // Open or create
                    FILE_ATTRIBUTE_NORMAL,          // Normal file
                    NULL);                          // No template file
if (log_file == INVALID_HANDLE_VALUE)
{
    printf("%d [ERR] cant open file GLE %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
hMapping = CreateFileMapping( log_file, 0, PAGE_READWRITE, 0,4096 ,0 );
if (hMapping == INVALID_HANDLE_VALUE)
{
    printf("%d [ERR] cant create file mapping %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
pFileData = (CHAR*)MapViewOfFile( hMapping, FILE_MAP_ALL_ACCESS, 0,0, 0 );
if (pFileData == NULL)
{
    printf("%d [ERR] cant mapview of file %d\n",GetCurrentThreadId(),GetLastError());
    return -1;
}
pLogMsg = LogPrint();//returns a null terminated string
memcpy(pFileData,pLogMsg,strlen(pLogMsg));
pFileData += strlen(pLogMsg);
free(pLogMsg);


问:
Sorting an array (incl subarray) in Angular 4 for a table
My team and I are creating an Audience Response Web Application with Angular 4. I am creating an array with the name allAnswers which looks like this . When I end a quiz I am routed to the results component which shows me this table. As you can see the answers are messed up. This is the html code of my table component.

Let me explain the structure of the array allAnswers. An answer is built out of an:

0 element:

this is where the questionID stands for which the answer is for

1 element:

answer: this is a simple boolean bc right now we just have true/false questions implemented

studentID: a string which identifies a single student in a quiz

As you can see in the picture of the table we want to structure it as follows:

The first table head element is named "Frage" which means question. the column under it contains the questionIDs, which will be later replaced by the question text (which is not the problem right now). The next table headers are the studentsID, in the row in which they have joined a Quiz (a seperate array which looks like this). Now we want to sort the allAnswers array so that that it correctly shows the answer of each student fitting to the right answer.

How can that be solved?

答:
Thank you for your replies, but I already figured it out. I thought about implementing a pipe, but then a colleague mentioned ng-template (former ng-container) and now it works. I restructured my allAnswers array, so it contained studentID, questionID and answer on one level. And this is the code in html which made it all magically work.

If you have any suggestions of making it look more clean, please write :). I'm still a beginner, started with Angular a few months before.


答:
You can achieve this simply with

```<code>Carbon::parse("2018-01-01")->modify("next Sunday");
</code>```

or using next() which might be faster

```<code>Carbon::parse("2018-01-01")->next(Carbon::SUNDAY);
</code>```

Title: Get date from coming day and specified date in Carbon?

Body:
You can achieve this simply with

Carbon::parse("2018-01-01")->modify("next Sunday");

or using next() which might be faster

Carbon::parse("2018-01-01")->next(Carbon::SUNDAY);


问:
Geode regions is always empty, did not bring server side data
We are running Gemfire 8.1, a Pivotal version of Geode chosen by our client in order to provide support, the current application is using Spring Data Gemfire, so the configuration is mixed between client-config.xml and Spring Beans and it works properly.

I intend to do a tool application to help some data manipulation, initially I wished to do it on Go, but the Geode plugin is not ready yet and I would rather to avoid disordering the environment to provide the REST API.

I started it in Java as simple as possible, only with the Geode Core dependency as we can see in the official sample, and I am transposing xml configuration on code, but no matter which combination I do I am never able to get the remote keys, all regions always return empty maps, even registring ALL_KEYS interest.

I have tried to connect directly to the server instead of to the locator, with and without subscription, running the code on my machine or even directly on the server machine, always the same result.

Debugging the currenct application code (the working one not this tool), I am inclined to say the problem is with the region, as I have tried to assign a not yet registred region with CacheFactory.getAnyInstance().createClientRegionFactory(ClientRegionShortcut.PROXY).create("region-name") and I obtained region.getAttributes().getDataPolicy() as EMPTY rather than NORMAL the other regions are, and my tool have the same behaviour, with all new regions with DataPolicy being EMPY.

If I connect via gfsh I am able to list members and regions, I wonder what would gfsh and Spring Data doing different to be able to handle server-side data.

How can I do a application that to the same the gfsh does as simple as possible? I just want to connect and read some regions.

答:
When using ClientRegionShortcut.PROXY, the region has no local state and forwards all operations to the server, as described in the javadocs, that's why the keys are not stored locally on client side, the client is just a data accessor to the region. You need to use ClientRegionShortcut. CACHING_PROXY instead, which is similar to PROXY but also has local state.
More information about this topic can also be found in Region Shortcuts and Custom Named Region Attributes.

Hope this helps.

Cheers.


问:
[Python3x]: How to extract two values separately (beautifulsoup)?
This is the value (coordinates) that I would like to have separately (latitude, longitude).

```<code><input id="dokad" value="51.819544, 19.30441" type="hidden">
</code>```

When I do like that:

```<code>lat_lon = soup.find('input', attrs={'id':'dokad'}).get('value')
</code>```

Result:

```<code>lat_lon
Out[1012]: '51.186147, 19.199997'
type(lat_lon)
Out[1013]: str
</code>```

How can I extract these two values separately?

答:
Use str.split() to split string and then float() to convert your strings to float:

lat_lon = lat_lon.split(', ')

And then convert your list elements to float by doing this:
lat_lon = [float(number) for number in lat_lon]

now lat_lon variable should contain list of floating point values: [51.186147, 19.199997]

Body:
This is the value (coordinates) that I would like to have separately (latitude, longitude).

<input id="dokad" value="51.819544, 19.30441" type="hidden">

When I do like that:

lat_lon = soup.find('input', attrs={'id':'dokad'}).get('value')

Result:

lat_lon
Out[1012]: '51.186147, 19.199997'
type(lat_lon)
Out[1013]: str

How can I extract these two values separately?


问:
macOS - vagrant up failed, /dev/vboxnetctl: no such file or directory
Can be useful, I found this error. The common solution is reinstall virtualbox but there are a better way.

Solution

```<code>sudo /Library/StartupItems/VirtualBox/VirtualBox restart
</code>```

or

```<code>sudo /Library/StartupItems/VirtualBox/VirtualBox start
</code>```

VirtualBox 4.3+

On recents versions, the file (/Library/StartupItems/VirtualBox/VirtualBox) don't exists, so you need to use the command below:

```<code>sudo launchctl load /Library/LaunchDaemons/org.virtualbox.startup.plist
</code>```

Error

Print: http://d.pr/i/1Bvi

There was on error while executing VBoxManage, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below
  Command: ["hostonlyif", "create"]

Stderr: 0%... Progress state: NS_ERROR_FAILURE VBoxManage: error:
  Failed to create the host-only adapter VBoxManage: error:
  VBoxNetAdpCtl: Error while adding new interface: failed to open
  /dev/vboxnetctl: No such file or directory

VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005),
  component HostNetworkInterface, interface IHostNetworkInterface
  VBoxManage: error: Context: "int handleCreate(HandlerArg*, int, int*)"
  at line 68 of file VBoxManageHostonly.cpp

Vagrant Git issue about the error: https://github.com/mitchellh/vagrant/issues/1671#issuecomment-22304107

答:
I'm running macOS High Sierra 10.13.1 and VirtualBox 5.2.2.

This worked for me:

Grant permission to VirtualBox under System Preferences > Security & Privacy > General (this request is new to macOS High Sierra)

Open Terminal and run: sudo "/Library/Application Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh" restart

ContentLicense: CC BY-SA 4.0

Body:
Can be useful, I found this error. The common solution is reinstall virtualbox but there are a better way.

Solution

sudo /Library/StartupItems/VirtualBox/VirtualBox restart

or

sudo /Library/StartupItems/VirtualBox/VirtualBox start

VirtualBox 4.3+

On recents versions, the file (/Library/StartupItems/VirtualBox/VirtualBox) don't exists, so you need to use the command below:

sudo launchctl load /Library/LaunchDaemons/org.virtualbox.startup.plist

Error

Print: http://d.pr/i/1Bvi

There was on error while executing VBoxManage, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below
  Command: ["hostonlyif", "create"]

Stderr: 0%... Progress state: NS_ERROR_FAILURE VBoxManage: error:
  Failed to create the host-only adapter VBoxManage: error:
  VBoxNetAdpCtl: Error while adding new interface: failed to open
  /dev/vboxnetctl: No such file or directory

VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005),
  component HostNetworkInterface, interface IHostNetworkInterface
  VBoxManage: error: Context: "int handleCreate(HandlerArg*, int, int*)"
  at line 68 of file VBoxManageHostonly.cpp

Vagrant Git issue about the error: https://github.com/mitchellh/vagrant/issues/1671#issuecomment-22304107


问:
How do I bypass protect_from_forgery in Rails 3 for a Facebook canvas app?
I have a Rails 3 Facebook canvas app. When it loads up it gives me an invalid authenticity token error and displays the signed_request parameter that Facebook sends to my app. Is there a way to bypass the 'protect_from_forgery' for the signed_request from facebook?

Thanks!

Tim

答: You can also just remove protect_from_forgery from the application controller, if you only use the app as a canvas app.</p>


问:
Filter out records with a wildcard
I am using ElasticSearch + Kibana to log errors. In the Kibana dashboard, I can filter out records by a certain field by clicking on the magnifier glass with the minus sign. It then generates the following query to exclude:

```<code>{
  "query": {
    "match": {
      "message": {
        "query": "Invalid HTTP_HOST header: '12.34.567.89'. You may need to add '12.34.567.89' to ALLOWED_HOSTS.",
        "type": "phrase"
      }
    }
  }
}
</code>```

Now I want to exclude these records for all possible IP addresses, so I need a wildcard (or regexp). I found the documentation about wildcards and regexps here. However, they do not resemble the syntax used above.

If I change the query above to the one from the documentation, it doesn't filter it at all. Example:

```<code>{
  "query": {
    "wildcard": {
      "message": "Invalid HTTP_HOST header: *"
    }
  }
}
</code>```

If I try to combine them, I get a parsing error: Discover: [parsing_exception] [match] unknown token [START_OBJECT] after [query], with { line=1 col=444 }. Example:

```<code>{
  "query": {
    "match": {
      "message": {
        "query": {
          "wildcard": {
            "message": "Invalid HTTP_HOST header: *"
          }
        },
        "type": "phrase"
      }
    }
  }
}
</code>```

I have tried a few more combinations, but I can't get it to work. Any ideas?

答:
Another possibility is to use the regexp query, like this, but depending on how much data you have, it's going to be CPU intensive:

```<code>POST _search
{
  "query": {
    "regexp": {
      "message.keyword": {"value":"Invalid HTTP_HOST header: '<1-999>\\.<1-999>\\.<1-999>\\.<1-999>'\\. You may need to add '<1-999>\\.<1-999>\\.<1-999>\\.<1-999>' to ALLOWED_HOSTS\\.",
      "flags": "ALL"}
    }
  }
}
</code>```

You might be better off analyzing your data before indexing it and split it into better searchable parts.

Title: Filter out records with a wildcard

Body:
I am using ElasticSearch + Kibana to log errors. In the Kibana dashboard, I can filter out records by a certain field by clicking on the magnifier glass with the minus sign. It then generates the following query to exclude:

{
  "query": {
    "match": {
      "message": {
        "query": "Invalid HTTP_HOST header: '12.34.567.89'. You may need to add '12.34.567.89' to ALLOWED_HOSTS.",
        "type": "phrase"
      }
    }
  }
}

Now I want to exclude these records for all possible IP addresses, so I need a wildcard (or regexp). I found the documentation about wildcards and regexps here. However, they do not resemble the syntax used above.

If I change the query above to the one from the documentation, it doesn't filter it at all. Example:

{
  "query": {
    "wildcard": {
      "message": "Invalid HTTP_HOST header: *"
    }
  }
}

If I try to combine them, I get a parsing error: Discover: [parsing_exception] [match] unknown token [START_OBJECT] after [query], with { line=1 col=444 }. Example:

{
  "query": {
    "match": {
      "message": {
        "query": {
          "wildcard": {
            "message": "Invalid HTTP_HOST header: *"
          }
        },
        "type": "phrase"
      }
    }
  }
}

I have tried a few more combinations, but I can't get it to work. Any ideas?

Body:
Another possibility is to use the regexp query, like this, but depending on how much data you have, it's going to be CPU intensive:

POST _search
{
  "query": {
    "regexp": {
      "message.keyword": {"value":"Invalid HTTP_HOST header: '<1-999>\\.<1-999>\\.<1-999>\\.<1-999>'\\. You may need to add '<1-999>\\.<1-999>\\.<1-999>\\.<1-999>' to ALLOWED_HOSTS\\.",
      "flags": "ALL"}
    }
  }
}

You might be better off analyzing your data before indexing it and split it into better searchable parts.


问:
Terminal not working on PhpStorm 2017.2.4
I have this error when opening a terminal in PhpStorm:

Can't open local terminal

java.io.IOException: Exec_tty error:Unknown

I found simmilar problems on previous versions of PhpStorm fixed with the new release, but I can't find any info related to version 2017.2.4.

Has anyone got an idea why it is coming up with this error?

答: A path to the shell (File | Settings | Tools | Terminal) should be checked to make sure a system's default one is used.</p>


问:
how to show default selected option in select box
I have searched similar kind of links ,but no luck.

I have an array of objects which i need to show as a dropdown and i have to select one default option .My object contains value,selected properties.If value and selected properties are matched then it has to be the default selected option.My dropdown Array look like this...

```<code>[
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "hp",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "samsung",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "dell",
      "type": "String"
    }
  ]
</code>```

and HTML code like this..

```<code><select formControlName="controlFordropdwn" >
            <option value="" disabled  hidden>Select</option>
            <option *ngFor="let type of dropdown"   [value]="type.value" [selected]='type.value == type.selected'  >
              {{type.value}}
            </option>
          </select>
</code>```

Any response which is related to this will help me alot.
Thanks to you inAdvance

答:
i have this scenario which i have worked, hope it will help</p>

```<code> HTML:
 <select class="form-control">
 <option [attr.selected]="index == 2 ? true : null" *ngFor="let segment of segmentation;
 let index=index;" [ngValue]="index">{{segment.name}}</option>
</select>

TS:
segmentation = [
{ "name": "name 1", "columns": [ { "index": 0}]},
{ "name": "name 2", "columns": [{"index": 1}]},
{ "name": "name 3","columns": [ { "index": 2}]}
]
</code>```

Body:
I have searched similar kind of links ,but no luck.

I have an array of objects which i need to show as a dropdown and i have to select one default option .My object contains value,selected properties.If value and selected properties are matched then it has to be the default selected option.My dropdown Array look like this...

[
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "hp",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "samsung",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "dell",
      "type": "String"
    }
  ]

and HTML code like this..

<select formControlName="controlFordropdwn" >
            <option value="" disabled  hidden>Select</option>
            <option *ngFor="let type of dropdown"   [value]="type.value" [selected]='type.value == type.selected'  >
              {{type.value}}
            </option>
          </select>

Any response which is related to this will help me alot.
Thanks to you inAdvance

Body:
i have this scenario which i have worked, hope it will help

 HTML:
 <select class="form-control">
 <option [attr.selected]="index == 2 ? true : null" *ngFor="let segment of segmentation;
 let index=index;" [ngValue]="index">{{segment.name}}</option>
</select>

TS:
segmentation = [
{ "name": "name 1", "columns": [ { "index": 0}]},
{ "name": "name 2", "columns": [{"index": 1}]},
{ "name": "name 3","columns": [ { "index": 2}]}
]


问:
Label with different font sizes
Basically I want to achieve something like this:

but I have no idea how to do it, I tried with 2 labels to combine them but the result isn't that great..

答: Use devexpress LabelControl.AllowHtmlString property to true and use the supported <size> tag within the LabelControl's Text property as detailed in the HTML Text Formatting documentation.

Title: Label with different font sizes


问:
Reading lines from a file and splitting them into arrays
I am working on a Linux project in C. I am creating a number a processes and each one writes his information on a file in the following format

PID | NAME | TYPE | GENOME

and the process.txt file looks something like this:

567 | A | B | 20

568 | N | A | 2

569 | Z | B | 12

This information I provide while executing it's code. What i want to do is to let the parent process read the file at the end of the child execution and be able to split this values into arrays in this way:

```<code>    pids[] = {567, 568, 569}
    names[] = {A, N, Z}
    type[] = {B, A, B}
    genome[] = {20, 2, 12}
</code>```

I have been looking for a way to do such thing but haven't found anything specific yet. A runnable code would be appreciated.

答:
When scan or writting a file, you need to open it first.
Then, you could specify what you want to do using fprintf to write or fscanf to scan the data.
To scan you file, here's the code :

```<code>int main(){
        char name[4], type[4];
        int pids[4], genome[4];
        int i = 0;
        FILE * file = fopen("process.txt", "r"); // "r" = read
        while(fscanf(file, "%d|%c|%c|%d\n", &pids[i], name[i], type[i], &genome[i]) != EOF){
            i++;
        }
}
</code>```

Body:
I am working on a Linux project in C. I am creating a number a processes and each one writes his information on a file in the following format

PID | NAME | TYPE | GENOME

and the process.txt file looks something like this:

567 | A | B | 20

568 | N | A | 2

569 | Z | B | 12

This information I provide while executing it's code. What i want to do is to let the parent process read the file at the end of the child execution and be able to split this values into arrays in this way:

    pids[] = {567, 568, 569}
    names[] = {A, N, Z}
    type[] = {B, A, B}
    genome[] = {20, 2, 12}

I have been looking for a way to do such thing but haven't found anything specific yet. A runnable code would be appreciated.

Body:
When scan or writting a file, you need to open it first.
Then, you could specify what you want to do using fprintf to write or fscanf to scan the data.
To scan you file, here's the code :

int main(){
        char name[4], type[4];
        int pids[4], genome[4];
        int i = 0;
        FILE * file = fopen("process.txt", "r"); // "r" = read
        while(fscanf(file, "%d|%c|%c|%d\n", &pids[i], name[i], type[i], &genome[i]) != EOF){
            i++;
        }
}


问:
Spring MongoTemplate upsert entire list
I have a list of objects which I want to insert into a collection. The mongoTemplate.insert(list); works fine but now I want to modify it to upsert(); as my list can contain duplicate objects which are already inserted into a collection. So what I want is insert entire list and on the go check if the item is already present in the collection then skip it else insert it.

答:
The only way to do a bulk-upsert operation is the method MongoCollection.bulkWrite (or at least: the only way I know... ;-))

To use it, you have to convert your documents to the appropriate WriteModel: for upserts on a per-document basis, this is UpdateOneModel.

```<code>List<Document> toUpdate = ...;
MongoCollection coll = ...;

// Convert Document to UpdateOneModel<Document>
List<UpdateOneModel<Document>> bulkOperationList = toUpdate.stream()
   .map(doc -> new UpdateOneModel<Document>(
       Filters.eq("_id", doc.get("_id")),  // identify by same _id
       doc,
       new UpdateOptions().upsert(true)))
   .collect(Collectors.toList());

// Write to DB
coll.bulkWrite(bulkOperationList);
</code>```

(Disclaimer: I only typed this code, I never ran it)

Title: Spring MongoTemplate upsert entire list

Body:
The only way to do a bulk-upsert operation is the method MongoCollection.bulkWrite (or at least: the only way I know... ;-))

To use it, you have to convert your documents to the appropriate WriteModel: for upserts on a per-document basis, this is UpdateOneModel.

List<Document> toUpdate = ...;
MongoCollection coll = ...;

// Convert Document to UpdateOneModel<Document>
List<UpdateOneModel<Document>> bulkOperationList = toUpdate.stream()
   .map(doc -> new UpdateOneModel<Document>(
       Filters.eq("_id", doc.get("_id")),  // identify by same _id
       doc,
       new UpdateOptions().upsert(true)))
   .collect(Collectors.toList());

// Write to DB
coll.bulkWrite(bulkOperationList);

(Disclaimer: I only typed this code, I never ran it)


问:
Unexpected output when multiple threads update same variable
```<code>#include<stdio.h>
#include<pthread.h>
#define NUM_THREAD (5)

int sum=0;
void* runner(void * param);

int main(int argc,char **argv){

    pthread_t tid[NUM_THREAD];
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    for(i=0;i<NUM_THREAD;i++){
    pthread_create(&tid[i],&attr,runner,NULL);
    }
    for(i=0;i<NUM_THREAD;i++){
    pthread_join(tid[i],NULL);
            }
    printf("After threading %d",sum);
    return 0;
}

void * runner(void *param){
    for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}
</code>```

output: 225

In the following code, the output is 225. But the correct should be 45

I know threads share global variables!. so this function should correctly output right. But adding that sum=0 inside only gives correct output.  Whats happening here I don't understand!

```<code>void * runner(void *param){
sum=0;   // MY DOUBT
for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}
</code>```

output: 45

答:
What you are dealing with is a race condition. With each systems, you'll get different output. The behavior of this code is not deterministic.
Because, as you create each thread, in a loop, runner function, which iterates for 10 times, is invoked in an order which can not be known.

So, expecting 45 or 245 or anything for that matter is wrong.

Race condition is an undesired condition when multiple threads can modify a common/shared data at the same time because they can have access to it.
The scheduler which can behave differently from system to system might switch between those 5 threads at any point in time. To have a deterministic behavior, this needs to be addressed by some synchronization technique like Mutex or a Semaphore.

Mutex are my favorite for that. Not writing the whole code for you, because its not necessary with the question and I am lazy.

The rough steps to do the same would be:

Where you create threads,

Initialize Mutex before you create threads

Create threads (0 to n)

Destroy Mutex once you are done

pthread_join

And in thread handlers, in your case runner function,

Lock Mutex

Do something

Unlock Mutex (Don't forget this!)

So, your main should contain pthread_mutex_init, if it does return NULL, you can proceed.

In runner function, pthread_mutex_lock(&lock); should be the first trivial thing it does, followed by your code and then finally pthread_mutex_unlock(&lock); before it returns.

The mutex you created can be destroyed by pthread_mutex_destroy.

Its fun!

Body:
#include<stdio.h>
#include<pthread.h>
#define NUM_THREAD (5)

int sum=0;
void* runner(void * param);

int main(int argc,char **argv){

    pthread_t tid[NUM_THREAD];
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    for(i=0;i<NUM_THREAD;i++){
    pthread_create(&tid[i],&attr,runner,NULL);
    }
    for(i=0;i<NUM_THREAD;i++){
    pthread_join(tid[i],NULL);
            }
    printf("After threading %d",sum);
    return 0;
}

void * runner(void *param){
    for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}

output: 225

In the following code, the output is 225. But the correct should be 45

I know threads share global variables!. so this function should correctly output right. But adding that sum=0 inside only gives correct output.  Whats happening here I don't understand!

void * runner(void *param){
sum=0;   // MY DOUBT
for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}

output: 45


问:
Align FrameLayout inside ConstraintLayout to bottom
I want a layout above recycler view at the bottom of the screen,(like a frame) so that even when that layout is visible I can still scroll recycler view behind it. So I want to align the frame layout at the bottom of the screen and make it visible and invisible as per requirement. Here is my code.

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.protossoft.root.aesencryption.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:id="@+id/listView"
        android:layout_height="match_parent">

    </ListView>

  <!--  <RelativeLayout
        android:layout_width="match_parent"

        android:layout_height="wrap_content">-->
    <FrameLayout
        android:layout_width="match_parent"

        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="443dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/deviceNumberImage"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.2"
                android:src="@android:drawable/btn_default" />

            <TextView
                android:id="@+id/deviceNumber"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.8"
                android:text="990000862471854" />

        </LinearLayout>
    </FrameLayout>
   <!-- </RelativeLayout>-->
</code>```

I don't have too much of idea about constraint layout, but when I am moving the view at the bottom from the editor, it is using property like

```<code>tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="443dp"
</code>```

I want to achieve the same with some property like align_parentBottom. But none of the properties is available for use. What do I need to do so that the frame layout is visible at the bottom and on the top of recycler view at the same time?
Thanks :)

答:
I want to achieve the same with some property like align_parentBottom.

You should use app:layout_constraintBottom_toBottomOf="parent" attribute.

Here's the setup that you need:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">
        ...
    </FrameLayout>

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I want a layout above recycler view at the bottom of the screen,(like a frame) so that even when that layout is visible I can still scroll recycler view behind it. So I want to align the frame layout at the bottom of the screen and make it visible and invisible as per requirement. Here is my code.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.protossoft.root.aesencryption.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:id="@+id/listView"
        android:layout_height="match_parent">

    </ListView>

    <FrameLayout
        android:layout_width="match_parent"

        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="443dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/deviceNumberImage"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.2"
                android:src="@android:drawable/btn_default" />

            <TextView
                android:id="@+id/deviceNumber"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.8"
                android:text="990000862471854" />

        </LinearLayout>
    </FrameLayout>

I don't have too much of idea about constraint layout, but when I am moving the view at the bottom from the editor, it is using property like

tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="443dp"

I want to achieve the same with some property like align_parentBottom. But none of the properties is available for use. What do I need to do so that the frame layout is visible at the bottom and on the top of recycler view at the same time?
Thanks :)

Body:
I want to achieve the same with some property like align_parentBottom.

You should use app:layout_constraintBottom_toBottomOf="parent" attribute.

Here's the setup that you need:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">
        ...
    </FrameLayout>

</android.support.constraint.ConstraintLayout>


问:
Inject host's SSH keys into Docker Machine with Docker Compose
I am using Docker on Mac OS X with Docker Machine (with the default boot2docker machine), and I use docker-compose to setup my development environment.

Let's say that one of the containers is called "stack". Now what I want to do is call:

```<code>docker-composer run stack ssh user@stackoverflow.com
</code>```

My public key (which has been added to stackoverflow.com and which will be used to authenticate me) is located on the host machine. I want this key to be available to the Docker Machine container so that I will be able to authenticate myself against stackoverflow using that key from within the container. Preferably without physically copying my key to Docker Machine.

Is there any way to do this? Also, if my key is password protected, is there any way to unlock it once so after every injection I will not have to manually enter the password?

答:
WARNING: This feature seems to have limited support in Docker Compose and is more designed for Docker Swarm.

(I haven't checked to make sure, but) My current impression is that:

In Docker Compose secrets are just bind mount volumes, so there's no additional security compared to volumes

Ability to change secrets permissions with Linux host may be limited

See answer comments for more details.

Docker has a feature called secrets, which can be helpful here. To use it one could add the following code to docker-compose.yml:

```<code>---
version: '3.1' # Note the minimum file version for this feature to work
services:
  stack:
    ...
    secrets:
      - host_ssh_key

secrets:
  host_ssh_key:
    file: ~/.ssh/id_rsa
</code>```

Then the new secret file can be accessed in Dockerfile like this:

```<code>RUN mkdir ~/.ssh && ln -s /run/secrets/host_ssh_key ~/.ssh/id_rsa
</code>```

Secret files won't be copied into container:

When you grant a newly-created or running service access to a secret, the decrypted secret is mounted into the container in an in-memory filesystem

For more details please refer to:

https://docs.docker.com/engine/swarm/secrets/

https://docs.docker.com/compose/compose-file/compose-file-v3/#secrets

Body:
I am using Docker on Mac OS X with Docker Machine (with the default boot2docker machine), and I use docker-compose to setup my development environment.

Let's say that one of the containers is called "stack". Now what I want to do is call:

docker-composer run stack ssh user@stackoverflow.com

My public key (which has been added to stackoverflow.com and which will be used to authenticate me) is located on the host machine. I want this key to be available to the Docker Machine container so that I will be able to authenticate myself against stackoverflow using that key from within the container. Preferably without physically copying my key to Docker Machine.

Is there any way to do this? Also, if my key is password protected, is there any way to unlock it once so after every injection I will not have to manually enter the password?

Body:
WARNING: This feature seems to have limited support in Docker Compose and is more designed for Docker Swarm.

(I haven't checked to make sure, but) My current impression is that:

In Docker Compose secrets are just bind mount volumes, so there's no additional security compared to volumes

Ability to change secrets permissions with Linux host may be limited

See answer comments for more details.

Docker has a feature called secrets, which can be helpful here. To use it one could add the following code to docker-compose.yml:

---
version: '3.1' # Note the minimum file version for this feature to work
services:
  stack:
    ...
    secrets:
      - host_ssh_key

secrets:
  host_ssh_key:
    file: ~/.ssh/id_rsa

Then the new secret file can be accessed in Dockerfile like this:

RUN mkdir ~/.ssh && ln -s /run/secrets/host_ssh_key ~/.ssh/id_rsa

Secret files won't be copied into container:

When you grant a newly-created or running service access to a secret, the decrypted secret is mounted into the container in an in-memory filesystem

For more details please refer to:

https://docs.docker.com/engine/swarm/secrets/

https://docs.docker.com/compose/compose-file/compose-file-v3/#secrets


问:
UITableViewCell containing a UICollectionView using RxSwift
I started using RxSwift in my iOS project and I have a UITableView with a custom UITableViewCell subclass. Within that subclass, I have a UICollectionView.

Populating the tableview using RxSwift works pretty flawlessly, I'm using another extension of RxSwift for that (RxDataSources)

Here's how I'm doing it:

```<code>    self.dataSource = RxTableViewSectionedReloadDataSource<Section>(configureCell: {(section, tableView, indexPath, data)  in
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCellWithCollectionView

        switch indexPath.section {
        case 0:
            cell.collectionViewCellNibName = "ContactDataItemCollectionViewCell"
            cell.collectionViewCellReuseIdentifier = "contactDataItemCellIdentifier"
        case 1, 2:
            cell.collectionViewCellNibName = "DebtCollectionViewCell"
            cell.collectionViewCellReuseIdentifier = "debtCellIdentifier"
        default:
            break
        }
        cell.registerNibs(indexPath.section, nativePaging: false, layoutDirection: indexPath.section != 0 ? .horizontal : .vertical)

        let cellCollectionView = cell.collectionView!

        data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
            cell.setup(debt: data)
        }

        return cell

    })
</code>```

This actually works. But the problem arises when a tableview cell gets scrolled off the screen and reappears. This triggers the code block from above and lets the app crash when

```<code>    data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
        cell.setup(debt: data)
    }
</code>```

is invoked twice on the same tableview cell (The funny thing is, even Xcode crashes without any trace).

What can I do to avoid this?

EDIT:

I have found a solution, but I must admit that I'm not really happy with it... Here's the idea (tested and works)

I define another Dictionary in my class:

```<code>var boundIndizes = [Int: Bool]()
</code>```

and then I make an if around the binding like this:

```<code>if let bound = self.boundIndizes[indexPath.section], bound == true {
    //Do nothing, content is already bound
} else {
    data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
        cell.setup(debt: data)
        }.disposed(by: self.disposeBag)
    self.boundIndizes[indexPath.section] = true
}
</code>```

But I cannot believe there is no "cleaner" solution

答:
The issue is you are binding your data.debts to the collectionView within the cell every time the cell is dequeued.

I would recommend you move the logic that is related to your data.debts to the cell itself and declare a var disposeBag: DisposeBag which you reinstantiate on prepareForReuse. See this answer for reference.

Body:
I started using RxSwift in my iOS project and I have a UITableView with a custom UITableViewCell subclass. Within that subclass, I have a UICollectionView.

Populating the tableview using RxSwift works pretty flawlessly, I'm using another extension of RxSwift for that (RxDataSources)

Here's how I'm doing it:

    self.dataSource = RxTableViewSectionedReloadDataSource
(configureCell: {(section, tableView, indexPath, data)  in
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCellWithCollectionView

        switch indexPath.section {
        case 0:
            cell.collectionViewCellNibName = "ContactDataItemCollectionViewCell"
            cell.collectionViewCellReuseIdentifier = "contactDataItemCellIdentifier"
        case 1, 2:
            cell.collectionViewCellNibName = "DebtCollectionViewCell"
            cell.collectionViewCellReuseIdentifier = "debtCellIdentifier"
        default:
            break
        }
        cell.registerNibs(indexPath.section, nativePaging: false, layoutDirection: indexPath.section != 0 ? .horizontal : .vertical)

        let cellCollectionView = cell.collectionView!

        data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
            cell.setup(debt: data)
        }

        return cell

    })

This actually works. But the problem arises when a tableview cell gets scrolled off the screen and reappears. This triggers the code block from above and lets the app crash when

    data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
        cell.setup(debt: data)
    }

is invoked twice on the same tableview cell (The funny thing is, even Xcode crashes without any trace).

What can I do to avoid this?

EDIT:

I have found a solution, but I must admit that I'm not really happy with it... Here's the idea (tested and works)

I define another Dictionary in my class:

var boundIndizes = [Int: Bool]()

and then I make an if around the binding like this:

if let bound = self.boundIndizes[indexPath.section], bound == true {
    //Do nothing, content is already bound
} else {
    data.debts.asObservable().bind(to: cellCollectionView.rx.items(cellIdentifier: "debtCellIdentifier", cellType: DebtCollectionViewCell.self)) { row, data, cell in
        cell.setup(debt: data)
        }.disposed(by: self.disposeBag)
    self.boundIndizes[indexPath.section] = true
}

But I cannot believe there is no "cleaner" solution


问:
Why doesn't Python want to access the second item of my 2-items list?

I'm trying to split an email address under the format jim.smith-royal@smth.edu or jim.smith@smth.edu into a name and a surname, so jim and smith, or jim and smith royal (with a space in between). (I am a beginner so I may not be doing it in the simplest way, but still).

```<code>for row in votants:
    mail = row[1]
    full_name = mail.split('@')[0]
    prenom = full_name.split('.')[0]

    #The code works until here, full_name.split gives me ['jim','smith'] and prenom gives me 'jim'

    pre_name = full_name.split('.')
    nom = pre_name[1]

    #The problem is until here, but I kept the rest of my code for anyone who might have the same objective as me

    try:
        nom = nom.split('-')[0] + " " + nom.split('-')[1]
    except Exception:
        pass
    row.append(prenom)
    row.append(nom)
</code>```

Instead of giving me nom as 'smith', I get "IndexError: list index out of range".

答:
I tried:

```<code>mail = "jim.smith@smth.edu"
full_name = mail.split('@')[0]
prenom = full_name.split('.')[0]

#The code works until here, full_name.split gives me ['jim','smith'] and prenom gives me 'jim'

pre_name = full_name.split('.')
nom = pre_name[1]

#The problem is until here, but I kept the rest of my code for anyone who might have the same objective as me

print(full_name);
print(pre_name);
print(nom);
print(prenom);
</code>```

and it prints:

jim.smith

['jim', 'smith']

smith

jim

Without any exceptions.

Problem:

Like comments said: If no "." is used in name (before @), you are probably facing the indexOutOfRange Exception.

Possible Solutions:

Surround it in if-else block:

```<code>if len(pre_name) >= 2
</code>```

or use try-except:

```<code>try:
    nom = pre_name[1]
except IndexError:
    nom = pre_name[0];
</code>```

or use:

```<code>if "." in full_name:
    pre_name = full_name.split('.')
    nom = pre_name[1]
</code>```

General Debugging:

use print() earlier.

```<code>// works until here
pre_name = full_name.split('.')
print(pre_name) // if no '.' was used, you will see the array contains only 1 element
nom = pre_name[1] // problem here?
</code>```

Body:
I'm trying to split an email address under the format jim.smith-royal@smth.edu or jim.smith@smth.edu into a name and a surname, so jim and smith, or jim and smith royal (with a space in between). (I am a beginner so I may not be doing it in the simplest way, but still).

for row in votants:
    mail = row[1]
    full_name = mail.split('@')[0]
    prenom = full_name.split('.')[0]

    #The code works until here, full_name.split gives me ['jim','smith'] and prenom gives me 'jim'

    pre_name = full_name.split('.')
    nom = pre_name[1]

    #The problem is until here, but I kept the rest of my code for anyone who might have the same objective as me

    try:
        nom = nom.split('-')[0] + " " + nom.split('-')[1]
    except Exception:
        pass
    row.append(prenom)
    row.append(nom)

Instead of giving me nom as 'smith', I get "IndexError: list index out of range".

Body:
I tried:

mail = "jim.smith@smth.edu"
full_name = mail.split('@')[0]
prenom = full_name.split('.')[0]

#The code works until here, full_name.split gives me ['jim','smith'] and prenom gives me 'jim'

pre_name = full_name.split('.')
nom = pre_name[1]

#The problem is until here, but I kept the rest of my code for anyone who might have the same objective as me

print(full_name);
print(pre_name);
print(nom);
print(prenom);

and it prints:

jim.smith

['jim', 'smith']

smith

jim

Without any exceptions.

Problem:

Like comments said: If no "." is used in name (before @), you are probably facing the indexOutOfRange Exception.

Possible Solutions:

Surround it in if-else block:

if len(pre_name) >= 2

or use try-except:

try:
    nom = pre_name[1]
except IndexError:
    nom = pre_name[0];

or use:

if "." in full_name:
    pre_name = full_name.split('.')
    nom = pre_name[1]

General Debugging:

use print() earlier.

// works until here
pre_name = full_name.split('.')
print(pre_name) // if no '.' was used, you will see the array contains only 1 element
nom = pre_name[1] // problem here?


问:
is there an url for photo gallery so that we could jump to in ios
I want user jump to their photo gallery after pressing a button.

Is there a URL for that? I am using objective-c if it matters.

答:
Apple do not allow you to move to Gallery through App. Hence you can open gallery for picking video & photos etc. You just can do like this if you want to pick from gallery :

```<code>if([UIImagePickerController isSourceTypeAvailable:
                    UIImagePickerControllerSourceTypePhotoLibrary]) {

 UIImagePickerController *picker= [[UIImagePickerController alloc] init];
 picker.delegate = self;
 picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
 picker.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeMovie, (NSString *)kUTTypeImage, nil];

 [self presentModalViewController:picker animated:YES];
</code>```

}

Sets the file types you want to get on the property of the PickerViewControllerObject "mediaTypes" and you're ready.

Body:
Apple do not allow you to move to Gallery through App. Hence you can open gallery for picking video & photos etc. You just can do like this if you want to pick from gallery :

if([UIImagePickerController isSourceTypeAvailable:
                    UIImagePickerControllerSourceTypePhotoLibrary]) {

 UIImagePickerController *picker= [[UIImagePickerController alloc] init];
 picker.delegate = self;
 picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
 picker.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeMovie, (NSString *)kUTTypeImage, nil];

 [self presentModalViewController:picker animated:YES];

}

Sets the file types you want to get on the property of the PickerViewControllerObject "mediaTypes" and you're ready.


问:
Custom notification not working in Android 8
I am using this tutorial: Android custom notification for developing and android application with custom notifications.
Although this app runs perfectly on android 7 and below, but I am unable to run it on android 8 on my onpePlus 3T. Please help.</p>

答:
Your tutorial is outdated. If you targeting Android 8.0 (API level 26) you must create at least one notification channel.

Read official notification guide for more info: https://developer.android.com/guide/topics/ui/notifiers/notifications.html#ManageChannels


问:
Best practise for different column types on Rails
I have a model in rails that refers to a game_item that belongs to a user. This weapon has an is_equipped column that resembles whether the item is equipped or not. The game_item can be a weapon, a helmet and more (specified by item_type in game_item model).

Now, i'm looking for a good way to get the equipped item for every type. I can do things like get_equipped_item(type) and specify the type, or get_equipped_helmet, get_equipped_weapon etc.
I'm looking for the better way to do that, the rails way :) Any ideas ?

答:
```<code>rails generate scaffold GameItem item_type:string is_enabled:boolean

rake db:migrate

rails console

a = GameItem.new(:item_type => "helmet", :is_enabled => true)
b = GameItem.new(:item_type => "gun", :is_enabled => false)
c = GameItem.new(:item_type => "knife", :is_enabled => true)

s = [a, b, c]

s.find_all{|item| item.is_enabled == true}

s.size // size is 2 since 2 of the items in the array have is_enabled set to true.
</code>```


问:
Get information from an ObjectJson without Array
I have the class below and I can fetch information from a JSONArray in this format:

{"cliente":[{"id":"1334","nome":"Bruno"}]}

```<code>TextView nome_usuario;

private static final String TAG_CLIENTE = "cliente";
private static final String TAG_NOME = "nome";

JSONArray cliente = null;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View grafico = inflater.inflate(R.layout.fragment_fragment_perfil, container, false);
nome_usuario = (TextView ) grafico.findViewById(R.id.txtNome);
new JSONParse().execute();
return grafico;
}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Atualizando");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();

}

@Override
protected JSONObject doInBackground(String... args) {
    JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl("url do json");
        return json;

}
@Override
protected void onPostExecute(JSONObject json) {
    pDialog.dismiss();
    try {
        cliente = json.getJSONArray(TAG_CLIENTE);
        JSONObject c = cliente.getJSONObject(0);
        String nome = c.getString(TAG_NOME);
        nome_usuario.setText(nome);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}
}

}
</code>```

But now I would like to work with a json in the following format:

{"name": "Bruno"}

I found a question similar to my How to parse JSON Object Android Studio, but I could not apply it to my example.

答:
Getting information from an JSONObject:

```<code>JSONObject aJsonObject = new JSONObject(aJsonResponse);
JSONArray aJsonArray = aJsonObject.getJSONArray("cliente");
for (int i = 0; i < aJsonArray.length(); i++) {
    aJsonObject = aJsonArray.getJSONObject(i);
String aId = aJsonObject .getString("id");
String aNome = aJsonObject .getString("nome");
}
</code>```

Body:
I have the class below and I can fetch information from a JSONArray in this format:

{"cliente":[{"id":"1334","nome":"Bruno"}]}

TextView nome_usuario;

private static final String TAG_CLIENTE = "cliente";
private static final String TAG_NOME = "nome";

JSONArray cliente = null;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View grafico = inflater.inflate(R.layout.fragment_fragment_perfil, container, false);
nome_usuario = (TextView ) grafico.findViewById(R.id.txtNome);
new JSONParse().execute();
return grafico;
}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Atualizando");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();

}

@Override
protected JSONObject doInBackground(String... args) {
    JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl("url do json");
        return json;

}
@Override
protected void onPostExecute(JSONObject json) {
    pDialog.dismiss();
    try {
        cliente = json.getJSONArray(TAG_CLIENTE);
        JSONObject c = cliente.getJSONObject(0);
        String nome = c.getString(TAG_NOME);
        nome_usuario.setText(nome);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}
}

}

But now I would like to work with a json in the following format:

{"name": "Bruno"}

I found a question similar to my How to parse JSON Object Android Studio, but I could not apply it to my example.

Body:
Getting information from an JSONObject:

JSONObject aJsonObject = new JSONObject(aJsonResponse);
JSONArray aJsonArray = aJsonObject.getJSONArray("cliente");
for (int i = 0; i < aJsonArray.length(); i++) {
    aJsonObject = aJsonArray.getJSONObject(i);
String aId = aJsonObject .getString("id");
String aNome = aJsonObject .getString("nome");
}


问:
MySQL zip installation defaults file my.ini could not open during the installation
I have a program that installs MySQL from zip file.
Program can extract files from zip file to the Program Files folder and create an option file in Program Files folder for mysql called "my.ini".

After the extraction process, program is gonna initialize data folders and files via run the mysqld.exe.

The program run the mysqld.exe via Process.Start() with some arguments. The arguments are
--defaults-file=C:\\Program Files\\MySQL\\my.ini --initialize-insecure --console.

When I try to run mysqld.exe with that arguments, it throws an error like;

```<code>mysqld: [ERROR] Could not open required defaults file: C:\Program
mysqld: [ERROR] Fatal error in defaults handling. Program aborted!
</code>```

My codes are like below;

```<code>        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.WorkingDirectory = destPath + "\\bin";
        p.StartInfo.FileName = destPath + "\\bin\\mysqld.exe";
        p.StartInfo.Arguments = "--defaults-file=" + destPath + "\\my.ini --initialize-insecure --console";
        p.OutputDataReceived += P_OutputDataReceived;
        p.Start();

        // destPath:"C:\\Program Files\\MySQL"
</code>```

答:
I solved it. my.ini file must places to paths like below;

More information can be found below
https://dev.mysql.com/doc/refman/5.7/en/option-files.html

Body:
I have a program that installs MySQL from zip file.
Program can extract files from zip file to the Program Files folder and create an option file in Program Files folder for mysql called "my.ini".

After the extraction process, program is gonna initialize data folders and files via run the mysqld.exe.

The program run the mysqld.exe via Process.Start() with some arguments. The arguments are
--defaults-file=C:\\Program Files\\MySQL\\my.ini --initialize-insecure --console.

When I try to run mysqld.exe with that arguments, it throws an error like;

mysqld: [ERROR] Could not open required defaults file: C:\Program
mysqld: [ERROR] Fatal error in defaults handling. Program aborted!

My codes are like below;

        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.WorkingDirectory = destPath + "\\bin";
        p.StartInfo.FileName = destPath + "\\bin\\mysqld.exe";
        p.StartInfo.Arguments = "--defaults-file=" + destPath + "\\my.ini --initialize-insecure --console";
        p.OutputDataReceived += P_OutputDataReceived;
        p.Start();

        // destPath:"C:\\Program Files\\MySQL"


问:
How to show/hide Telegram group messages only for group members, who carry out some action?
We have a group in Telegram and want to hide group messages from members before they carry out some action, for example enter email. After member enter his email, he can see all group messages, else see nothing.

Is it possible with Telegram API or Telegram bot API?

答: There is no message hiding ability in Telegram but there are some workarounds. You could create a bot that interact with user (e.g. gets and verifies his/her email) and then sends all "hidden" messages to him. Or just adds him to a private group (where no one can add other people except admin).</p>


问:
Prevent VS Code intellisense suggestion boxes from consuming up/down arrows
When I type "std::" in VS Code with Intellisense active, a dropdown appears with suggested completions. Then, pressing the down key will cycle through the dropdown. But I don't want to browse through the dropdown with my arrow keys; I want to move to the next line of code. Is there a way to make arrow keys ignore the dropdown without disabling dropdowns entirely?</p>

答:
Add these to your keybindings.json or find the selectNextSuggestion and selectPrevSuggestion commands in the Ketboard Shortcuts and disable them:

{
  "key": "down",
  "command": "-selectNextSuggestion",
  "when": "suggestWidgetMultipleSuggestions && suggestWidgetVisible && textInputFocus || suggestWidgetVisible && textInputFocus && !suggestWidgetHasFocusedSuggestion"
},
{
  "key": "up",
  "command": "-selectPrevSuggestion",
  "when": "suggestWidgetMultipleSuggestions && suggestWidgetVisible && textInputFocus || suggestWidgetVisible && textInputFocus && !suggestWidgetHasFocusedSuggestion"
}
// {
//   "key": "down",
//   "command": "your other command here",
//   "when": "suggestWidgetMultipleSuggestions && suggestWidgetVisible && textInputFocus || suggestWidgetVisible && textInputFocus && !suggestWidgetHasFocusedSuggestion"
// }
```

The first disables the default DownArrow action when a suggest panel is open and the second makes the DownArrow do something else in that situation.  You don't need the second keybinding since you only want the default action once the special selectNextSuggestion is disabled.

By the way, even with this these keybindings removed you can still use Ctrl+Up/Down to move the selection in the suggest widget.

Body:
Add these to your keybindings.json or find the selectNextSuggestion and selectPrevSuggestion commands in the Ketboard Shortcuts and disable them:

{
  "key": "down",
  "command": "-selectNextSuggestion",
  "when": "suggestWidgetMultipleSuggestions && suggestWidgetVisible && textInputFocus || suggestWidgetVisible && textInputFocus && !suggestWidgetHasFocusedSuggestion"
},
{
  "key": "up",
  "command": "-selectPrevSuggestion",
  "when": "suggestWidgetMultipleSuggestions && suggestWidgetVisible && textInputFocus || suggestWidgetVisible && textInputFocus && !suggestWidgetHasFocusedSuggestion"
}
// {
//   "key": "down",
//   "command": "your other command here",
//   "when": "suggestWidgetMultipleSuggestions && suggestWidgetVisible && textInputFocus || suggestWidgetVisible && textInputFocus && !suggestWidgetHasFocusedSuggestion"
// }

The first disables the default DownArrow action when a suggest panel is open and the second makes the DownArrow do something else in that situation.  You don't need the second keybinding since you only want the default action once the special selectNextSuggestion is disabled.

By the way, even with this these keybindings removed you can still use Ctrl+Up/Down to move the selection in the suggest widget.


问:
Syntax error when trying to pipe multiple commands in an alias definition
Hey can anyone help me to solve syntax error on creation of alias.I am new to bash so i am not aware of any restriction in use of alias command

Every time i run this alias command

```<code>alias user='responseVar=$(curl -XGET link)  && echo ${responseVar} | jq '.offsets[] | " \(.topic) \(.offset) \(.logSize) "' | awk 'NR>1{arr[$2]=arr[$2]+($4-$3)} END{for (a in arr) print a"="arr[a]}''
</code>```

I get this error.

```<code>bash: syntax error near unexpected token `('
</code>```

答:
Avoid using alias (they're only allowed in interactive shells) and define a simple function instead to do

```<code>doSomething() {
    curl -XGET link | jq '.offsets[] | " \(.topic) \(.offset) \(.logSize) "' |
       awk 'NR>1{arr[$2]=arr[$2]+($4-$3)} END{for (a in arr) print a"="arr[a]}'
}
</code>```

and defined in any of your startup configuration files(e.g. .bashrc for instance) and launch and new shell and do just

```<code>doSomething
</code>```

Body:
Hey can anyone help me to solve syntax error on creation of alias.I am new to bash so i am not aware of any restriction in use of alias command

Every time i run this alias command

alias user='responseVar=$(curl -XGET link)  && echo ${responseVar} | jq '.offsets[] | " \(.topic) \(.offset) \(.logSize) "' | awk 'NR>1{arr[$2]=arr[$2]+($4-$3)} END{for (a in arr) print a"="arr[a]}''

I get this error.

bash: syntax error near unexpected token `('

Body:
Avoid using alias (they're only allowed in interactive shells) and define a simple function instead to do

doSomething() {
    curl -XGET link | jq '.offsets[] | " \(.topic) \(.offset) \(.logSize) "' |
       awk 'NR>1{arr[$2]=arr[$2]+($4-$3)} END{for (a in arr) print a"="arr[a]}'
}

and defined in any of your startup configuration files(e.g. .bashrc for instance) and launch and new shell and do just

doSomething


问:
How to set last recorded value to spinner dropdown?
```<code>String Food;
String[] FoodArray;
Spinner spinFood;
spinFood= (Spinner) findViewById(R.id.spin_food);
FoodArray=getResources().getStringArray(R.array.carray);
spinFood.setAdapter(new
CustomSpinnerAdapter(ChildActivity.this,R.layout.activity_child,FoodArray));

spinFood.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int
        position, long id) {

            if(position==1){
                Food=getString(R.string.textYes);
            }
            else if (position==2){
                Food=getString(R.string.textNo);
            }
            else {
               Food="0";
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
</code>```

i tried a lot  but didn't get the answer,
 please help me.

the spinner should be set to a last recorded value which comes from the database, by default.

答: You can use spinner.setSelection() method to record your last transaction

Body:
String Food;
String[] FoodArray;
Spinner spinFood;
spinFood= (Spinner) findViewById(R.id.spin_food);
FoodArray=getResources().getStringArray(R.array.carray);
spinFood.setAdapter(new
CustomSpinnerAdapter(ChildActivity.this,R.layout.activity_child,FoodArray));

spinFood.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int
        position, long id) {

            if(position==1){
                Food=getString(R.string.textYes);
            }
            else if (position==2){
                Food=getString(R.string.textNo);
            }
            else {
               Food="0";
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

i tried a lot  but didn't get the answer,
 please help me.

the spinner should be set to a last recorded value which comes from the database, by default.