问:
getting webpack to ignore electron main process packages
While it is not necessary for Electron, I wanted to webpack all the render process javascript (as apposed to the nodejs (called main process) javascript. And put render process javascript in a single bundle.

Why:

This might be a bit faster for startup

It will give me the ability to use the webpack server for hot loading

Well I pointed webpack at the root of render-side javascript, and it started making the bundle. But it also is seeing some electron remote javascript components and is trying to bundle those in also, and is failing.

How do I get Webpack to ignore lines that are pointing to the remote/main process code: (all my main process code will be in a folder called ./main). I tried to exclude the ./main/* folder, but perhaps I did not do that properly

Example lines

```<code>const { remote } = require('electron')
const { dialog } = remote.require('electron')
const { dialog } = require('electron').remote
const utils = remote.require('../main/utils')
const watson = remote.require('../main/watson')
</code>```

Webpack.config.js

```<code>const webpack = require('webpack')
const path = require('path')

const config = {
    context: path.resolve(__dirname, '..', 'src'),
    entry: './dash/dash.js',
    output: {
        path: path.resolve(__dirname, '..' , 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            test: /\.js$/,
            include: path.resolve(__dirname, 'src'),
            exclude: /(main)/,
            use: [{
                loader: 'babel-loader',
                options: {
                    "sourceMaps": "inline",
                    presets: [
                        ['react', "node7", "stage-3",
                            { modules: false }]
                    ]
                }
            }]
        }]
    }
}
</code>```

module.exports = config

Output

```<code>Hash: 3aa4f4a528c7beea5c01
Version: webpack 2.6.0
Time: 4157ms
    Asset     Size  Chunks                    Chunk Names
bundle.js  2.98 MB       0  [emitted]  [big]  main
   [0] ./~/process/browser.js 5.42 kB {0} [built]
   [1] ./~/react/react.js 56 bytes {0} [built]
  [52] ./dist/dash/actions.js 18.6 kB {0} [built]
  [53] ./~/electron/index.js 338 bytes {0} [built]
  [54] ./~/redux/es/index.js 1.08 kB {0} [built]
 [310] ./dist/dash/initialState.json 357 bytes {0} [built]
 [311] ./dist/dash/reducers.js 8.22 kB {0} [built]
 [312] ./dist/jsx/Dashboard.js 7.08 kB {0} [built]
 [313] ./dist/main/utils.js 12.6 kB {0} [built]
 [314] ./~/redux-devtools-extension/index.js 635 bytes {0} [built]
 [315] ./~/redux-thunk/lib/index.js 529 bytes {0} [built]
 [316] ./~/shallow-equal/objects/index.js 394 bytes {0} [built]
 [317] ./dist/dash/dash.js 8.74 kB {0} [built]
 [321] ./dist/jsx/Utilities.js 5.55 kB {0} [built]
 [322] ./dist/main 160 bytes {0} [built]
    + 755 hidden modules

WARNING in ./dist/main/utils.js
34:25-44 Critical dependency: the request of a dependency is an expression

ERROR in ./dist/main/utils.js
Module not found: Error: Can't resolve 'fs' in 'd:\wwwroot\librarian2017\dashboard\dist\main'
 @ ./dist/main/utils.js 5:11-24
 @ ./dist/dash/dash.js

ERROR in ./dist/main/utils.js
Module not found: Error: Can't resolve 'child_process' in 'd:\wwwroot\librarian2017\dashboard\dist\main'
 @ ./dist/main/utils.js 9:22-46
 @ ./dist/dash/dash.js

ERROR in ./~/electron/index.js
Module not found: Error: Can't resolve 'fs' in 'd:\wwwroot\librarian2017\dashboard\node_modules\electron'
 @ ./~/electron/index.js 1:9-22
 @ ./dist/dash/dash.js

ERROR in ./~/get-folder-size/index.js
Module not found: Error: Can't resolve 'fs' in 'd:\wwwroot\librarian2017\dashboard\node_modules\get-folder-size'
 @ ./~/get-folder-size/index.js 3:9-22
 @ ./dist/main/utils.js
 @ ./dist/dash/dash.js

ERROR in ./~/rmdir/lib/rmdir.js
Module not found: Error: Can't resolve 'fs' in 'd:\wwwroot\librarian2017\dashboard\node_modules\rmdir\lib'
 @ ./~/rmdir/lib/rmdir.js 9:9-22
 @ ./~/rmdir/index.js
 @ ./dist/main/utils.js
 @ ./dist/dash/dash.js
</code>```

答:
Thank you @shashi, I found from on the webpack github site there were two things I was missing. One was the target, and the other was a resolve field (since I am using REACT in jsx files). See solution below:</p>

```<code>const webpack = require('webpack')
const path = require('path')

const config = {
    context: path.resolve(__dirname, '..', 'src'),
    entry: './dash/dash.js',
    target: "electron-renderer",
    output: {
        path: path.resolve(__dirname, '..', 'dist'),
        filename: 'bundle.js'
    },
    resolve: { extensions: [".jsx", ".js", ".json"] },
    module: {
        rules: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            include: path.resolve(__dirname, '..', 'src'),
            use: [{
                loader: 'babel-loader',
                options: {
                    "sourceMaps": "inline",
                    "presets": [
                        "react",
                        [
                            "env",
                            {
                                "targets": {
                                    "electron": "1.6.7"
                                },
                                "debug": true,
                                "useBuiltIns": true
                            }
                        ]
                    ],
                    "plugins": [
                        "transform-object-rest-spread"
                    ]
                }
            }]
        }]
    }
}

module.exports = config
</code>```

Body:
While it is not necessary for Electron, I wanted to webpack all the render process javascript (as apposed to the nodejs (called main process) javascript. And put render process javascript in a single bundle.

Why:

This might be a bit faster for startup

It will give me the ability to use the webpack server for hot loading

Well I pointed webpack at the root of render-side javascript, and it started making the bundle. But it also is seeing some electron remote javascript components and is trying to bundle those in also, and is failing.

How do I get Webpack to ignore lines that are pointing to the remote/main process code: (all my main process code will be in a folder called ./main). I tried to exclude the ./main/* folder, but perhaps I did not do that properly

Example lines

const { remote } = require('electron')
const { dialog } = remote.require('electron')
const { dialog } = require('electron').remote
const utils = remote.require('../main/utils')
const watson = remote.require('../main/watson')

Webpack.config.js

const webpack = require('webpack')
const path = require('path')

const config = {
    context: path.resolve(__dirname, '..', 'src'),
    entry: './dash/dash.js',
    output: {
        path: path.resolve(__dirname, '..' , 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            test: /\.js$/,
            include: path.resolve(__dirname, 'src'),
            exclude: /(main)/,
            use: [{
                loader: 'babel-loader',
                options: {
                    "sourceMaps": "inline",
                    presets: [
                        ['react', "node7", "stage-3",
                            { modules: false }]
                    ]
                }
            }]
        }]
    }
}

module.exports = config

Output

Hash: 3aa4f4a528c7beea5c01
Version: webpack 2.6.0
Time: 4157ms
    Asset     Size  Chunks                    Chunk Names
bundle.js  2.98 MB       0  [emitted]  [big]  main
   [0] ./~/process/browser.js 5.42 kB {0} [built]
   [1] ./~/react/react.js 56 bytes {0} [built]
  [52] ./dist/dash/actions.js 18.6 kB {0} [built]
  [53] ./~/electron/index.js 338 bytes {0} [built]
  [54] ./~/redux/es/index.js 1.08 kB {0} [built]
 [310] ./dist/dash/initialState.json 357 bytes {0} [built]
 [311] ./dist/dash/reducers.js 8.22 kB {0} [built]
 [312] ./dist/jsx/Dashboard.js 7.08 kB {0} [built]
 [313] ./dist/main/utils.js 12.6 kB {0} [built]
 [314] ./~/redux-devtools-extension/index.js 635 bytes {0} [built]
 [315] ./~/redux-thunk/lib/index.js 529 bytes {0} [built]
 [316] ./~/shallow-equal/objects/index.js 394 bytes {0} [built]
 [317] ./dist/dash/dash.js 8.74 kB {0} [built]
 [321] ./dist/jsx/Utilities.js 5.55 kB {0} [built]
 [322] ./dist/main 160 bytes {0} [built]
    + 755 hidden modules

WARNING in ./dist/main/utils.js
34:25-44 Critical dependency: the request of a dependency is an expression

ERROR in ./dist/main/utils.js
Module not found: Error: Can't resolve 'fs' in 'd:\wwwroot\librarian2017\dashboard\dist\main'
 @ ./dist/main/utils.js 5:11-24
 @ ./dist/dash/dash.js

ERROR in ./dist/main/utils.js
Module not found: Error: Can't resolve 'child_process' in 'd:\wwwroot\librarian2017\dashboard\dist\main'
 @ ./dist/main/utils.js 9:22-46
 @ ./dist/dash/dash.js

ERROR in ./~/electron/index.js
Module not found: Error: Can't resolve 'fs' in 'd:\wwwroot\librarian2017\dashboard\node_modules\electron'
 @ ./~/electron/index.js 1:9-22
 @ ./dist/dash/dash.js

ERROR in ./~/get-folder-size/index.js
Module not found: Error: Can't resolve 'fs' in 'd:\wwwroot\librarian2017\dashboard\node_modules\get-folder-size'
 @ ./~/get-folder-size/index.js 3:9-22
 @ ./dist/main/utils.js
 @ ./dist/dash/dash.js

ERROR in ./~/rmdir/lib/rmdir.js
Module not found: Error: Can't resolve 'fs' in 'd:\wwwroot\librarian2017\dashboard\node_modules\rmdir\lib'
 @ ./~/rmdir/lib/rmdir.js 9:9-22
 @ ./~/rmdir/index.js
 @ ./dist/main/utils.js
 @ ./dist/dash/dash.js

Body:
Thank you @shashi, I found from on the webpack github site there were two things I was missing. One was the target, and the other was a resolve field (since I am using REACT in jsx files). See solution below:

const webpack = require('webpack')
const path = require('path')

const config = {
    context: path.resolve(__dirname, '..', 'src'),
    entry: './dash/dash.js',
    target: "electron-renderer",
    output: {
        path: path.resolve(__dirname, '..', 'dist'),
        filename: 'bundle.js'
    },
    resolve: { extensions: [".jsx", ".js", ".json"] },
    module: {
        rules: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            include: path.resolve(__dirname, '..', 'src'),
            use: [{
                loader: 'babel-loader',
                options: {
                    "sourceMaps": "inline",
                    "presets": [
                        "react",
                        [
                            "env",
                            {
                                "targets": {
                                    "electron": "1.6.7"
                                },
                                "debug": true,
                                "useBuiltIns": true
                            }
                        ]
                    ],
                    "plugins": [
                        "transform-object-rest-spread"
                    ]
                }
            }]
        }]
    }
}

module.exports = config


来源: stackexchange

问:
How to use custom chaining modes in .Net with OpenSSL?
I need to implement custom chaining mode for encryption. I need to use symmetric block cipher (AES, 3DES, DES, IDEA). The problem I encounter is, the libraries/wrappers I found do not allow it.

BouncyCastle has those as Enum: Mode = CipherMode.CBC, so I do not see - how I can use my own. System.Security.Cryptography seem to do same way.

Is there any .NET library or wrapper, that allows custom made chaining modes?

Right now only idea I have got is to encrypt every block using CBC with IV full of zero bits and implement my chaining mode on top of it, but it does not seems as good idea.

答:
I don't know of any library that supports a chaining callback, it sort of goes against the black-box-ness of most cryptographic API.

The way to accomplish your goal is to encrypt using ECB, since that is "just apply the encryption algorithm to this data". For example, to do CBC:

```<code>private byte[] _iv;
private ICryptoTransform _encryptor;

private void EncryptBlock(byte[] input, byte[] output)
{
    byte[] buf = (byte[])input.Clone();

    for (int i = 0; i < buf.Length; i++)
    {
        buf[i] ^= _iv[i];
    }

    _encryptor.TransformBlock(buf, 0, buf.Length, output, 0);
    Buffer.BlockCopy(out, 0, _iv, 0, output.Length);
}
</code>```

(all sorts of error checking omitted)

Given somewhere you initialized things as

```<code>using (Aes aes = Aes.Create())
{
    aes.Mode = CipherMode.ECB;
    aes.Key = key;
    _encryptor = aes.CreateEncryptor();
    _decryptor = aes.CreateDecryptor();
}
</code>```

(etc).

ContentLicense: CC BY-SA 3.0

Body:
I don't know of any library that supports a chaining callback, it sort of goes against the black-box-ness of most cryptographic API.

The way to accomplish your goal is to encrypt using ECB, since that is "just apply the encryption algorithm to this data". For example, to do CBC:

private byte[] _iv;
private ICryptoTransform _encryptor;

private void EncryptBlock(byte[] input, byte[] output)
{
    byte[] buf = (byte[])input.Clone();

    for (int i = 0; i < buf.Length; i++)
    {
        buf[i] ^= _iv[i];
    }

    _encryptor.TransformBlock(buf, 0, buf.Length, output, 0);
    Buffer.BlockCopy(out, 0, _iv, 0, output.Length);
}

(all sorts of error checking omitted)

Given somewhere you initialized things as

using (Aes aes = Aes.Create())
{
    aes.Mode = CipherMode.ECB;
    aes.Key = key;
    _encryptor = aes.CreateEncryptor();
    _decryptor = aes.CreateDecryptor();
}

(etc).


问:
Count distinct values in array - performance tips
I'm having some issues optimizing a go map.

I want to generate a frequency table (count distinct occurrences) in an array of strings. My code holds nicely for small arrays, but as I start working with 100k+ structures -with many distinct values- it just isn't performant enough.

Right now, my approach is to generate an array with the distinct values, compare values and increasing the counter variable (mapped to the string).

```<code>    counter := make( map[string]int )
    for _, distinct := range distinctStrArray{
        for _, row := range StrArray{
            if (row == distinct){
                counter[distinct]++
            }
        }
    }
</code>```

I've tried another approach, where with the input array previously sorted (to minimize the number of changes to the map). This is a bit faster.

```<code>    count:=0
    for _, distinct := range distinctStrArray{
        for _, row := range StrArray{
            if (row == distinct){
                count++
            }
        }
    counter[distinct] += count
    count= 0
    }
</code>```

Do you have any suggestion of what I can do to optimize a simple count(distinct) type problem...? I'm open to anything.

thanks!

答:
Without more context, I would dump the separate array of distinct values - generating it takes time, and using it necessitates the nested loop. Assuming there's no other purpose to the second array, I'd use something like:

```<code>counter := make( map[string]int )
for _, row := range StrArray {
    counter[row]++
}
</code>```

If you need the list of distinct strings without the counts for some separate purpose, you can easily get it afterward:

```<code>distinctStrings := make([]string, len(counter))
i := 0
for k := range counter {
    distinctStrings[i] = k
    i++
}
</code>```

Iterating the array of distinct strings is O(n), while map access by key is O(log(n)). That takes your overall from O(n^2) to O(n*log(n)), which should be a significant improvement with larger datasets. But, as with any optimization: test, measure, analyze, optimize.

ContentLicense: CC BY-SA 4.0

Body:
I'm having some issues optimizing a go map.

I want to generate a frequency table (count distinct occurrences) in an array of strings. My code holds nicely for small arrays, but as I start working with 100k+ structures -with many distinct values- it just isn't performant enough.

Right now, my approach is to generate an array with the distinct values, compare values and increasing the counter variable (mapped to the string).

    counter := make( map[string]int )
    for _, distinct := range distinctStrArray{
        for _, row := range StrArray{
            if (row == distinct){
                counter[distinct]++
            }
        }
    }

I've tried another approach, where with the input array previously sorted (to minimize the number of changes to the map). This is a bit faster.

    count:=0
    for _, distinct := range distinctStrArray{
        for _, row := range StrArray{
            if (row == distinct){
                count++
            }
        }
    counter[distinct] += count
    count= 0
    }

Do you have any suggestion of what I can do to optimize a simple count(distinct) type problem...? I'm open to anything.

thanks!

Body:
Without more context, I would dump the separate array of distinct values - generating it takes time, and using it necessitates the nested loop. Assuming there's no other purpose to the second array, I'd use something like:

counter := make( map[string]int )
for _, row := range StrArray {
    counter[row]++
}

If you need the list of distinct strings without the counts for some separate purpose, you can easily get it afterward:

distinctStrings := make([]string, len(counter))
i := 0
for k := range counter {
    distinctStrings[i] = k
    i++
}

Iterating the array of distinct strings is O(n), while map access by key is O(log(n)). That takes your overall from O(n^2) to O(n*log(n)), which should be a significant improvement with larger datasets. But, as with any optimization: test, measure, analyze, optimize.


问:
When will a thread woken via a condition variable run?
When I wake up a thread waiting on a condition variable while holding the corresponding mutex, can I assume that the woken thread will run after I release the mutex and before anyone else (myself included) can lock the mutex again? Or can I only be sure that it will run at some point in the future?

To be precise, assume that I have the following functions.

```<code>bool taken = false;
int waiting = 0;

pthread_mutex_t m;   // properly initialised elsewhere
pthread_cond_t c;

void enter() {
    pthread_mutex_lock(&m);
    // Is `taken || (waiting == 0)` guaranteed here?
    while (taken) {
        ++ waiting;
        pthread_cond_wait(&c, &m);
        -- waiting;
    }
    taken = true;
    pthread_mutex_unlock(&m);
}

void leave() {
    pthread_mutex_lock(&m);
    taken = false;
    if (waiting > 0) {
        pthread_cond_signal(&c);
    }
    pthread_mutex_unlock(&m);
}
</code>```

(This is a toy example, not meant to be useful.)

Also assume that all threads are using these functions as

```<code>enter()
// some work here
leave()
</code>```

Can I then be sure that directly after acquiring the mutex in enter() (see comment in the code), if taken is false waiting has to be zero? [It seems to me that this should be the case, because the woken thread will assume to find the state that the waking thread has left behind (if the wake-up was not spurious) and this could otherwise not be guaranteed, but I did not find it clearly worded anywhere.]

I am mainly interested in the behaviour on (modern) Linux, but of course knowing whether this is defined by POSIX would also be of interest.

Note: This may have already been asked in another question, but I hope that mine is clearer.

After t0 does pthread_cond_signal, t1 is no longer waiting for the condition variable, but it is also not running, because t0 still holds the mutex; t1 is instead waiting for the mutex. The thread t2 may also be waiting for the mutex, at the beginning of enter(). Now t0 releases the mutex. Both t1 and t2 are waiting for it. Is t1 handled in a special way and guaranteed to get it, or could t2 get it instead?

答:
Thanks for your comment, Carsten, that cleared it up.

No, see this answer for more reference. Given your example, t2 could acquire the mutex before t1 and a race condition may occur leading to unexpected outcomes.

Reiterating, t0 may initially have the mutex and be in the while loop holding on the line pthread_cond_wait(&c, &m);and the mutex is released atomically reference. t1 could call leave() acquiring the mutex signaling the condition c, and then release the mutex. t0 will prepare to run --waiting by trying to acquire the now-freed mutex by t1, but it can become context switched by the OS. Some other thread t2 waiting on the mutex can grab it and run enter() causing undesired outcomes, see non-reentrant. t2 then releases the mutex. t0 may swaps back only to see values have been mutated.

Body:
When I wake up a thread waiting on a condition variable while holding the corresponding mutex, can I assume that the woken thread will run after I release the mutex and before anyone else (myself included) can lock the mutex again? Or can I only be sure that it will run at some point in the future?

To be precise, assume that I have the following functions.

bool taken = false;
int waiting = 0;

pthread_mutex_t m;   // properly initialised elsewhere
pthread_cond_t c;

void enter() {
    pthread_mutex_lock(&m);
    // Is `taken || (waiting == 0)` guaranteed here?
    while (taken) {
        ++ waiting;
        pthread_cond_wait(&c, &m);
        -- waiting;
    }
    taken = true;
    pthread_mutex_unlock(&m);
}

void leave() {
    pthread_mutex_lock(&m);
    taken = false;
    if (waiting > 0) {
        pthread_cond_signal(&c);
    }
    pthread_mutex_unlock(&m);
}

(This is a toy example, not meant to be useful.)

Also assume that all threads are using these functions as

enter()
// some work here
leave()

Can I then be sure that directly after acquiring the mutex in enter() (see comment in the code), if taken is false waiting has to be zero? [It seems to me that this should be the case, because the woken thread will assume to find the state that the waking thread has left behind (if the wake-up was not spurious) and this could otherwise not be guaranteed, but I did not find it clearly worded anywhere.]

I am mainly interested in the behaviour on (modern) Linux, but of course knowing whether this is defined by POSIX would also be of interest.

Note: This may have already been asked in another question, but I hope that mine is clearer.

After t0 does pthread_cond_signal, t1 is no longer waiting for the condition variable, but it is also not running, because t0 still holds the mutex; t1 is instead waiting for the mutex. The thread t2 may also be waiting for the mutex, at the beginning of enter(). Now t0 releases the mutex. Both t1 and t2 are waiting for it. Is t1 handled in a special way and guaranteed to get it, or could t2 get it instead?


问:
Start a Animation when I press a Button doesn't work
I have a beginning Animation which is called divanimated. Its a rectangel which comes in. Now I want to start a 2nd Animation on this div when I hit a button. I don't know why it isn't working.
Here is my code:

```<code>    <div class="div"> </div>
    <img src="/arrowright.png" class="arrowright">
    <script>
        $(".arrowright").click(function(){
            $(".div").toggleClass("divanimated");
        });
    </script>
</code>```

css:

```<code>.divanimated{
animation-name: divanimated;
-webkit-animation-name: divanimated;

animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;

animation-timing-function: ease-out;
-webkit-animation-timing-function: ease-out;

transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
-webkit-transform-origin: 0% 0%;

 background: #e74c3c;
z-index: 1;
width: 72.8vw;
height: 39vh;
margin-top: 136.5vh;
margin-left: 13.6vw;
position: absolute;
border-radius: 7vh;
display: none;
box-shadow:2px 2px 10px #333333;
}

@keyframes divanimated{
0% {
    transform: scaleX(0.3);
}
40% {
    transform: scaleX(1.02);
}
60% {
    transform: scaleX(0.98);
}
80% {
    transform: scaleX(1.01);
}
100% {
    transform: scaleX(0.98);
}
80% {
    transform: scaleX(1.01);
}
100% {
    transform: scaleX(1);
}
}

@-webkit-keyframes divanimated{
0% {
    -webkit-transform: scaleX(0.3);
}
40% {
    -webkit-transform: scaleX(1.02);
}
60% {
    -webkit-transform: scaleX(0.98);
}
80% {
    -webkit-transform: scaleX(1.01);
}
100% {
    -webkit-transform: scaleX(0.98);
}
80% {
    -webkit-transform: scaleX(1.01);
}
100% {
    -webkit-transform: scaleX(1);
}
}
.div{
animation-name: div;
-webkit-animation-name: div;

animation-duration: 1.6s;
-webkit-animation-duration: 1.6s;

animation-timing-function: ease-out;
-webkit-animation-timing-function: ease -out;

visibility: visible !important;

background: #e74c3c;
z-index: 1;
width: 72.8vw;
height: 39vh;
margin-top: 136.5vh;
margin-left: 13.6vw;
position: absolute;
border-radius: 7vh;
display: none;
box-shadow:2px 2px 10px #333333;
}

@keyframes div{
0% {
    transform: translateY(100%) scaleX(0.5);
}
30%{
    transform: translateY(-8%) scaleX(0.5);
}
40%{
    transform: translateY(2%) scaleX(0.5);
}
50%{
    transform: translateY(0%) scaleX(1.1);
}
60%{
    transform: translateY(0%) scaleX(0.9);
}
70% {
    transform: translateY(0%) scaleX(1.05);
}
80%{
    transform: translateY(0%) scaleX(0.95);
}
90% {
    transform: translateY(0%) scaleX(1.02);
}
100%{
    transform: translateY(0%) scaleX(1);
}
}

@-webkit-keyframes div{
0% {
    -webkit-transform: translateY(100%) scaleX(0.5);
}
30%{
    -webkit-transform: translateY(-8%) scaleX(0.5);
}
40%{
    -webkit-transform: translateY(2%) scaleX(0.5);
}
50%{
    -webkit-transform: translateY(0%) scaleX(1.1);
}
60%{
    -webkit-transform: translateY(0%) scaleX(0.9);
}
70% {
    -webkit-transform: translateY(0%) scaleX(1.05);
}
80%{
    -webkit-transform: translateY(0%) scaleX(0.95);
}
90% {
    -webkit-transform: translateY(0%) scaleX(1.02);
}
100%{
    -webkit-transform: translateY(0%) scaleX(1);
}
}
</code>```

Can someone help me ? Whats wrong with my code ?

Thanks for the help.

答:
Your .div and .divanimated selectors have the same specificity.  Because the .div style is specified after the .divanimated selector it will override all the similar attributes such as animation-name.

For this example, you could fix the problem by adding the div class to the .divanimated selector.

Your new CSS selector (line 1 of your CSS) would be:
.div.divanimated

Body:
I have a beginning Animation which is called divanimated. Its a rectangel which comes in. Now I want to start a 2nd Animation on this div when I hit a button. I don't know why it isn't working.
Here is my code:

css:

.divanimated{
animation-name: divanimated;
-webkit-animation-name: divanimated;

animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;

animation-timing-function: ease-out;
-webkit-animation-timing-function: ease-out;

transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
-webkit-transform-origin: 0% 0%;

 background: #e74c3c;
z-index: 1;
width: 72.8vw;
height: 39vh;
margin-top: 136.5vh;
margin-left: 13.6vw;
position: absolute;
border-radius: 7vh;
display: none;
box-shadow:2px 2px 10px #333333;
}

@keyframes divanimated{
0% {
    transform: scaleX(0.3);
}
40% {
    transform: scaleX(1.02);
}
60% {
    transform: scaleX(0.98);
}
80% {
    transform: scaleX(1.01);
}
100% {
    transform: scaleX(0.98);
}
80% {
    transform: scaleX(1.01);
}
100% {
    transform: scaleX(1);
}
}

@-webkit-keyframes divanimated{
0% {
    -webkit-transform: scaleX(0.3);
}
40% {
    -webkit-transform: scaleX(1.02);
}
60% {
    -webkit-transform: scaleX(0.98);
}
80% {
    -webkit-transform: scaleX(1.01);
}
100% {
    -webkit-transform: scaleX(0.98);
}
80% {
    -webkit-transform: scaleX(1.01);
}
100% {
    -webkit-transform: scaleX(1);
}
}
.div{
animation-name: div;
-webkit-animation-name: div;

animation-duration: 1.6s;
-webkit-animation-duration: 1.6s;

animation-timing-function: ease-out;
-webkit-animation-timing-function: ease -out;

visibility: visible !important;

background: #e74c3c;
z-index: 1;
width: 72.8vw;
height: 39vh;
margin-top: 136.5vh;
margin-left: 13.6vw;
position: absolute;
border-radius: 7vh;
display: none;
box-shadow:2px 2px 10px #333333;
}

@keyframes div{
0% {
    transform: translateY(100%) scaleX(0.5);
}
30%{
    transform: translateY(-8%) scaleX(0.5);
}
40%{
    transform: translateY(2%) scaleX(0.5);
}
50%{
    transform: translateY(0%) scaleX(1.1);
}
60%{
    transform: translateY(0%) scaleX(0.9);
}
70% {
    transform: translateY(0%) scaleX(1.05);
}
80%{
    transform: translateY(0%) scaleX(0.95);
}
90% {
    transform: translateY(0%) scaleX(1.02);
}
100%{
    transform: translateY(0%) scaleX(1);
}
}

@-webkit-keyframes div{
0% {
    -webkit-transform: translateY(100%) scaleX(0.5);
}
30%{
    -webkit-transform: translateY(-8%) scaleX(0.5);
}
40%{
    -webkit-transform: translateY(2%) scaleX(0.5);
}
50%{
    -webkit-transform: translateY(0%) scaleX(1.1);
}
60%{
    -webkit-transform: translateY(0%) scaleX(0.9);
}
70% {
    -webkit-transform: translateY(0%) scaleX(1.05);
}
80%{
    -webkit-transform: translateY(0%) scaleX(0.95);
}
90% {
    -webkit-transform: translateY(0%) scaleX(1.02);
}
100%{
    -webkit-transform: translateY(0%) scaleX(1);
}
}

Can someone help me ? Whats wrong with my code ?

Thanks for the help.


问:
XMLHttpRequest for html page on web server but not in development
I have a web page which needs to load two separate rss feeds and display them in a ticker. The page loads and runs fine on my own machine but when I put it on our apache web server, it doesn't load anything.  When I open up the debug console, it shows the following error (in Safari 5.0.2):

NETWORK_ERR: XMLHttpRequest Exception 101: A network error occured in synchronous requests

How can I fix this?

Here's the basic outline of the javascript methods for loading the rss feeds.

```<code>function init() {
        // get RSS forecast
        getRSS("http://weather.yahooapis.com/forecastrss?p=63211");
        getRSS("http://webserver.com/reader.xml");
    }

function getRSS (url) {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.send();
    xmlobject=xmlhttp.responseXML;
    // code to process response here...
    }
</code>```

答: Issue is that JavaScript has the same origin policy so you can not grab content from another domain. </p>

ContentLicense: CC BY-SA 2.5

Body:
I have a web page which needs to load two separate rss feeds and display them in a ticker. The page loads and runs fine on my own machine but when I put it on our apache web server, it doesn't load anything.  When I open up the debug console, it shows the following error (in Safari 5.0.2):

NETWORK_ERR: XMLHttpRequest Exception 101: A network error occured in synchronous requests

How can I fix this?

Here's the basic outline of the javascript methods for loading the rss feeds.

function init() {
        // get RSS forecast
        getRSS("http://weather.yahooapis.com/forecastrss?p=63211");
        getRSS("http://webserver.com/reader.xml");
    }

function getRSS (url) {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.send();
    xmlobject=xmlhttp.responseXML;
    // code to process response here...
    }


问:
Typescript can't find 'require', setting up pouchdb with Ionic2
I'm also trying to follow the Tutorial How To Use PouchDB + SQLite For Local Storage In Ionic 2, which seems a good entry point for using pouchdb with Angular 2 / Ionic 2. My OS is OSx

After getting able to install typings 'require' ionic serve throws:

TypeScript error: (...) Error TS2304: Cannot find name 'require'.

I followed the installing typings require failed in macOSX and Install Typings require for Ionic2 application threads but it didn't help me. (beside of a better understanding of 'TypeScript')

the require files are under:

```<code>/ionic2-tutorial-pouchdb/typings/globals/require
</code>```

any Ideas? The tutorial about 'install require' doesn't work for me.

thx Pitt

答:
I'm guessing that you have a line of code like:

```<code>let PouchDB = require('pouchdb');
</code>```

You do not need to use require for importing into Angular2. Instead you should use import like this:

```<code>import PouchDB from 'pouchdb';
</code>```

Reference from one of the GitHub issues on the PouchDB GitHub account

The link you provided also uses import rather than require. Also in newer versions of typescript, Typings have been replaced with @Types.

Body:
I'm also trying to follow the Tutorial How To Use PouchDB + SQLite For Local Storage In Ionic 2, which seems a good entry point for using pouchdb with Angular 2 / Ionic 2. My OS is OSx

After getting able to install typings 'require' ionic serve throws:

TypeScript error: (...) Error TS2304: Cannot find name 'require'.

I followed the installing typings require failed in macOSX and Install Typings require for Ionic2 application threads but it didn't help me. (beside of a better understanding of 'TypeScript')

the require files are under:

/ionic2-tutorial-pouchdb/typings/globals/require

any Ideas? The tutorial about 'install require' doesn't work for me.

thx Pitt

Body:
I'm guessing that you have a line of code like:

let PouchDB = require('pouchdb');

You do not need to use require for importing into Angular2. Instead you should use import like this:

import PouchDB from 'pouchdb';

Reference from one of the GitHub issues on the PouchDB GitHub account

The link you provided also uses import rather than require. Also in newer versions of typescript, Typings have been replaced with @Types.


问:
TypeError: Cannot read property 'prototype' of undefined
I have an issue that I can't seem to resolve, mostly because I have little knowledge of why it is occurring in this particular scenario.
Here's the error :

```<code>TypeError: Cannot read property 'followers' of undefined
    at Object.<anonymous> (C:\Users\username\Documents\My Lib\bot\src\bot.js:15:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3
</code>```

and here's what the code looks like :

```<code>const Twit = require('twit'),
    config = require('./config'),
    init = new Twit(config);

function Twitter(twitter) {
    this.twitter = twitter
}

Twitter.prototype.followers = function(params) {
    this.twitter.get('followers/list', params, (err, data) => {
        if (!err)
            data.users.forEach(user => console.log(data))
    })
};

var bot = Twitter(init);

bot.followers({ screen_name: 'myscreenname'})
</code>```

Haha. I'm almost certain it's a silly mistake. I just can't seem to find the source.
Any help is and will be appreciated.

答:
You forgot the new keyword. Try this:

```<code>var bot = new Twitter(init);
</code>```

Body:
I have an issue that I can't seem to resolve, mostly because I have little knowledge of why it is occurring in this particular scenario.
Here's the error :

TypeError: Cannot read property 'followers' of undefined
    at Object.<anonymous> (C:\Users\username\Documents\My Lib\bot\src\bot.js:15:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3

and here's what the code looks like :

const Twit = require('twit'),
    config = require('./config'),
    init = new Twit(config);

function Twitter(twitter) {
    this.twitter = twitter
}

Twitter.prototype.followers = function(params) {
    this.twitter.get('followers/list', params, (err, data) => {
        if (!err)
            data.users.forEach(user => console.log(data))
    })
};

var bot = Twitter(init);

bot.followers({ screen_name: 'myscreenname'})

Haha. I'm almost certain it's a silly mistake. I just can't seem to find the source.
Any help is and will be appreciated.

Body:
You forgot the new keyword. Try this:

var bot = new Twitter(init);


问:
Host machine cannot access nginx virtual hosts on the guest machine
Question: how to create simple nginx config that will read folders structure as domains (test.local, myblog.local) and shows the page from this folders, including PHP?

Information:
Windows 10 x64 build

Vagrant 1.9.5

VirtualBox 5.0.22 (latest)

Guest OS: Ubuntu Xenial x64 latest

So, i want to create simple nginx config, that will recreate folder structure. See
my config file on pastebin.

Also here is a Vagrantfile config, which use SMB to mount a folder.

The structure of folders:

```<code>├───devhost.local
│   ├───log
│   └───public
│           index.html
│           index.php
│
└───test.local
    ├───log
    └───public
            index.html
</code>```

The rights for files and folders for devhost:

```<code>ubuntu@ubuntu-xenial:~$ ls -la /var/www/html/devhost.local/
total 4
drwxr-xr-x 2 ubuntu www-data    0 Jun  7 11:17 .
drwxr-xr-x 2 ubuntu www-data 4096 Jun  7 12:44 ..
drwxr-xr-x 2 ubuntu www-data    0 Jun  7 11:17 log
drwxr-xr-x 2 ubuntu www-data    0 Jun  6 14:13 public
</code>```

My hosts file in Windows:

```<code>192.168.33.10   devhost.local
</code>```

So, when i have default config in my sites-enabled folder i can open guest machine through 192.168.33.10 and i see html page of nginx, but when i remove this default config and enable my wildcard config (see link my config file) so i cannot access my domains. The sudo nginx -t says that everything is ok, also i tried to restart my guest machine, reload/restart nginx service. Also, i disable Windows 10 Firewall (i dont know if its disabled fully, but says that its disabled). Also, the log files is empty and even not created, both access log and error log.

Where is my mistake? If need more information, please, ask me, i will give.

Thanks a lot!

答:
following nginx setup should help.</p>

```<code>server {
  listen 80 default_server;
  root /var/www/html/$host;
  index index.html index.php;
  location ~ \.php {
    # ... fastcgi details
  }
}
</code>```

Body:
Question: how to create simple nginx config that will read folders structure as domains (test.local, myblog.local) and shows the page from this folders, including PHP?

Information:
Windows 10 x64 build

Vagrant 1.9.5

VirtualBox 5.0.22 (latest)

Guest OS: Ubuntu Xenial x64 latest

So, i want to create simple nginx config, that will recreate folder structure. See
my config file on pastebin.

Also here is a Vagrantfile config, which use SMB to mount a folder.

The structure of folders:

├───devhost.local
│   ├───log
│   └───public
│           index.html
│           index.php
│
└───test.local
    ├───log
    └───public
            index.html

The rights for files and folders for devhost:

ubuntu@ubuntu-xenial:~$ ls -la /var/www/html/devhost.local/
total 4
drwxr-xr-x 2 ubuntu www-data    0 Jun  7 11:17 .
drwxr-xr-x 2 ubuntu www-data 4096 Jun  7 12:44 ..
drwxr-xr-x 2 ubuntu www-data    0 Jun  7 11:17 log
drwxr-xr-x 2 ubuntu www-data    0 Jun  6 14:13 public

My hosts file in Windows:

192.168.33.10   devhost.local

So, when i have default config in my sites-enabled folder i can open guest machine through 192.168.33.10 and i see html page of nginx, but when i remove this default config and enable my wildcard config (see link my config file) so i cannot access my domains. The sudo nginx -t says that everything is ok, also i tried to restart my guest machine, reload/restart nginx service. Also, i disable Windows 10 Firewall (i dont know if its disabled fully, but says that its disabled). Also, the log files is empty and even not created, both access log and error log.

Where is my mistake? If need more information, please, ask me, i will give.

Thanks a lot!

Body:
following nginx setup should help.

server {
  listen 80 default_server;
  root /var/www/html/$host;
  index index.html index.php;
  location ~ \.php {
    # ... fastcgi details
  }
}


问:
Centering navigation element with CSS
I am trying to center the .site-nav ul li in the .site-nav ul but have not been successful. I've tried align-content, width:100%, margin: 0 auto, text-align. I am relatively new to CSS, a few months, and this is my first time posting a question here. This is the link to my codepen: https://codepen.io/darenjm/pen/eRpNEV

```<code>.clearfix:after{
content:"";
display:block;
clear:both;
}
.wrapper{
width:90%;
margin:0 auto;
}
.site-logo{
text-align:center;
padding: 20px 0 10px 0;
}
.site-nav{
background:#af2922;
}
.site-nav ul{
background:#efedee;
padding:0;
margin:0;
}
.site-nav > ul ul{
position:absolute;
}
.site-nav ul li{
background:#ecc019;
list-style:none;
}
.site-nav ul li a{
display:inline-block;
width:100px;
padding:5px 10px;
text-decoration:none;
}
.site-nav ul li:hover > a{
background:rgba(255,255,255,0.6);
}
nav > ul > li{
float:left;
}
</code>```

答:
You can use inline-block on the li's, then text-align: center on the parent

.clearfix:after{
    content:"";
    display:block;
    clear:both;
}
.wrapper{
    width:90%;
    margin:0 auto;
}
.site-logo{
    text-align:center;
    padding: 20px 0 10px 0;
}
.site-nav{
    background:#af2922;
}
.site-nav ul{
    background:#efedee;
    padding:0;
    margin:0;
  text-align: center;
}
.site-nav > ul ul{
    position:absolute;
}
.site-nav ul li{
    background:#ecc019;
    list-style:none;
}
.site-nav ul li a{
    display:inline-block;
    width:100px;
    padding:5px 10px;
    text-decoration:none;
}
.site-nav ul li:hover > a{
    background:rgba(255,255,255,0.6);
}
nav > ul > li{
    display: inline-block;
}
.block{
    height:50px;
    background:#ddd;
}

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div class="wrapper">
    <div class="site-logo">
      <img src="" alt="" class="logo" width="">
    </div>
    <nav class="site-nav">
      <ul class="clearfix">
        <li>Home</li><li>Projects
          <ul>
            <li class="sub-back">Santa Marta</li>
            <li class="sub-back">Barranquilla</li>
            <li class="sub-back">La Dorada</li>
          </ul>
        </li><li>Customers</li><li>Partners</li><li>About</li><li>Contact</li>
      </ul>
    </nav>
    <!-- .site-nav -->
    <div class="menu-toggle">
      <div class="hamburger"></div>
    </div>
    <div class="block"></div>
  </div>
  <!-- .wrapper -->
</div>
<!-- .header --></code>```

You could also use display: flex; justify-content: center on the parent and remove the float on the li

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}
.wrapper {
  width: 90%;
  margin: 0 auto;
}
.site-logo {
  text-align: center;
  padding: 20px 0 10px 0;
}
.site-nav {
  background: #af2922;
}
.site-nav ul {
  background: #efedee;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.site-nav > ul ul {
  position: absolute;
}
.site-nav ul li {
  background: #ecc019;
  list-style: none;
}
.site-nav ul li a {
  display: inline-block;
  width: 100px;
  padding: 5px 10px;
  text-decoration: none;
}
.site-nav ul li:hover > a {
  background: rgba(255, 255, 255, 0.6);
}

.block {
  height: 50px;
  background: #ddd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div class="wrapper">
    <div class="site-logo">
      <img src="" alt="" class="logo" width="">
    </div>
    <nav class="site-nav">
      <ul class="clearfix">
        <li>Home</li>
        <!--
-->
        <li>Projects
          <ul>
            <li class="sub-back">Santa Marta</li>
            <li class="sub-back">Barranquilla</li>
            <li class="sub-back">La Dorada</li>
          </ul>
        </li>
        <li>Customers</li>
        <li>Partners</li>
        <li>About</li>
        <li>Contact</li>
      </ul>
    </nav>
    <!-- .site-nav -->
    <div class="menu-toggle">
      <div class="hamburger"></div>
    </div>
    <div class="block"></div>
  </div>
  <!-- .wrapper -->
</div>
<!-- .header --></code>```

Title: Centering navigation element with CSS

Body:
I am trying to center the .site-nav ul li in the .site-nav ul but have not been successful. I've tried align-content, width:100%, margin: 0 auto, text-align. I am relatively new to CSS, a few months, and this is my first time posting a question here. This is the link to my codepen: https://codepen.io/darenjm/pen/eRpNEV

.clearfix:after{
content:"";
display:block;
clear:both;
}
.wrapper{
width:90%;
margin:0 auto;
}
.site-logo{
text-align:center;
padding: 20px 0 10px 0;
}
.site-nav{
background:#af2922;
}
.site-nav ul{
background:#efedee;
padding:0;
margin:0;
}
.site-nav > ul ul{
position:absolute;
}
.site-nav ul li{
background:#ecc019;
list-style:none;
}
.site-nav ul li a{
display:inline-block;
width:100px;
padding:5px 10px;
text-decoration:none;
}
.site-nav ul li:hover > a{
background:rgba(255,255,255,0.6);
}
nav > ul > li{
float:left;
}

Body:
You can use inline-block on the li's, then text-align: center on the parent

.clearfix:after{
    content:"";
    display:block;
    clear:both;
}
.wrapper{
    width:90%;
    margin:0 auto;
}
.site-logo{
    text-align:center;
    padding: 20px 0 10px 0;
}
.site-nav{
    background:#af2922;
}
.site-nav ul{
    background:#efedee;
    padding:0;
    margin:0;
  text-align: center;
}
.site-nav > ul ul{
    position:absolute;
}
.site-nav ul li{
    background:#ecc019;
    list-style:none;
}
.site-nav ul li a{
    display:inline-block;
    width:100px;
    padding:5px 10px;
    text-decoration:none;
}
.site-nav ul li:hover > a{
    background:rgba(255,255,255,0.6);
}
nav > ul > li{
    display: inline-block;
}
.block{
    height:50px;
    background:#ddd;
}

<div class="header">
  <div class="wrapper">
    <div class="site-logo">
      <img src="" alt="" class="logo" width="">
    </div>
    <nav class="site-nav">
      <ul class="clearfix">
        <li><a href="#">Home</a></li><li><a href="#">Projects</a>
          <ul>
            <li class="sub-back"><a href="#">Santa Marta</a></li>
            <li class="sub-back"><a href="#">Barranquilla</a></li>
            <li class="sub-back"><a href="#">La Dorada</a></li>
          </ul>
        </li><li><a href="#">Customers</a></li><li><a href="#">Partners</a></li><li><a href="#">About</a></li><li><a href="#">Contact</a></li>
      </ul>
    </nav>
    <!-- .site-nav -->
    <div class="menu-toggle">
      <div class="hamburger"></div>
    </div>
    <div class="block"></div>
  </div>
  <!-- .wrapper -->
</div>
<!-- .header -->

You could also use display: flex; justify-content: center on the parent and remove the float on the li

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}
.wrapper {
  width: 90%;
  margin: 0 auto;
}
.site-logo {
  text-align: center;
  padding: 20px 0 10px 0;
}
.site-nav {
  background: #af2922;
}
.site-nav ul {
  background: #efedee;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.site-nav > ul ul {
  position: absolute;
}
.site-nav ul li {
  background: #ecc019;
  list-style: none;
}
.site-nav ul li a {
  display: inline-block;
  width: 100px;
  padding: 5px 10px;
  text-decoration: none;
}
.site-nav ul li:hover > a {
  background: rgba(255, 255, 255, 0.6);
}

.block {
  height: 50px;
  background: #ddd;
}

<div class="header">
  <div class="wrapper">
    <div class="site-logo">
      <img src="" alt="" class="logo" width="">
    </div>
    <nav class="site-nav">
      <ul class="clearfix">
        <li><a href="#">Home</a></li>
        <!--
-->
        <li><a href="#">Projects</a>
          <ul>
            <li class="sub-back"><a href="#">Santa Marta</a></li>
            <li class="sub-back"><a href="#">Barranquilla</a></li>
            <li class="sub-back"><a href="#">La Dorada</a></li>
          </ul>
        </li>
        <li><a href="#">Customers</a></li>
        <li><a href="#">Partners</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
    </nav>
    <!-- .site-nav -->
    <div class="menu-toggle">
      <div class="hamburger"></div>
    </div>
    <div class="block"></div>
  </div>
  <!-- .wrapper -->
</div>
<!-- .header -->


问:
Memory leak synchronous reading interrupt transfer data via libUSB
I discovered a memory leak reading data via USB interrupt transfer using libUSB synchronously. My simple user program is not using any dynamic memory allocation itself. Internally libusb makes excessive use of dynamic memory allocation. The communication flow is working as expected. Is there a special function to free any internal dynamic memory after using libusb_interrupt_transfer? Does anyone have an idea what causes the continously increase of memory during runtime?

My protocol implements a two way handshake. Because of this a simple data exchange causes a OUT(request), IN(Ack/Nack), IN(Response) and OUT(Ack/Nack) transfer. The report size is 32 Bytes, the outEndpointAddr is 1, the inEndpointAddr is 129, Here are the relevant code snippets.

```<code>int main (void)
{
    uint32_t devFound = 0;
    uint32_t devErrors = 0;

    ...

    int libUsbErr = 0;
    if(!findSensor(&devFound, &devErrors, &libUsbErr, foundCB))
        printf("finding sensor failed %d\n", libUsbErr);

    if(!openSensor(mySensor, &libUsbErr))
        printf("open sensor failed %d\n", libUsbErr);

    int i = 0;
    while(1)
    {
        printf("[%06d] Int Temp %f C\n",i++, readIntTemper());
        Delay(0.5);
    }
    closeSensor(&mySensor, NULL);

    closeSensorContext();
    return 0;
}

float readIntTemper()
{
    static uint8_t tmp[32];
    static uint8_t response[32];

    ...//Prepare request frame

    int libUsbErr = 0;
    if(!HID_Write(mySensor, tmp, &written, 4000, &libUsbErr))
    {
        printf("write request failed %d\n", libUsbErr);
        return 0;
    }

    //Read Ack / Nack
    if(!HID_Read(mySensor, tmp, &read, 4000, &libUsbErr))
    {
        printf("Read ACK NACK failed %d\n", libUsbErr);
        return 0;
    }

    ...//Test if Ack / Nack

    if(!HID_Read(mySensor, response, &read, 4000, &libUsbErr))
    {
        printf("Read response failed %d\n", libUsbErr);
        return 0;
    }

    ... //Prepare ACK

    if(!HID_Write(mySensor, tmp, &written, 4000, &libUsbErr))
    {
        printf("Ack response failed %d\n", libUsbErr);
        return 0;
    }

    ...

    float* temper = (float*)&response[8];
    return *temper;
}

bool HID_Write(const Sensor* sens, uint8_t* repBuf, int* transferred, uint32_t timeout, int* libUsbErr)
{
    if(sens == NULL || repBuf == NULL || transferred == NULL)
        return returnlibUSBErr(libUsbErr, -1008); ///TODO nice error codes;

    if(!sens->claimed)
        return returnlibUSBErr(libUsbErr, -1012); ///TODO nice error codes;

    int r = libusb_interrupt_transfer(sens->devHandle, sens->outEndpointAddr,
                          repBuf, sens->outRepSize, transferred, timeout);
    if (r < 0)
        return returnlibUSBErr(libUsbErr, r);
    return returnlibUSBErr(libUsbErr, LIB_USB_OK);
}

bool HID_Read(const Sensor* sens, uint8_t* repBuf, int* read, uint32_t timeout, int* libUsbErr)
{
    if(sens == NULL || read == NULL)
        return returnlibUSBErr(libUsbErr, -1008); ///TODO nice error codes;

    if(!sens->claimed)
        return returnlibUSBErr(libUsbErr, -1012); ///TODO nice error codes;

    int r = libusb_interrupt_transfer(sens->devHandle, sens->inEndpointAddr, repBuf,sens->inRepSize, read, timeout);
    if (r < 0)
        return returnlibUSBErr(libUsbErr, r);
    return returnlibUSBErr(libUsbErr, LIB_USB_OK);
}
</code>```

EDIT

If followed this instruction to monitor memory usage:

https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-performance-monitor-to-find-a-user-mode-memory-leak

To find the leak I used UMDH Windows tool like mentioned here:

https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-umdh-to-find-a-user-mode-memory-leak

The problem is that I have to use CVI NI compilter to build my application. I wasn't able to get the symbol table out of this compilter. So my heap dump diff only shows addresses.

```<code>// Each log entry has the following syntax:
//
// + BYTES_DELTA (NEW_BYTES - OLD_BYTES) NEW_COUNT allocs BackTrace TRACEID
// + COUNT_DELTA (NEW_COUNT - OLD_COUNT) BackTrace TRACEID allocations
//     ... stack trace ...
//
// where:
//
//     BYTES_DELTA - increase in bytes between before and after log
//     NEW_BYTES - bytes in after log
//     OLD_BYTES - bytes in before log
//     COUNT_DELTA - increase in allocations between before and after log
//     NEW_COUNT - number of allocations in after log
//     OLD_COUNT - number of allocations in before log
//     TRACEID - decimal index of the stack trace in the trace database
//         (can be used to search for allocation instances in the original
//         UMDH logs).
//

+   80000 ( 80000 -     0)      1 allocs    BackTrace4920B3C
+       1 (     1 -     0)  BackTrace4920B3C    allocations

    ntdll!RtlAllocateHeap+274
    cvirte!LoadExternalModule+291EC
    cvirte!CVIDynamicMemoryInfo+12B6
    cvirte!CVIDynamicMemoryInfo+1528
    cvirte!CVIDynamicMemoryInfo+1AF9
    cvirte!mblen+84D
    cvirte!_CVI_Resource_Acquire+116
    cvirte!malloc+68
    libUSB_HID!???+0 : 41DCE8
    libUSB_HID!???+0 : 4E95C7
    libUSB_HID!???+0 : 4C13BE
    libUSB_HID!???+0 : 4BA09D
    libUSB_HID!???+0 : 4C7ABA
    libUSB_HID!???+0 : 4F92F0
    libUSB_HID!???+0 : 4FB3BD
    libUSB_HID!???+0 : 4FC50E
    libUSB_HID!???+0 : 415C31
    libUSB_HID!???+0 : 408847
    libUSB_HID!???+0 : 402967
    libUSB_HID!???+0 : 41B51E
    libUSB_HID!???+0 : 41A021
    kernel32!BaseThreadInitThunk+E
    ntdll!__RtlUserThreadStart+70
</code>```

I also replaced all free, alloc, calloc and realloc cmds within libUSB with my a own implementation tracking every single memory request. This tracking is not showing any memory leak. The amount of allocated bytes stays constant during runtime as expected. Anyway the UMDH tools shows a heap allocation difference. So I'm completely out of ideas what to test next atm.

答: Sorry guys I ported my program to minGW gcc and everythink is working as expected. It seams that my porting of libusb for CVI compiler is not completely correct. Now I use the standard dll and the memory leak is gone. </p>

Body:
I discovered a memory leak reading data via USB interrupt transfer using libUSB synchronously. My simple user program is not using any dynamic memory allocation itself. Internally libusb makes excessive use of dynamic memory allocation. The communication flow is working as expected. Is there a special function to free any internal dynamic memory after using libusb_interrupt_transfer? Does anyone have an idea what causes the continously increase of memory during runtime?

My protocol implements a two way handshake. Because of this a simple data exchange causes a OUT(request), IN(Ack/Nack), IN(Response) and OUT(Ack/Nack) transfer. The report size is 32 Bytes, the outEndpointAddr is 1, the inEndpointAddr is 129, Here are the relevant code snippets.

int main (void)
{
    uint32_t devFound = 0;
    uint32_t devErrors = 0;

    ...

    int libUsbErr = 0;
    if(!findSensor(&devFound, &devErrors, &libUsbErr, foundCB))
        printf("finding sensor failed %d\n", libUsbErr);

    if(!openSensor(mySensor, &libUsbErr))
        printf("open sensor failed %d\n", libUsbErr);

    int i = 0;
    while(1)
    {
        printf("[%06d] Int Temp %f C\n",i++, readIntTemper());
        Delay(0.5);
    }
    closeSensor(&mySensor, NULL);

    closeSensorContext();
    return 0;
}

float readIntTemper()
{
    static uint8_t tmp[32];
    static uint8_t response[32];

    ...//Prepare request frame

    int libUsbErr = 0;
    if(!HID_Write(mySensor, tmp, &written, 4000, &libUsbErr))
    {
        printf("write request failed %d\n", libUsbErr);
        return 0;
    }

    //Read Ack / Nack
    if(!HID_Read(mySensor, tmp, &read, 4000, &libUsbErr))
    {
        printf("Read ACK NACK failed %d\n", libUsbErr);
        return 0;
    }

    ...//Test if Ack / Nack

    if(!HID_Read(mySensor, response, &read, 4000, &libUsbErr))
    {
        printf("Read response failed %d\n", libUsbErr);
        return 0;
    }

    ... //Prepare ACK

    if(!HID_Write(mySensor, tmp, &written, 4000, &libUsbErr))
    {
        printf("Ack response failed %d\n", libUsbErr);
        return 0;
    }

    ...

    float* temper = (float*)&response[8];
    return *temper;
}

bool HID_Write(const Sensor* sens, uint8_t* repBuf, int* transferred, uint32_t timeout, int* libUsbErr)
{
    if(sens == NULL || repBuf == NULL || transferred == NULL)
        return returnlibUSBErr(libUsbErr, -1008); ///TODO nice error codes;

    if(!sens->claimed)
        return returnlibUSBErr(libUsbErr, -1012); ///TODO nice error codes;

    int r = libusb_interrupt_transfer(sens->devHandle, sens->outEndpointAddr,
                          repBuf, sens->outRepSize, transferred, timeout);
    if (r < 0)
        return returnlibUSBErr(libUsbErr, r);
    return returnlibUSBErr(libUsbErr, LIB_USB_OK);
}

bool HID_Read(const Sensor* sens, uint8_t* repBuf, int* read, uint32_t timeout, int* libUsbErr)
{
    if(sens == NULL || read == NULL)
        return returnlibUSBErr(libUsbErr, -1008); ///TODO nice error codes;

    if(!sens->claimed)
        return returnlibUSBErr(libUsbErr, -1012); ///TODO nice error codes;

    int r = libusb_interrupt_transfer(sens->devHandle, sens->inEndpointAddr, repBuf,sens->inRepSize, read, timeout);
    if (r < 0)
        return returnlibUSBErr(libUsbErr, r);
    return returnlibUSBErr(libUsbErr, LIB_USB_OK);
}

EDIT

If followed this instruction to monitor memory usage:

https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-performance-monitor-to-find-a-user-mode-memory-leak

To find the leak I used UMDH Windows tool like mentioned here:

https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/using-umdh-to-find-a-user-mode-memory-leak

The problem is that I have to use CVI NI compilter to build my application. I wasn't able to get the symbol table out of this compilter. So my heap dump diff only shows addresses.

// Each log entry has the following syntax:
//
// + BYTES_DELTA (NEW_BYTES - OLD_BYTES) NEW_COUNT allocs BackTrace TRACEID
// + COUNT_DELTA (NEW_COUNT - OLD_COUNT) BackTrace TRACEID allocations
//     ... stack trace ...
//
// where:
//
//     BYTES_DELTA - increase in bytes between before and after log
//     NEW_BYTES - bytes in after log
//     OLD_BYTES - bytes in before log
//     COUNT_DELTA - increase in allocations between before and after log
//     NEW_COUNT - number of allocations in after log
//     OLD_COUNT - number of allocations in before log
//     TRACEID - decimal index of the stack trace in the trace database
//         (can be used to search for allocation instances in the original
//         UMDH logs).
//

+   80000 ( 80000 -     0)      1 allocs    BackTrace4920B3C
+       1 (     1 -     0)  BackTrace4920B3C    allocations

    ntdll!RtlAllocateHeap+274
    cvirte!LoadExternalModule+291EC
    cvirte!CVIDynamicMemoryInfo+12B6
    cvirte!CVIDynamicMemoryInfo+1528
    cvirte!CVIDynamicMemoryInfo+1AF9
    cvirte!mblen+84D
    cvirte!_CVI_Resource_Acquire+116
    cvirte!malloc+68
    libUSB_HID!???+0 : 41DCE8
    libUSB_HID!???+0 : 4E95C7
    libUSB_HID!???+0 : 4C13BE
    libUSB_HID!???+0 : 4BA09D
    libUSB_HID!???+0 : 4C7ABA
    libUSB_HID!???+0 : 4F92F0
    libUSB_HID!???+0 : 4FB3BD
    libUSB_HID!???+0 : 4FC50E
    libUSB_HID!???+0 : 415C31
    libUSB_HID!???+0 : 408847
    libUSB_HID!???+0 : 402967
    libUSB_HID!???+0 : 41B51E
    libUSB_HID!???+0 : 41A021
    kernel32!BaseThreadInitThunk+E
    ntdll!__RtlUserThreadStart+70

I also replaced all free, alloc, calloc and realloc cmds within libUSB with my a own implementation tracking every single memory request. This tracking is not showing any memory leak. The amount of allocated bytes stays constant during runtime as expected. Anyway the UMDH tools shows a heap allocation difference. So I'm completely out of ideas what to test next atm.


问:
loopback custom query did not give response
my loopback custom query cannot give response after some time. below is my code.

```<code>var ds = tbljourney.dataSource;
        ds.connector.query("select * from user where  email='" + data.email + "'"
        , function (err, user) {
                user = user[0];

            console.log("user", user);
            if (err) {
                console.log(err);

            }
            else if (user) {
   }
  });
</code>```

some time it give a response but after 50 or 60 attemps its stuck

答:
try to run your queries using the method below. Here's I'm connecting to an Oracle database. A lot of concat gets messy.</p>

```<code>Model.remoteMethod(data,cb){
  var app = require('../server');
  var ds = app.datasources.newDatasource;

  var sql = "SELECT * FROM TABLE WHERE SITE_ID=:param1 AND "+
    "(DESTINATION=:param2 OR USERNAME=:param2 )";
  var params = [param1, param2];
  ds.connector.execute(sql, params, function(err, result){
    if (err) console.error("error: " + err);
    cb(err, result);
  });
}
</code>```

Body:
my loopback custom query cannot give response after some time. below is my code.

var ds = tbljourney.dataSource;
        ds.connector.query("select * from user where  email='" + data.email + "'"
        , function (err, user) {
                user = user[0];

            console.log("user", user);
            if (err) {
                console.log(err);

            }
            else if (user) {
   }
  });

some time it give a response but after 50 or 60 attemps its stuck

Body:
try to run your queries using the method below. Here's I'm connecting to an Oracle database. A lot of concat gets messy.

Model.remoteMethod(data,cb){
  var app = require('../server');
  var ds = app.datasources.newDatasource;

  var sql = "SELECT * FROM TABLE WHERE SITE_ID=:param1 AND "+
    "(DESTINATION=:param2 OR USERNAME=:param2 )";
  var params = [param1, param2];
  ds.connector.execute(sql, params, function(err, result){
    if (err) console.error("error: " + err);
    cb(err, result);
  });
}


问:
How to capitalize every letter in an Android EditText?
I have an array of editTexts which I make like this:

```<code>        inputs[i] = new EditText(this);
        inputs[i].setWidth(376);
        inputs[i].setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
        tFields.addView(inputs[i]);
</code>```

I want every character to be capitalized.  Right now, the first letter of the first word is lowercase, then all the characters afterwords are upper case.  I can take what the user inputs after they are done and convert that to uppercase, but that's not really what I'm going for.  Is there a way to get these fields to behave the way I want them to?

答:
For some reason adding the xml did not work on my device.

I found that a Text Filter works for to uppercase, like this

```<code>    EditText editText = (EditText) findViewById(R.id.editTextId);

    InputFilter toUpperCaseFilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {

            StringBuilder stringBuilder = new StringBuilder();

            for (int i = start; i < end; i++) {
                Character character = source.charAt(i);
                character = Character.toUpperCase(character); // THIS IS UPPER CASING
                stringBuilder.append(character);

            }
            return stringBuilder.toString();
        }

    };

    editText.setFilters(new InputFilter[] { toUpperCaseFilter });
</code>```

Body:
I have an array of editTexts which I make like this:

        inputs[i] = new EditText(this);
        inputs[i].setWidth(376);
        inputs[i].setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
        tFields.addView(inputs[i]);

I want every character to be capitalized.  Right now, the first letter of the first word is lowercase, then all the characters afterwords are upper case.  I can take what the user inputs after they are done and convert that to uppercase, but that's not really what I'm going for.  Is there a way to get these fields to behave the way I want them to?

Body:
For some reason adding the xml did not work on my device.

I found that a Text Filter works for to uppercase, like this

    EditText editText = (EditText) findViewById(R.id.editTextId);

    InputFilter toUpperCaseFilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {

            StringBuilder stringBuilder = new StringBuilder();

            for (int i = start; i < end; i++) {
                Character character = source.charAt(i);
                character = Character.toUpperCase(character); // THIS IS UPPER CASING
                stringBuilder.append(character);

            }
            return stringBuilder.toString();
        }

    };

    editText.setFilters(new InputFilter[] { toUpperCaseFilter });


问:
How to schedule a random timing (every random minutes) event
I'm developing an Android App, I'm trying to manage a Vibration event.
I need to schedule it every random minutes when a switch is checked. I have been using this code:

```<code>int delay3 = (60 + new Random().nextInt(60)) * 1000;

timer3.schedule(timerTask3, 0, delay3);
</code>```

but the timer doesn't change delay3 until the switch is unchecked and checked again. Is there a way to schedule the event at random timing i.e. delay3 should change every time the task is running without unchecking the switch?

Thank you.

答:
Schedule the task to run after a random delay once. Inside the task, after the desired process, reschedule it after a random delay.

Example:

```<code>Random random = new Random();
Timer timer = new Timer();
timer.schedule(new MyTimerTask(timer, random), random.nextInt(10000));
</code>```

with:

```<code>private static class MyTimerTask extends TimerTask {
    private final Timer timer;
    private final Random random;

    public MyTimerTask(Timer timer, Random random) {
        this.timer = timer;
        this.random = random;
    }

    @Override
    public void run() {
        System.out.println("TEST");
        timer.schedule(new MyTimerTask(timer, random), random.nextInt(10000));
    }
}
</code>```

Body:
I'm developing an Android App, I'm trying to manage a Vibration event.
I need to schedule it every random minutes when a switch is checked. I have been using this code:

int delay3 = (60 + new Random().nextInt(60)) * 1000;

timer3.schedule(timerTask3, 0, delay3);

but the timer doesn't change delay3 until the switch is unchecked and checked again. Is there a way to schedule the event at random timing i.e. delay3 should change every time the task is running without unchecking the switch?

Thank you.

Body:
Schedule the task to run after a random delay once. Inside the task, after the desired process, reschedule it after a random delay.

Example:

Random random = new Random();
Timer timer = new Timer();
timer.schedule(new MyTimerTask(timer, random), random.nextInt(10000));

with:

private static class MyTimerTask extends TimerTask {
    private final Timer timer;
    private final Random random;

    public MyTimerTask(Timer timer, Random random) {
        this.timer = timer;
        this.random = random;
    }

    @Override
    public void run() {
        System.out.println("TEST");
        timer.schedule(new MyTimerTask(timer, random), random.nextInt(10000));
    }
}


问:
Jquery Fade in menu on click
I'm trying to achieve a fade in effect when I click on an icon which toggles a 100% height and width menu and a fade out when I click the X. However I'm not sure how to achieve this effect. The only way I've managed to make it work is by adding a top, bottom, left and right value but I do not want it to slide from a side but rather appear as an opacity change from 0 to 1 with a transition. I've set the top value to work so you can see the menu but it is not what I'm looking for.

HTML:

```<code><div class="o1">
    <div class="o2"></div>
</div>

<div class="nav">

<div class="out">
<div class="x"></div>
<div class="x2"></div>
</div>

<ul>
    <li class="lione">About Me</li>
    <li class="litwo">My Portfolio</li>
    <li class="lithree">My Skills</li>
    <li class="lifour">Contact Me</li>
</ul>
</div>
</code>```

CSS:

```<code>.nav {
height: 100vh;
width: 100vw;
position: absolute;
top: -100%;
/left: -100%;
/right: -100%;
/bottom: -100%;
z-index: 1;
background-color: #3a3a3a;
transition: 1s all ease;
opacity: 0;
}

.nav ul {
list-style: none;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

.nav li {
text-align: center;
color: #81CFE0;
padding: 10px;
font-family: 'Quicksand';
font-weight: 100;
}

.lione {
border: 1px solid;
border-right: none;
border-bottom: none;
}

.litwo {
border: 1px solid;
border-top: none;
border-right: none;
border-bottom: none;
}

.lithree {
border: 1px solid;
border-top: none;
border-left: none;
border-bottom: none;
}

.lifour {
border: 1px solid;
border-top: none;
border-left: none;
}

.out {
height: 4vh;
margin-left: 98%;
margin-right: 0.5%;
transition: 1s all ease;
}

.x {
height: 1px;
background-color: #81cfe0;
width: 20px;
transform: rotate(45deg);
position: absolute;
top: 15px;
right: 10px;
}

.x2 {
height: 1px;
background-color: #81cfe0;
width: 20px;
transform: rotate(-45deg);
position: absolute;
right: 10px;
top: 15px;
}

.o1 {
height: 20px;
width: 20px;
border-radius: 100%;
border: 1px solid #81cfe0;
position: absolute;
top: 1%;
right: 1%;
}

.open {
opacity: 1;
top: 0;
}

.o2 {
height: 13px;
width: 13px;
border-radius: 100%;
border: 1px solid #3a3a3a;
position: absolute;
left: 51%;
top: 51%;
transform: translate(-50%, -50%);
transition: 1s all ease;
}
</code>```

JS:

```<code>$(function () {
$('.o1').click(function() {
   $('.nav').toggleClass('open');
});

$('.out').click(function() {
   $('.open').toggleClass('open');
});
});
</code>```

https://jsfiddle.net/u03ofj16/

答:
I think you should use built in jquery fadeIn, fadeOut

See updated fiddle - https://jsfiddle.net/arvinddhakad/u03ofj16/3/

```<code>$(function () {
$('.o1').click(function() {
       $('.nav').fadeIn(1000);
    });

    $('.out').click(function() {
       $('.nav').fadeOut(1000);
    });
});
</code>```

Title: Jquery Fade in menu on click

Body:
I'm trying to achieve a fade in effect when I click on an icon which toggles a 100% height and width menu and a fade out when I click the X. However I'm not sure how to achieve this effect. The only way I've managed to make it work is by adding a top, bottom, left and right value but I do not want it to slide from a side but rather appear as an opacity change from 0 to 1 with a transition. I've set the top value to work so you can see the menu but it is not what I'm looking for.

HTML:

About Me

My Portfolio

My Skills

Contact Me

CSS:

.nav {
height: 100vh;
width: 100vw;
position: absolute;
top: -100%;
/left: -100%;
/right: -100%;
/bottom: -100%;
z-index: 1;
background-color: #3a3a3a;
transition: 1s all ease;
opacity: 0;
}

.nav ul {
list-style: none;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

.nav li {
text-align: center;
color: #81CFE0;
padding: 10px;
font-family: 'Quicksand';
font-weight: 100;
}

.lione {
border: 1px solid;
border-right: none;
border-bottom: none;
}

.litwo {
border: 1px solid;
border-top: none;
border-right: none;
border-bottom: none;
}

.lithree {
border: 1px solid;
border-top: none;
border-left: none;
border-bottom: none;
}

.lifour {
border: 1px solid;
border-top: none;
border-left: none;
}

.out {
height: 4vh;
margin-left: 98%;
margin-right: 0.5%;
transition: 1s all ease;
}

.x {
height: 1px;
background-color: #81cfe0;
width: 20px;
transform: rotate(45deg);
position: absolute;
top: 15px;
right: 10px;
}

.x2 {
height: 1px;
background-color: #81cfe0;
width: 20px;
transform: rotate(-45deg);
position: absolute;
right: 10px;
top: 15px;
}

.o1 {
height: 20px;
width: 20px;
border-radius: 100%;
border: 1px solid #81cfe0;
position: absolute;
top: 1%;
right: 1%;
}

.open {
opacity: 1;
top: 0;
}

.o2 {
height: 13px;
width: 13px;
border-radius: 100%;
border: 1px solid #3a3a3a;
position: absolute;
left: 51%;
top: 51%;
transform: translate(-50%, -50%);
transition: 1s all ease;
}

JS:

$(function () {
$('.o1').click(function() {
   $('.nav').toggleClass('open');
});

$('.out').click(function() {
   $('.open').toggleClass('open');
});
});

https://jsfiddle.net/u03ofj16/

Body:
I think you should use built in jquery fadeIn, fadeOut

See updated fiddle - https://jsfiddle.net/arvinddhakad/u03ofj16/3/

$(function () {
$('.o1').click(function() {
       $('.nav').fadeIn(1000);
    });

    $('.out').click(function() {
       $('.nav').fadeOut(1000);
    });
});


问:
can't build android project it shows error
project gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

App Gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.arun4fms.efix"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.chabbal:slidingdotsplash:1.0.2'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Error:A problem occurred configuring root project 'webapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.0-alpha3.
       Searched in the following locations:
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
       Required by:
           project :

答:
As already answered here:

Google have new maven repo, so it could be the reason.

https://android-developers.googleblog.com/2017/05/android-studio-3-0-canary1.html

section Google's Maven Repository

https://developer.android.com/studio/preview/features/new-android-plugin-migration.html
  https://developer.android.com/studio/build/dependencies.html#google-maven

Add Google’s Maven Repository to the buildscript repositories section to fix it like @KG87 did here.

```<code>buildscript {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" } // Add this line to fix it
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        ...
    }
}
</code>```

As explained here:

The repositories in the buildScript block are used to fetch the
  dependencies of your buildScript dependencies. These are the
  dependencies that are put on the classpath of your build and that you
  can refer to from your build file. For instance, extra plugins that
  exist on the internet.

The repositories on the root level are used to fetch the dependencies
  that your project depends on. So all the dependencies you need to
  compile your project.

And here:

The buildScript block determines which plugins, task classes, and
  other classes are available for use in the rest of the build script.
  Without a buildScript block, you can use everything that ships with
  Gradle out-of-the-box. If you additionally want to use third-party
  plugins, task classes, or other classes (in the build script!), you
  have to specify the corresponding dependencies in the buildScript
  block.

As announced here:

The Android Gradle Plugin 3.0.0-alpha3 was also released through
  maven.google.com.

So, try to fix it by adding Google’s Maven Repository.

```<code>buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
</code>```

Also add the repository here for other dependencies like the support libraries like this:

Make sure that the repositories section includes a maven section with
  the "https://maven.google.com" endpoint. For example:

```<code>allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
</code>```

The difference is explained here

The "buildscript" block only controls dependencies for the buildscript
  process itself, not for the application code, which the top-level
  "dependencies" block controls.

For instance, you could define dependencies in "buildscript/classpath"
  that represent Gradle plugins used in the build process. Those plugins
  would not be referenced as dependencies for the application code.

As commented here by @lugegege, this version doesn't exist in Bintray JCenter:

com.android.tools.build.gradle
  latest version is 2.5.0-alpha-preview-02, there is no 3.0.0-alpha3

Body:
project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App Gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.arun4fms.efix"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.chabbal:slidingdotsplash:1.0.2'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Error:A problem occurred configuring root project 'webapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.0-alpha3.
       Searched in the following locations:
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
       Required by:
           project :

Body:
As already answered here:

Google have new maven repo, so it could be the reason.

https://android-developers.googleblog.com/2017/05/android-studio-3-0-canary1.html

section Google's Maven Repository

https://developer.android.com/studio/preview/features/new-android-plugin-migration.html
  https://developer.android.com/studio/build/dependencies.html#google-maven

Add Google’s Maven Repository to the buildscript repositories section to fix it like @KG87 did here.

buildscript {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" } // Add this line to fix it
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        ...
    }
}

As explained here:

The repositories in the buildScript block are used to fetch the
  dependencies of your buildScript dependencies. These are the
  dependencies that are put on the classpath of your build and that you
  can refer to from your build file. For instance, extra plugins that
  exist on the internet.

The repositories on the root level are used to fetch the dependencies
  that your project depends on. So all the dependencies you need to
  compile your project.

And here:

The buildScript block determines which plugins, task classes, and
  other classes are available for use in the rest of the build script.
  Without a buildScript block, you can use everything that ships with
  Gradle out-of-the-box. If you additionally want to use third-party
  plugins, task classes, or other classes (in the build script!), you
  have to specify the corresponding dependencies in the buildScript
  block.

As announced here:

The Android Gradle Plugin 3.0.0-alpha3 was also released through
  maven.google.com.

So, try to fix it by adding Google’s Maven Repository.

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Also add the repository here for other dependencies like the support libraries like this:

Make sure that the repositories section includes a maven section with
  the "https://maven.google.com" endpoint. For example:

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

The difference is explained here

The "buildscript" block only controls dependencies for the buildscript
  process itself, not for the application code, which the top-level
  "dependencies" block controls.

For instance, you could define dependencies in "buildscript/classpath"
  that represent Gradle plugins used in the build process. Those plugins
  would not be referenced as dependencies for the application code.

As commented here by @lugegege, this version doesn't exist in Bintray JCenter:

com.android.tools.build.gradle
  latest version is 2.5.0-alpha-preview-02, there is no 3.0.0-alpha3


问:
Set UILabel Text at Completion of CloudKit Asyncronous Operation in Swift
I'm new to Swift, and asynchronous code in general, so tell me if this is way off. Basically I want to:

Open the App

That triggers a read of CloudKit records

Once the read is complete a UILabel will display the number of records retrieved

This clearly isn't useful in itself, but as a principle it will help me to understand the asynchronous code operation, and how to trigger actions on their completion.

```<code>// In ViewController Swift file:

class ViewController: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        readDatabase()
    }
    @IBOutlet weak var myLabel: UILabel!
}

let VC=ViewController()

//In Another Swift file:

func readDatabase() {
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "myRecord", predicate: predicate)
    let container = CKContainer.default()
    let privateDB = container.privateCloudDatabase

    privateDB.perform(query, inZoneWith:nil) { (allRecs, err) in
        VC.myLabel.text = ("\(allRecs?.count) records retreived")

    /*
    ERROR OCCURS IN LINE ABOVE:
       CONSOLE: fatal error: unexpectedly found nil while unwrapping an Optional value
       BY CODE LINE: Thread 8:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    */

    }
}
</code>```

I'm able to set the text field from within the viewDidLoad function, so why not from a function called within that function?

A few other things I've tried:

Use async dispatch to put it on thread 1

Implement a var with within the ViewController class, with a didSet that sets the text, set the var to the desired value in the privateDB.perform code to trigger the change

These both create the same problem as above.

Yes, I know there isn't any error handling in .perform, and yes there are records. If I trigger the setting of the UILabel text to the record count manually a few seconds after the view has loaded, it works fine.

So the question is...
How do I use the completion of the database read as a trigger to load attributes of the records to the view?

Thanks

Edit

What actually happened here was that VC was created globally, but never presented - since loadView was never called for it, myLabel didn't exist and, being a force unwrapped property, caused a crash when it was referenced

答:
The problem is with this line: let VC=ViewController(). Here you instantiate a new instance of your ViewController class and try to set the label on that newly created instance. However, you would want to set the label on your viewController instance that is currently displayed.

Just change this line VC.myLabel.text = ("\(allRecs?.count) records retreived") to self.myLabel.text = ("\(allRecs?.count) records retreived") and it should work fine.

Body:
I'm new to Swift, and asynchronous code in general, so tell me if this is way off. Basically I want to:

Open the App

That triggers a read of CloudKit records

Once the read is complete a UILabel will display the number of records retrieved

This clearly isn't useful in itself, but as a principle it will help me to understand the asynchronous code operation, and how to trigger actions on their completion.

// In ViewController Swift file:

class ViewController: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        readDatabase()
    }
    @IBOutlet weak var myLabel: UILabel!
}

let VC=ViewController()

//In Another Swift file:

func readDatabase() {
    let predicate = NSPredicate(value: true)
    let query = CKQuery(recordType: "myRecord", predicate: predicate)
    let container = CKContainer.default()
    let privateDB = container.privateCloudDatabase

    privateDB.perform(query, inZoneWith:nil) { (allRecs, err) in
        VC.myLabel.text = ("\(allRecs?.count) records retreived")

    /*
    ERROR OCCURS IN LINE ABOVE:
       CONSOLE: fatal error: unexpectedly found nil while unwrapping an Optional value
       BY CODE LINE: Thread 8:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    */

    }
}

I'm able to set the text field from within the viewDidLoad function, so why not from a function called within that function?

A few other things I've tried:

Use async dispatch to put it on thread 1

Implement a var with within the ViewController class, with a didSet that sets the text, set the var to the desired value in the privateDB.perform code to trigger the change

These both create the same problem as above.

Yes, I know there isn't any error handling in .perform, and yes there are records. If I trigger the setting of the UILabel text to the record count manually a few seconds after the view has loaded, it works fine.

So the question is...
How do I use the completion of the database read as a trigger to load attributes of the records to the view?

Thanks

Edit

What actually happened here was that VC was created globally, but never presented - since loadView was never called for it, myLabel didn't exist and, being a force unwrapped property, caused a crash when it was referenced


问:
request.querystring not found in static method
I have static method in which I want to extract querystring value of the request. But it gives me null value when i am calling it from webmethod. Below is the some code

```<code>public static int GetLatestAssetId()
    {
        int itemid=0;
        if (HttpContext.Current.Request.QueryString["itemId"] != null)
        itemid = Convert.ToInt32(HttpContext.Current.Request.QueryString["itemId"]);
        return itemid;
    }

[WebMethod]

        public static string GetContactData()
        {

            GetLatestAssetId();
            return "Success"
        }
</code>```

I am calling this webmethod from the ajax call.It works fine in page load but not in static method. How do I use this in static method. Please assist.

答:
Simple

```<code>    public static int GetQueryStringData()
    {
     if (HttpContext.Current.Request.QueryString["UserId"] != null)
      {
        return Convert.ToInt32(HttpContext.Current.Request.QueryString["UserId"]);
      }
     else
      {
        return 0;
      }
    }

    [WebMethod]
    public static string GetData()
    {
        int x = GetQueryStringData();
        if (x != 0)
            return "Success";
        else
            return "not success";
    }
</code>```

Body:
I have static method in which I want to extract querystring value of the request. But it gives me null value when i am calling it from webmethod. Below is the some code

public static int GetLatestAssetId()
    {
        int itemid=0;
        if (HttpContext.Current.Request.QueryString["itemId"] != null)
        itemid = Convert.ToInt32(HttpContext.Current.Request.QueryString["itemId"]);
        return itemid;
    }

[WebMethod]

        public static string GetContactData()
        {

            GetLatestAssetId();
            return "Success"
        }

I am calling this webmethod from the ajax call.It works fine in page load but not in static method. How do I use this in static method. Please assist.

Body:
Simple

    public static int GetQueryStringData()
    {
     if (HttpContext.Current.Request.QueryString["UserId"] != null)
      {
        return Convert.ToInt32(HttpContext.Current.Request.QueryString["UserId"]);
      }
     else
      {
        return 0;
      }
    }

    [WebMethod]
    public static string GetData()
    {
        int x = GetQueryStringData();
        if (x != 0)
            return "Success";
        else
            return "not success";
    }


问:
How to have different page numbering types in MS Word?
Trying to figure out how to get two different page numbering styles into the same document in MS Word.

The section highlighted in yellow is what I am trying to replicate.

As you can see, there are pages that are using Roman numerals, and pages using Indo-Arabic numbers.

Currently using MS word 2013.

答:
For the initial pages, set the page numbers as roman numerals.
When you want the actual numbers to start, go to:
Page Layout > Breaks > Section Breaks (Next Page)
Then in the new section, set your page numbering to 1, 2, 3, ...</p>


问:
Is it possible to transfer data to SQL Server from an unconventional database
My company has a SQL Server database which they would like to populate with data from a hierarchical database (as opposed to relational). I have already written a .net application to map its schema to a relational database and have successfully done that. However my problem is that the tech being used here is so old that I see no obvious way of data transfer.

However, I have certain ideas about how I can do this. This involves having to write file scans in my unconventional database and dump out files as csv. Then do a bulk upload into SQL Server. I do not appreciate this as there is the element of invalid data involved which terminates the bulk upload quite so often.

I was hoping to explore options around service broker. I was hoping to dump out live transactions where a record has changed in my database and then this can somehow be picked up?

Secondly I was also hoping to use something which if I dump out live or changed records in a file (I can format the file to whatever format is needed), can something suck it into SQL Server?

Any help would be greatly appreciated.

Regards,

Waqar

答:
Service Broker is a very powerful queue/messaging management system. I am not sure why you want to use it for this.

You can set up an SSIS job that keeps checking a folder for csv files and when detects a new one it reads it into SQL Server and then zips it and archives it somewhere else. This is very common. SSIS can then either process the data (its a wonderful ETL tool) or  invoke procedures in SQL Server to process the data. SSIS is very fast and is rarely overwhelmed so why would you use Service Broker?

If its IMS (mainframe) type data you have to convert it to flat tables and then as csv type text tables for SQL Server to read.

SQL server is very good at processing XML and, as of 2016, JSON shaped data, so if that is your data type you can directly import into SQL Server.