问:
How to import css from node_modules using webpack 2
I want to import a css file (lightgallery.css) from node_modules to public_html. My project has this structure

```<code>root
    app/
        main.jsx
        ...
    public_html/
        index.html
        ...
    node_modules/
        lightgallery/
        ...
    webpacj.config.js
</code>```

webpack.config.js

```<code>let config = {

    entry: {
        main: './app/main.jsx'
    },

    output: {
        path: path.resolve(__dirname, 'public_html')
    },

    resolve: {
        extensions: ['.js', '.json', '.css'],
        alias: {
          "lightgallery-css": path.resolve(__dirname, "./node_modules/lightgallery/src/css/lightgallery.css")
        }
    },

    module: {

        rules: [

        {
            test: /\.css$/,
            // include: /node_modules/,
            use:  ExtractTextPlugin.extract({
                fallback: "style-loader",
                use: "css-loader"
            })
        },

        {
            test: /\.(gif|png|jpg|jpeg|svg)$/,
            use: {
                loader: 'url-loader',
                options: {
                    limit: 25000,
                },
            },
        },

        {
            test: /\.(ttf|eot|woff|woff2)$/,
            loader: 'file-loader',
            options: {
                limit: 50000,
                name: 'fonts/[name].[ext]',
            },
        },

        ]
    },

    plugins: [

        new HtmlWebpackPlugin({
            template: './app/index.html'
        }),

        new  ExtractTextPlugin(path.resolve(__dirname, 'public_html') + '[name].bundle.css'),
    ]

}

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

I tried to load the css in .jsx file in this way

```<code>import 'lightgallery/src/css/lightgallery.css'
</code>```

but I can't find *.bundle.css in public_html (I get no errors after compiling my app)

What I wrong?

EDIT2:
The webpack's list of compiled files

```<code>Version: webpack 2.6.1
Time: 11314ms
                Asset       Size  Chunks                    Chunk Names
                14.js      11 kB      14  [emitted]         CompaniesArchived
         fonts/lg.eot    4.02 kB          [emitted]
        fonts/lg.woff    3.96 kB          [emitted]
                 0.js     354 kB       0  [emitted]  [big]  ProjectActivitiesPagination
                 1.js     194 kB       1  [emitted]         ProjectActivitiesShared
                 2.js    13.5 kB       2  [emitted]
                 3.js    14.1 kB       3  [emitted]
                 4.js    32.9 kB       4  [emitted]         Account
                 5.js    36.2 kB       5  [emitted]         Project
                 6.js    36.2 kB       6  [emitted]         MyProject
                 7.js    34.7 kB       7  [emitted]         Customer
                 8.js    33.5 kB       8  [emitted]         Company
                 9.js    20.7 kB       9  [emitted]         ProjectsArchived
                10.js    20.7 kB      10  [emitted]         MyProjectsArchived
                11.js    14.2 kB      11  [emitted]         CustomersArchived
                12.js    22.3 kB      12  [emitted]         Projects
                13.js    7.85 kB      13  [emitted]         PasswordChange
         fonts/lg.ttf    3.88 kB          [emitted]
                15.js    9.26 kB      15  [emitted]         Signup
                16.js    27.8 kB      16  [emitted]         AccountUpgrade
                17.js    6.27 kB      17  [emitted]         Login
                18.js    4.29 kB      18  [emitted]         AccountActivation
                19.js    3.08 kB      19  [emitted]         Search
                20.js    5.56 kB      20  [emitted]         ProjectsWithDeadline
                21.js    4.12 kB      21  [emitted]         ProjectsWithActivitiesToComplete
                22.js    5.63 kB      22  [emitted]         ProjectsForViewer
                23.js    3.41 kB      23  [emitted]         PasswordReset
                24.js     6.9 kB      24  [emitted]         MyProjects
                25.js    1.36 kB      25  [emitted]         Logout
                26.js    7.82 kB      26  [emitted]         Customers
              main.js    1.06 MB      27  [emitted]  [big]  main
            vendor.js    2.05 MB      28  [emitted]  [big]  vendor
           index.html    2.66 kB          [emitted]
nls/it/translation.js    7.88 kB          [emitted]
           nls/nls.js  182 bytes          [emitted]
</code>```

答:
Open the project in editor like Visual Studio Code, locate the file

.angular-cli.json

under the apps configuration array, add styles array.

```<code>"apps": [{
        "root": "src",
        "outDir": "dist",
        "assets": [
            "assets",
            "favicon.ico"
        ],
        "index": "index.html",
        "main": "main.ts",
        "polyfills": "polyfills.ts",
        "test": "test.ts",
        "tsconfig": "tsconfig.app.json",
        "testTsconfig": "tsconfig.spec.json",
        "prefix": "app",
        "styles": [
            "../node_modules/bootstrap/dist/css/bootstrap.css",
            "styles.css"
        ],
        "scripts": [],
</code>```

Body:
I want to import a css file (lightgallery.css) from node_modules to public_html. My project has this structure

root
    app/
        main.jsx
        ...
    public_html/
        index.html
        ...
    node_modules/
        lightgallery/
        ...
    webpacj.config.js

webpack.config.js

let config = {

    entry: {
        main: './app/main.jsx'
    },

    output: {
        path: path.resolve(__dirname, 'public_html')
    },

    resolve: {
        extensions: ['.js', '.json', '.css'],
        alias: {
          "lightgallery-css": path.resolve(__dirname, "./node_modules/lightgallery/src/css/lightgallery.css")
        }
    },

    module: {

        rules: [

        {
            test: /\.css$/,
            // include: /node_modules/,
            use:  ExtractTextPlugin.extract({
                fallback: "style-loader",
                use: "css-loader"
            })
        },

        {
            test: /\.(gif|png|jpg|jpeg|svg)$/,
            use: {
                loader: 'url-loader',
                options: {
                    limit: 25000,
                },
            },
        },

        {
            test: /\.(ttf|eot|woff|woff2)$/,
            loader: 'file-loader',
            options: {
                limit: 50000,
                name: 'fonts/[name].[ext]',
            },
        },

        ]
    },

    plugins: [

        new HtmlWebpackPlugin({
            template: './app/index.html'
        }),

        new  ExtractTextPlugin(path.resolve(__dirname, 'public_html') + '[name].bundle.css'),
    ]

}

module.exports = config;

I tried to load the css in .jsx file in this way

import 'lightgallery/src/css/lightgallery.css'

but I can't find *.bundle.css in public_html (I get no errors after compiling my app)

What I wrong?

EDIT2:
The webpack's list of compiled files

Version: webpack 2.6.1
Time: 11314ms
                Asset       Size  Chunks                    Chunk Names
                14.js      11 kB      14  [emitted]         CompaniesArchived
         fonts/lg.eot    4.02 kB          [emitted]
        fonts/lg.woff    3.96 kB          [emitted]
                 0.js     354 kB       0  [emitted]  [big]  ProjectActivitiesPagination
                 1.js     194 kB       1  [emitted]         ProjectActivitiesShared
                 2.js    13.5 kB       2  [emitted]
                 3.js    14.1 kB       3  [emitted]
                 4.js    32.9 kB       4  [emitted]         Account
                 5.js    36.2 kB       5  [emitted]         Project
                 6.js    36.2 kB       6  [emitted]         MyProject
                 7.js    34.7 kB       7  [emitted]         Customer
                 8.js    33.5 kB       8  [emitted]         Company
                 9.js    20.7 kB       9  [emitted]         ProjectsArchived
                10.js    20.7 kB      10  [emitted]         MyProjectsArchived
                11.js    14.2 kB      11  [emitted]         CustomersArchived
                12.js    22.3 kB      12  [emitted]         Projects
                13.js    7.85 kB      13  [emitted]         PasswordChange
         fonts/lg.ttf    3.88 kB          [emitted]
                15.js    9.26 kB      15  [emitted]         Signup
                16.js    27.8 kB      16  [emitted]         AccountUpgrade
                17.js    6.27 kB      17  [emitted]         Login
                18.js    4.29 kB      18  [emitted]         AccountActivation
                19.js    3.08 kB      19  [emitted]         Search
                20.js    5.56 kB      20  [emitted]         ProjectsWithDeadline
                21.js    4.12 kB      21  [emitted]         ProjectsWithActivitiesToComplete
                22.js    5.63 kB      22  [emitted]         ProjectsForViewer
                23.js    3.41 kB      23  [emitted]         PasswordReset
                24.js     6.9 kB      24  [emitted]         MyProjects
                25.js    1.36 kB      25  [emitted]         Logout
                26.js    7.82 kB      26  [emitted]         Customers
              main.js    1.06 MB      27  [emitted]  [big]  main
            vendor.js    2.05 MB      28  [emitted]  [big]  vendor
           index.html    2.66 kB          [emitted]
nls/it/translation.js    7.88 kB          [emitted]
           nls/nls.js  182 bytes          [emitted]

Body:
Open the project in editor like Visual Studio Code, locate the file

.angular-cli.json

under the apps configuration array, add styles array.

"apps": [{
        "root": "src",
        "outDir": "dist",
        "assets": [
            "assets",
            "favicon.ico"
        ],
        "index": "index.html",
        "main": "main.ts",
        "polyfills": "polyfills.ts",
        "test": "test.ts",
        "tsconfig": "tsconfig.app.json",
        "testTsconfig": "tsconfig.spec.json",
        "prefix": "app",
        "styles": [
            "../node_modules/bootstrap/dist/css/bootstrap.css",
            "styles.css"
        ],
        "scripts": [],


来源: stackexchange

问:
how to verifying hashed password php class
how to verify this hashed password from php class</p>

```<code>if(isset($_POST['loginSubmit'])){

    $key = '256sk0$*';
    $conditions['where'] = array(
        'id' => $_POST['id'],
        'password' => password_verify($_POST['password'].$key),
        'status' => '1'

     );
</code>```

答: encode password from post by your algorithm and compare with stored password in db.</p>

ContentLicense: CC BY-SA 3.0

Body:
how to verify this hashed password from php class

if(isset($_POST['loginSubmit'])){

    $key = '256sk0$*';
    $conditions['where'] = array(
        'id' => $_POST['id'],
        'password' => password_verify($_POST['password'].$key),
        'status' => '1'

     );


问:
Using rm in a makefile on Windows with MSYS
I have the following code in my makefile to remove files I don't want to persist after the tex file has been compiled succesfully.

```<code>grep '^OUTPUT ' $*.fls \
    | sed -e 's/^OUTPUT //' \
    | grep -vx $@ \
    | xargs rm
rm $*.fls
rm -f $*.bbl $*.blg
</code>```

I get the following error after the pdf has been produced succesfully.

```<code>rm: cannot remove `00_Master_Thesis.log': Permission denied
rm: cannot remove `00_Master_Thesis.nlo': Permission denied
rm: cannot remove `00_Master_Thesis.aux': Permission denied
rm: cannot remove `00_Master_Thesis.out': Permission denied
make.exe": *** [00_Master_Thesis.pdf] Error 123
</code>```

I tried to add several commands to get the right to delete those files and checked the rights on the folder containing these files. I also tried to start cmd as admin but nothing seems to help.

The same makefile is working fine on my Ubuntu system.
How can I let make delete those files on Windows, too?

EDIT:

The problem seems to be, that pdflatex.exe does not quit after the pdf has been written. I even can't delete those files manually because according to the windows explorer they are still opened in pdflatex.exe.

After I killed pdflatex.exe the error message changed now only showing:

```<code>rm: cannot remove `00_Master_Thesis.log': Permission denied
make.exe": *** [00_Master_Thesis.pdf] Error 123
</code>```

Now in addition to the log file only the *.log, *.bbl, *.blg, *.fls, *.ilg and *.nls files aren't removed. The *.aux, *.out and *.nlo files are gone for good after make finishes, which is at least a step in the right direction. ^^

How can I get pdflatex.exe get to quit or release the files so rm can remove them?

答:
As suggested by @RonaldSmith, try adding both options:

-halt-on-error and -interaction batchmode,

then it should work.

Body:
I have the following code in my makefile to remove files I don't want to persist after the tex file has been compiled succesfully.

grep '^OUTPUT ' $*.fls \
    | sed -e 's/^OUTPUT //' \
    | grep -vx $@ \
    | xargs rm
rm $*.fls
rm -f $*.bbl $*.blg

I get the following error after the pdf has been produced succesfully.

rm: cannot remove `00_Master_Thesis.log': Permission denied
rm: cannot remove `00_Master_Thesis.nlo': Permission denied
rm: cannot remove `00_Master_Thesis.aux': Permission denied
rm: cannot remove `00_Master_Thesis.out': Permission denied
make.exe": *** [00_Master_Thesis.pdf] Error 123

I tried to add several commands to get the right to delete those files and checked the rights on the folder containing these files. I also tried to start cmd as admin but nothing seems to help.

The same makefile is working fine on my Ubuntu system.
How can I let make delete those files on Windows, too?

EDIT:

The problem seems to be, that pdflatex.exe does not quit after the pdf has been written. I even can't delete those files manually because according to the windows explorer they are still opened in pdflatex.exe.

After I killed pdflatex.exe the error message changed now only showing:

rm: cannot remove `00_Master_Thesis.log': Permission denied
make.exe": *** [00_Master_Thesis.pdf] Error 123

Now in addition to the log file only the *.log, *.bbl, *.blg, *.fls, *.ilg and *.nls files aren't removed. The *.aux, *.out and *.nlo files are gone for good after make finishes, which is at least a step in the right direction. ^^

How can I get pdflatex.exe get to quit or release the files so rm can remove them?


问:
How to monitor applications status using .NET?
I have to develop a system that monitors applications runnig in a network. It should collects informations about the status of applications as well as sends alerts in case of problems.
I choose to develop this application on .NET.
Please indicates me if there is any APIs for that purpose or any ideas that can help me to begin.
If you suggest any other framework to develop such project may I know the reasons!

Thank you

答:
To be more clear, in my network I have different machines and servers where are running some applications like databases, web applications and many ohers.

The manager of this network need a monitoring application that alerts him if any application was fall down. But I haven't specifications about the kind of problems that may occur!!

May I have more explanations about WMI.

Thank you.

OwnerDisplayName: geniecom

ContentLicense: CC BY-SA 2.5


问:
Xpath - How to select related cousin data
```<code><html>
    <table border="1">
        <tbody>
            <tr>
                <td>
                    <table border="1">
                        <tbody>
                            <tr>
                                <th>aaa</th>
                                <th>bbb</th>
                                <th>ccc</th>
                                <th>ddd</th>
                                <th>eee</th>
                                <th>fff</th>
                            </tr>
                            <tr>
                                <td>111</td>
                                <td>222</td>
                                <td>333</td>
                                <td>444</td>
                                <td>555</td>
                                <td>666</td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>
</html>
</code>```

How can i select specific related cousin data using xpath, The desired output would be be:

```<code><th>aaa</th>
<th>ccc</th>
<th>fff</th>
<td>111</td>
<td>333</th>
<td>666</td>
</code>```

The most important aspect of the xpath is that i am looking to be able to include or exclude certain  tags and their corresponding tags

So based on the answers so far the closest I have is:

```<code>//th[not(contains(text(), "ddd"))] | //tr[2]/td[not(position()=4)]
</code>```

Is there any way of not explicitly using position()=4 but instead reference the corresponding th tag

答:
I'm not sure that this is the best solution, but you might try

```<code>//th[not(.="bbb") and not(.="ddd") and not(.="eee")] | //tr[2]/td[not(position()=index-of(//th, "bbb")) and not(position()=index-of(//th, "ddd")) and not(position()=index-of(//th, "eee"))]
</code>```

or shorter version

```<code>//th[not(.=("bbb", "ddd", "eee"))]| //tr[2]/td[not(position()=(index-of(//th, "bbb"), index-of(//th, "ddd"),index-of(//th, "eee")))]
</code>```

that returns

```<code><th>aaa</th>
<th>ccc</th>
<th>fff</th>
<td>111</td>
<td>333</td>
<td>666</td>
</code>```

You can avoid using complicated XPath expressions to get required output. Try to use Python + Selenium features instead:

```<code># Get list of th elements
th_elements = driver.find_elements_by_xpath('//th')
# Get list of td elements
td_elements = driver.find_elements_by_xpath('//tr[2]/td')
# Get indexes of required th elements - [0, 2, 5]
ok_index = [th_elements.index(i) for i in th_elements if i.text not in ('bbb', 'ddd', 'eee')]
for i in ok_index:
    print(th_elements[i].text)
for i in ok_index:
    print(td_elements[i].text)
</code>```

Output is

```<code>'aaa'
'ccc'
'fff'
'111'
'333'
'666'
</code>```

If you need XPath 1.0 solution:

```<code>//th[not(.=("bbb", "ddd", "eee"))]| //tr[2]/td[not(position()=(count(//th[.="bbb"]/preceding-sibling::th)+1, count(//th[.="ddd"]/preceding-sibling::th)+1, count(//th[.="eee"]/preceding-sibling::th)+1))]
</code>```

Body:
                                aaa
                                bbb
                                ccc
                                ddd
                                eee
                                fff

                                111
                                222
                                333
                                444
                                555
                                666

How can i select specific related cousin data using xpath, The desired output would be be:

aaa
ccc
fff
111
333
666

The most important aspect of the xpath is that i am looking to be able to include or exclude certain  tags and their corresponding tags

So based on the answers so far the closest I have is:

//th[not(contains(text(), "ddd"))] | //tr[2]/td[not(position()=4)]

Is there any way of not explicitly using position()=4 but instead reference the corresponding th tag

Body:
I'm not sure that this is the best solution, but you might try

//th[not(.="bbb") and not(.="ddd") and not(.="eee")] | //tr[2]/td[not(position()=index-of(//th, "bbb")) and not(position()=index-of(//th, "ddd")) and not(position()=index-of(//th, "eee"))]

or shorter version

//th[not(.=("bbb", "ddd", "eee"))]| //tr[2]/td[not(position()=(index-of(//th, "bbb"), index-of(//th, "ddd"),index-of(//th, "eee")))]

<a href="http://videlibri.sourceforge.net/cgi-bin/xidelcgi?&data=%3Chtml%3E%0A%20%3Ctable%20border%3D%221%22%3E%0A%20%3Ctbody%3E%0A%20%3Ctr%3E%0A%20%3Ctd%3E%0A%20%3Ctable%20border%3D%221%22%3E%0A%20%3Ctbody%3E%0A%20%3Ctr%3E%0A%20%3Cth%3Eaaa%3C%2Fth%3E%0A%20%3Cth%3Ebbb%3C%2Fth%3E%0A%20%3Cth%3Eccc%3C%2Fth%3E%0A%20%3Cth%3Eddd%3C%2Fth%3E%0A%20%3Cth%3Eeee%3C%2Fth%3E%0A%20%3Cth%3Efff%3C%2Fth%3E%0A%20%3C%2Ftr%3E%0A%20%3Ctr%3E%0A%20%3Ctd%3E111%3C%2Ftd%3E%0A%20%3Ctd%3E222%3C%2Ftd%3E%0A%20%3Ctd%3E333%3C%2Ftd%3E%0A%20%3Ctd%3E444%3C%2Ftd%3E%0A%20%3Ctd%3E555%3C%2Ftd%3E%0A%20%3Ctd%3E666%3C%2Ftd%3E%0A%20%3C%2Ftr%3E%0A%20%3C%2Ftbody%3E%0A%20%3C%2Ftable%3E%0A%20%3C%2Ftd%3E%0A%20%3C%2Ftr%3E%0A%20%3C%2Ftbody%3E%0A%20%3C%2Ftable%3E%0A%3C%2Fhtml%3E&=&extract=%2F%2Fth[not(.%3D%22bbb%22)%20and%20not(.%3D%22ddd%22)%20and%20not(.%3D%22eee%22)]%20%7C%20%2F%2Ftr[2]%2Ftd[not(position()%3Dindex-of(%2F%2Fth%2C%20%22bbb%22))%20and%20not(position()%3Dindex-of(%2F%2Fth%2C%20%22ddd%22))%20and%20not(position()%3Dindex-of(%2F%2Fth%2C%20%22eee%22))]%0A&=%2F%2Fth[not(.%3D%22bbb%22)%20and%20not(.%3D%22ddd%22)%20and%20not(.%3D%22eee%22)]%20%7C%20%2F%2Ftr[2]%2Ftd[not(position()%3Dindex-of(%2F%2Fth%2C%20%22bbb%22))%20and%20not(position()%3Dindex-of(%2F%2Fth%2C%20%22ddd%22))%20and%20not(position()%3Dindex-of(%2F%2Fth%2C%20%22eee%22))]&input-format=html&printed-node-format=html&output-format=adhoc&compatibility=Enable%20all%20extensions&dot-notation=unambiguous&extract-kind=xpath2" rel="nofollow noreferrer">that returns

<th>aaa</th>
<th>ccc</th>
<th>fff</th>
<td>111</td>
<td>333</td>
<td>666</td>

You can avoid using complicated XPath expressions to get required output. Try to use Python + Selenium features instead:

# Get list of th elements
th_elements = driver.find_elements_by_xpath('//th')
# Get list of td elements
td_elements = driver.find_elements_by_xpath('//tr[2]/td')
# Get indexes of required th elements - [0, 2, 5]
ok_index = [th_elements.index(i) for i in th_elements if i.text not in ('bbb', 'ddd', 'eee')]
for i in ok_index:
    print(th_elements[i].text)
for i in ok_index:
    print(td_elements[i].text)

Output is

'aaa'
'ccc'
'fff'
'111'
'333'
'666'

If you need XPath 1.0 solution:

//th[not(.=("bbb", "ddd", "eee"))]| //tr[2]/td[not(position()=(count(//th[.="bbb"]/preceding-sibling::th)+1, count(//th[.="ddd"]/preceding-sibling::th)+1, count(//th[.="eee"]/preceding-sibling::th)+1))]


问:
Convert array to WrappedArray
I have tried to use WrappedArray and initialize it by null

```<code>var classes:WrappedArray [String]= null
 var classe = ENTEleveClasses.apply(0)
         if(!classe.isEmpty()) {
           var cls = classe.split(",")
           for(c <- cls){
             classes =   classes :+ c  //  the error
           }
           classes
         }else ENTEleveClasses
</code>```

Error :

```<code>Caused by: java.lang.NullPointerException
    at comptesInvites.EleveENT$$anonfun$1.apply(EleveENT.scala:19)
    at comptesInvites.EleveENT$$anonfun$1.apply(EleveENT.scala:16)
    ... 16 more
</code>```

when I add an element a WrappedArray an Error occurred

Thanks

答:
You should always try to avoid initializing variables with null as it leads to numerous nullpointerExceptions and can even damage a system as a whole.

You should initialize the WrappedArray classes as

```<code>var classes:mutable.WrappedArray [String]= mutable.WrappedArray.empty[String]
</code>```

Title: Convert array to WrappedArray

Body:
I have tried to use WrappedArray and initialize it by null

var classes:WrappedArray [String]= null
 var classe = ENTEleveClasses.apply(0)
         if(!classe.isEmpty()) {
           var cls = classe.split(",")
           for(c <- cls){
             classes =   classes :+ c  //  the error
           }
           classes
         }else ENTEleveClasses

Error :

Caused by: java.lang.NullPointerException
    at comptesInvites.EleveENT$$anonfun$1.apply(EleveENT.scala:19)
    at comptesInvites.EleveENT$$anonfun$1.apply(EleveENT.scala:16)
    ... 16 more

when I add an element a WrappedArray an Error occurred

Thanks

Body:
You should always try to avoid initializing variables with null as it leads to numerous nullpointerExceptions and can even damage a system as a whole.

You should initialize the WrappedArray classes as

var classes:mutable.WrappedArray [String]= mutable.WrappedArray.empty[String]


问:
Tkinter timer to start at 0 on button click
I would like to create a timer that starts at 0 when a user presses a button and stop at whatever time it has displayed when the user presses the button again. So far, all of the questions user after that looks at the current time and updates in seconds from whatever time it is like so:

```<code>def timer(self):
    now = time.strftime("%H:%M:%S")
    self.label.configure(text=now)
    self.after(1000, self.timer)
</code>```

But I would like to start at zero, display the minutes and seconds. Is there anyway to achieve this?

答:
Here's a simple stopwatch GUI. There's some room for improvement. ;)

```<code>import tkinter as tk
from time import time

class Stopwatch:
    def __init__(self):
        root = tk.Tk()
        root.title('Stopwatch')

        self.display = tk.Label(root, text='00:00', width=20)
        self.display.pack()

        self.button = tk.Button(root, text='Start', command=self.toggle)
        self.button.pack()

        self.paused = True
        root.mainloop()

    def toggle(self):
        if self.paused:
            self.paused = False
            self.button.config(text='Stop')
            self.oldtime = time()
            self.run_timer()
        else:
            self.paused = True
            self.oldtime = time()
            self.button.config(text='Start')

    def run_timer(self):
        if self.paused:
            return
        delta = int(time() - self.oldtime)
        timestr = '{:02}:{:02}'.format(*divmod(delta, 60))
        self.display.config(text=timestr)
        self.display.after(1000, self.run_timer)

Stopwatch()
</code>```

The toggle method toggles the stopwatch on or off. The run_timer method updates the display Label with the time since the timer started, in minutes & seconds. For more accuracy, reduce the .after delay to say, 500, or 100. That will do unnecessary (and invisible) updates to the Label, but the displayed time will be a little more accurate, and the GUI will feel a little more responsive.

Body:
I would like to create a timer that starts at 0 when a user presses a button and stop at whatever time it has displayed when the user presses the button again. So far, all of the questions user after that looks at the current time and updates in seconds from whatever time it is like so:

def timer(self):
    now = time.strftime("%H:%M:%S")
    self.label.configure(text=now)
    self.after(1000, self.timer)

But I would like to start at zero, display the minutes and seconds. Is there anyway to achieve this?

Body:
Here's a simple stopwatch GUI. There's some room for improvement. ;)

import tkinter as tk
from time import time

class Stopwatch:
    def __init__(self):
        root = tk.Tk()
        root.title('Stopwatch')

        self.display = tk.Label(root, text='00:00', width=20)
        self.display.pack()

        self.button = tk.Button(root, text='Start', command=self.toggle)
        self.button.pack()

        self.paused = True
        root.mainloop()

    def toggle(self):
        if self.paused:
            self.paused = False
            self.button.config(text='Stop')
            self.oldtime = time()
            self.run_timer()
        else:
            self.paused = True
            self.oldtime = time()
            self.button.config(text='Start')

    def run_timer(self):
        if self.paused:
            return
        delta = int(time() - self.oldtime)
        timestr = '{:02}:{:02}'.format(*divmod(delta, 60))
        self.display.config(text=timestr)
        self.display.after(1000, self.run_timer)

Stopwatch()

The toggle method toggles the stopwatch on or off. The run_timer method updates the display Label with the time since the timer started, in minutes & seconds. For more accuracy, reduce the .after delay to say, 500, or 100. That will do unnecessary (and invisible) updates to the Label, but the displayed time will be a little more accurate, and the GUI will feel a little more responsive.


问:
Can't toggle active/inactive states a rows in Laravel
I  make a custom view to user easy turn of or turn off a post. Like this image.

I have an error like:

POST http://127.0.0.1:8000/admin/apartments/1/active 404 (Not Found).

In Controller/Admin/ApartmentController.php:

```<code>public function index(Request $request)
{
    $variations = Apartment::all();
    $dataType = DataType::where('slug', '=', 'products')->first();
    return view('voyager::apartments.browse', compact('dataType', 'variations'));
}
public function active(Apartment $apartment)
{
    $apartment->active = true;
    $apartment->save();
}
</code>```

In resources/views/vendor/voyager/apartments/browse.blade.php:

```<code><tbody>
    @foreach($variations as $data)
        <tr>
            <?php $checked = ($data->active == 1) ? true : false; ?>
            <td>
                <input type="checkbox" name="active" data-id="{{$data->id}}" class="toggleswitch toggleactive" @if($checked) checked @endif>
            </td>
        </tr>
    @endforeach
</tbody>

@section('javascript')
    <!-- DataTables -->
    <script>

      $(document).ready(function(){
          $('.toggleswitch').bootstrapToggle();
      });

      function parseActionUrl(action, id) {
          if (action.match(/\/[0-9]+$/)) {
              return action.replace(/([0-9]+$)/, id);
          }
          return action + '/' + id;
      }

      $('.toggleactive').on('change', function() {
          $.post('/admin/apartments/' + $(this).data('id') + '/active', { active: ($(this).is(':checked')) ? 1 : 0, _token : '{{ csrf_token() }}' }, function(){
              toastr.success("Updated success: apartment is actived");
          });
      });

    </script>
@stop
</code>```

... and routes/web.php:

```<code>Route::group(['prefix' => 'admin'], function () {
    Voyager::routes();

    Route::post('apartments/:id/active', 'ApartmentController@active');

    Route::group(['middleware' => ['admin.user'], 'as' => 'voyager.'], function () {
        Route::resource('apartments', 'Admin\ApartmentController');
    });
});
</code>```

Note:

If I want to when clicking button On, show toast message like: The apartment is enabled. Else when clicking button Off it will show button The apartment is disabled.

Have the best way to change this code?

```<code>$('.toggleactive').on('change', function() {
    $.post('/admin/apartments/' + $(this).data('id') + '/active', { active: ($(this).is(':checked')) ? 1 : 0, _token : '{{ csrf_token() }}' }, function(){
        toastr.success("Updated success: apartment is actived");
    });
});
</code>```

答:
Change your route to this.

```<code>Route::post('apartments/{apartment}/active', 'Admin\ApartmentController@active');
</code>```

Also change your controller method to this.

```<code>public function active(Apartment $apartment)
{
    $apartment->active = request('active');
    $apartment->save();
}
</code>```

Edit : Do this to update your toast message based on the request.

```<code>public function active(Apartment $apartment)
{
    $status = request('active');
    $apartment->active = $status;
    $apartment->save();

    return $status;
}

$('.toggleactive').on('change', function() {
    $.post('/admin/apartments/' + $(this).data('id') + '/active', { active: ($(this).is(':checked')) ? 1 : 0, _token : '{{ csrf_token() }}' }, function(data){
        toastr.success("Updated success: The apartment is " + (data == 1 ? 'enabled' : 'disabled'));
    });
});
</code>```

Body:
I  make a custom view to user easy turn of or turn off a post. Like this image.

I have an error like:

POST http://127.0.0.1:8000/admin/apartments/1/active 404 (Not Found).

In Controller/Admin/ApartmentController.php:

public function index(Request $request)
{
    $variations = Apartment::all();
    $dataType = DataType::where('slug', '=', 'products')->first();
    return view('voyager::apartments.browse', compact('dataType', 'variations'));
}
public function active(Apartment $apartment)
{
    $apartment->active = true;
    $apartment->save();
}

In resources/views/vendor/voyager/apartments/browse.blade.php:

    @foreach($variations as $data)

            <?php $checked = ($data->active == 1) ? true : false; ?>

                <input type="checkbox" name="active" data-id="{{$data->id}}" class="toggleswitch toggleactive" @if($checked) checked @endif>

    @endforeach

@section('javascript')

@stop

... and routes/web.php:

Route::group(['prefix' => 'admin'], function () {
    Voyager::routes();

    Route::post('apartments/:id/active', 'ApartmentController@active');

    Route::group(['middleware' => ['admin.user'], 'as' => 'voyager.'], function () {
        Route::resource('apartments', 'Admin\ApartmentController');
    });
});

Note:

If I want to when clicking button On, show toast message like: The apartment is enabled. Else when clicking button Off it will show button The apartment is disabled.

Have the best way to change this code?

$('.toggleactive').on('change', function() {
    $.post('/admin/apartments/' + $(this).data('id') + '/active', { active: ($(this).is(':checked')) ? 1 : 0, _token : '{{ csrf_token() }}' }, function(){
        toastr.success("Updated success: apartment is actived");
    });
});

Body:
Change your route to this.

Route::post('apartments/{apartment}/active', 'Admin\ApartmentController@active');

Also change your controller method to this.

public function active(Apartment $apartment)
{
    $apartment->active = request('active');
    $apartment->save();
}

Edit : Do this to update your toast message based on the request.

public function active(Apartment $apartment)
{
    $status = request('active');
    $apartment->active = $status;
    $apartment->save();

    return $status;
}

$('.toggleactive').on('change', function() {
    $.post('/admin/apartments/' + $(this).data('id') + '/active', { active: ($(this).is(':checked')) ? 1 : 0, _token : '{{ csrf_token() }}' }, function(data){
        toastr.success("Updated success: The apartment is " + (data == 1 ? 'enabled' : 'disabled'));
    });
});


问:
boostrap modal not updating with vue js v2 two way binding
I'm new to vue js and trying to use it with a bootstrap modal to view more data. My scenario is a table with multiple records and a button to see in depth details for the clicked record in a bootstrap modal. After clicking the first button it caches and doesn't update it while selecting another button for different details.

Does anyone see what I'm doing wrong?

(It's a combination of Laravel, jQuery and VueJS)

HTML Table:

```<code><table class="table table-striped">
<thead>
    <tr>
        <th>E-mail address</th>
        <th>Status</th>
        <th>Sent at</th>
        <th>Expires in</th>
        <th></th>
    </tr>
</thead>
<tbody>
    <tr>
        <td class="v-align-middle">
            john@doe.example
        </td>
        <td class="v-align-middle">
            <span class="label label-default">
                pending
            </span>
        </td>
        <td class="v-align-middle">
            2017-06-05 17:59:15
        </td>
        <td class="v-align-middle">
            29 days
        </td>
        <td>
            <div class="btn-group pull-right">
                <a href="#" class="btn btn-default" data-toggle="modal" data-target="#inviteDetailsModal" data-email="john@doe.example">
                    <i class="fa fa-eye"></i>
                </a>
            </div>
        </td>
    </tr>
    <tr>
        <td class="v-align-middle">
            jane@doe.example
        </td>
        <td class="v-align-middle">
            <span class="label label-default">
                pending
            </span>
        </td>
        <td class="v-align-middle">
            2017-06-05 13:27:25
        </td>
        <td class="v-align-middle">
            29 days
        </td>
        <td>
            <div class="btn-group pull-right">
                <a href="#" class="btn btn-default" data-toggle="modal" data-target="#inviteDetailsModal" data-email="jane@doe.example">
                    <i class="fa fa-eye"></i>
                </a>
            </div>
        </td>
    </tr>
</tbody>
</code>```

JavaScript:

```<code>$('[data-target="#inviteDetailsModal"]').on('click', function () {
    let email = $(this).data('email'),
        baseUrl = $('html').data('base');

    Vue.component('invite-details', {
        data: function () {
            return {
                email: null,
                token: null,
                logs: [],
                expires: null
            }
        },
        methods: {
            update: function (data) {
                this.email = data['email'];
                this.token = data['token'];
                this.logs = data['logs'];
                this.expires = data['expires'];
            },
            fetchData: function () {
                this.$http.get(baseUrl + '/system/invites/' + email + '/details')
                    .then(response => {
                        this.update(response.body);
                    }, response => {
                        console.log('whoops something went wrong');
                    });
            }
        },
        mounted: function () {
            this.$el.addEventListener('shown.bs.modal', this.fetchData());
        },
        beforeDestroy: function () {
            this.$el.removeEventListener('shown.bs.modal', this.fetchData());
        }
    });

    new Vue({
        el: '#inviteDetailsModal'
    });
});
</code>```

The bootstrap modal:

```<code><div class="modal fade slide-up" id="inviteDetailsModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content-wrapper">
        <invite-details inline-template>
            <div class="modal-content" id="details">
                <div class="modal-header clearfix text-left">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        <i class="pg-close fs-14"></i>
                    </button>
                    <h5>
                        Invite details for <span class="semi-bold">@{{ email }}</span>
                    </h5>
                    <p class="p-b-10">
                        <span data-tooltip="true" data-placement="bottom" title="token">
                            <em>@{{ token }}</em>
                        </span>
                    </p>
                </div>
                <div class="modal-body">
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>Sent at</th>
                            <th>Status</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="log in logs">
                            <td>@{{ log.number }}</td>
                            <td>@{{ log.sentAt }}</td>
                            <td>@{{ log.status }}</td>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer text-center">
                    <span class="hint-text">
                        <em>expires in <strong>@{{ expires }}</strong> days</em>
                    </span>
                </div>
            </div>
        </invite-details>
    </div>
</div>
</code>```

答:
Since you're using one modal component and are attempting to change its content based on the specific button in the table clicked, the mounted hook is only going to fire once when the component is initially mounted.

What you want is for the content to update each time the modal is shown.

First of, it looks like your component only needs one email prop. Move the rest of the props to be in the data method for the component, since (I'm assuming) they aren't being passed into the component:

```<code>props: ['email'],
data: function() {
  return {
    token: null,
    logs: null,
    expires: null,
  }
}
</code>```

Then, I would create a new method called fetchData to put the $http.get call in:

```<code>fetchData: function() {
  this.$http.get('http://localhost:2000/system/invites/' + this.email + '/details')
    .then(response => {
      this.update(response.body);
    }, response => {
      console.log('whoops something went wrong');
    });
}
</code>```

In your modal component's mounted hook, add a listener to the bootstrap modal's show event using jQuery. And be sure to remove the listener in the component's beforeDestroy hook:

```<code>mounted() {
  $(this.$el).on('shown.bs.modal', this.fetchData);
},
beforeDestroy() {
  $(this.$el).off('shown.bs.modal', this.fetchData);
}
</code>```

Now, every time the modal's show event fires, the $http.get request will fire based on the current value of the component's email property.

Here's an example fiddle.

Body:
I'm new to vue js and trying to use it with a bootstrap modal to view more data. My scenario is a table with multiple records and a button to see in depth details for the clicked record in a bootstrap modal. After clicking the first button it caches and doesn't update it while selecting another button for different details.

Does anyone see what I'm doing wrong?

(It's a combination of Laravel, jQuery and VueJS)

HTML Table:

        E-mail address
        Status
        Sent at
        Expires in

            john@doe.example

                pending

            2017-06-05 17:59:15

            29 days

            jane@doe.example

                pending

            2017-06-05 13:27:25

            29 days

JavaScript:

$('[data-target="#inviteDetailsModal"]').on('click', function () {
    let email = $(this).data('email'),
        baseUrl = $('html').data('base');

    Vue.component('invite-details', {
        data: function () {
            return {
                email: null,
                token: null,
                logs: [],
                expires: null
            }
        },
        methods: {
            update: function (data) {
                this.email = data['email'];
                this.token = data['token'];
                this.logs = data['logs'];
                this.expires = data['expires'];
            },
            fetchData: function () {
                this.$http.get(baseUrl + '/system/invites/' + email + '/details')
                    .then(response => {
                        this.update(response.body);
                    }, response => {
                        console.log('whoops something went wrong');
                    });
            }
        },
        mounted: function () {
            this.$el.addEventListener('shown.bs.modal', this.fetchData());
        },
        beforeDestroy: function () {
            this.$el.removeEventListener('shown.bs.modal', this.fetchData());
        }
    });

    new Vue({
        el: '#inviteDetailsModal'
    });
});

The bootstrap modal:

        <invite-details inline-template>

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">

                    </button>

                        Invite details for @{{ email }}

                            @{{ token }}

                            #
                            Sent at
                            Status

                            @{{ log.number }}
                            @{{ log.sentAt }}
                            @{{ log.status }}

                        expires in @{{ expires }} days

        </invite-details>

Body:
Since you're using one modal component and are attempting to change its content based on the specific button in the table clicked, the mounted hook is only going to fire once when the component is initially mounted.

What you want is for the content to update each time the modal is shown.

First of, it looks like your component only needs one email prop. Move the rest of the props to be in the data method for the component, since (I'm assuming) they aren't being passed into the component:

props: ['email'],
data: function() {
  return {
    token: null,
    logs: null,
    expires: null,
  }
}

Then, I would create a new method called fetchData to put the $http.get call in:

fetchData: function() {
  this.$http.get('http://localhost:2000/system/invites/' + this.email + '/details')
    .then(response => {
      this.update(response.body);
    }, response => {
      console.log('whoops something went wrong');
    });
}

In your modal component's mounted hook, add a listener to the bootstrap modal's show event using jQuery. And be sure to remove the listener in the component's beforeDestroy hook:

mounted() {
  $(this.$el).on('shown.bs.modal', this.fetchData);
},
beforeDestroy() {
  $(this.$el).off('shown.bs.modal', this.fetchData);
}

Now, every time the modal's show event fires, the $http.get request will fire based on the current value of the component's email property.

Here's an example fiddle.


问:
TypeError: list indices must be integers or slices, not str 'convert the chararter'
```<code>Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
      print(Number[n]+1\n)
InputNum3 = input()
Number[InputNum3] = ''.join(str('-'))
</code>```

want:

```<code>1       2
     3
     4
     .... 20
</code>```

input 2

want:

```<code>1
      -
      3
      4...20
</code>```

but the result is:

TypeError: list indices must be integers or slices, not str

答:
In Python3, input() returns a string. In Python2, however, input() returns the type you are looking for, an integer. Therefore, you need to cast the input() function to an int, since you are obviously trying to assign a value in the list by index. </p>

```<code>Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
   print(Number[n]+1\n)

InputNum3 = int(input())
Number[InputNum3] = ''.join(str('-'))
</code>```

Body:
Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
      print(Number[n]+1\n)
InputNum3 = input()
Number[InputNum3] = ''.join(str('-'))

want:

1       2
     3
     4
     .... 20

input 2

want:

1
      -
      3
      4...20

but the result is:

TypeError: list indices must be integers or slices, not str

Body:
In Python3, input() returns a string. In Python2, however, input() returns the type you are looking for, an integer. Therefore, you need to cast the input() function to an int, since you are obviously trying to assign a value in the list by index.

Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
   print(Number[n]+1\n)

InputNum3 = int(input())
Number[InputNum3] = ''.join(str('-'))


问:
is there a Collection Subscription Inheritance passed onto child templates
Consider below hierarchy of templates,

'A' has 2 template 'B' and 'C'.

'B' has 2 templates 'D' and 'E'.

my question is whether the meteor collection subcription made in template 'A' is available in the helper for template 'E' since 'A' has 'B' and 'B' has 'E'?

NOTE: if YES/NO why?

答:
will that data be available? probably.

if template A is setting up the sub in its onCreated(), and attached to "this", then that means the sub will go away when the template is destroyed.

and if the sub-template is set up like this:

```<code><template name="A">
  {{> B}}
</template>
</code>```

... template A is not destroyed while B is rendered.

this means that template B should be able to do a find() in minimongo and see that data that A subscribed to.

personally, i prefer to pass down from A to B any data that A "owns" that B uses. but that works better in a non-reactive scenario. if B needs to find() data and expects it to be reactive, then i'll typically have B also subscribe to that data. imho, it's more clear in that case to have B also subscribe, because if it's taken out of the A context, it will stop working.

Body:
will that data be available? probably.

if template A is setting up the sub in its onCreated(), and attached to "this", then that means the sub will go away when the template is destroyed.

and if the sub-template is set up like this:

<template name="A">
  {{> B}}
</template>

... template A is not destroyed while B is rendered.

this means that template B should be able to do a find() in minimongo and see that data that A subscribed to.

personally, i prefer to pass down from A to B any data that A "owns" that B uses. but that works better in a non-reactive scenario. if B needs to find() data and expects it to be reactive, then i'll typically have B also subscribe to that data. imho, it's more clear in that case to have B also subscribe, because if it's taken out of the A context, it will stop working.


问:
Unable to build in AMD-GPU kernel module: This feature depends on another which has been configured as a module
I am trying to build-in the AMD-GPU kernel module to my custom kernel. However, I am only able to build it as a module. When I press y in order to build it a text box appears that reads:
  This feature depends on another which has been configured as a module. As a result, this feature will be built as a module.

My question is, what kernel modules does the AMD-GPU module depend on so that I can build it into the kernel?

Apologies for my wording and formatting, and thanks for the help.

答:
if you type modinfo amdgpu modinfo gives you all the info about the kernel object.

AMDGPU depends:  drm,drm_kms_helper,ttm,i2c-algo-bit


问:
Long to wide with automatic dummy creation and multiple value columns
I'm sitting in front of a dataframe that looks like this:

```<code>      country year Indicator         a         b        c
48996      US 2003      var1        NA        NA       NA
16953      FR 1988      var2        NA 10664.920       NA
22973      FR 1943      var3        NA  5774.334       NA
8760       CN 1995      var4  8804.565        NA 12750.31
47795      US 2012      var5        NA        NA       NA
30033      GB 1969      var6        NA 29631.362       NA
25796      FR 1921      var7        NA 14004.520       NA
39534      NL 1941      var8        NA        NA       NA
42255      NZ 1969      var8        NA        NA       NA
7249       CN 1995      var9 50635.862        NA 75260.56
</code>```

What I want to do is basically a long to wide transformation with Indicator as key variable. I would usually use spread() from the tidyr package. However, spread() unfortunately does not accept multiple value columns (in this case a, b and c) and it does not fully do what I want to achieve:

Make the entries of Indicator the new columns

Keep the Country / Year combinations as rows

Creat a UNIQUE row for every old value from a, b and c

Create a Dummy Variable for every "old" value column name (i.e. a,
b, c)

So in the end, the Chinese observations of my example should become

```<code>country year var1 [...] var4       [...]   var9       dummy.a dummy.b dummy.c
CN      1995 NA         8804.565           50635.862        1       0       0
CN      1995 NA         12750.31           75260.56         0       0       1
</code>```

As my original dataframe is 58.162x119, I would appreciate something that does not include a lot of manual work :-)

I hope I was clear in what I want to achieve. Thanks for your help!

The above mentioned dataframe can be reproduced using the following code:

```<code>structure(list(country = c("US", "FR", "FR", "CN", "US", "GB",
"FR", "NL", "NZ", "CN"), year = c(2003L, 1988L, 1943L, 1995L,
2012L, 1969L, 1921L, 1941L, 1969L, 1995L), Indicator = structure(c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 8L, 9L), .Label = c("var1", "var2",
"var3", "var4", "var5", "var6", "var7", "var8", "var9", "var10",
"var11", "var12", "var13", "var14", "var15", "var16", "var17",
"var18"), class = "factor"), a = c(NA, NA, NA, 8804.56480733,
NA, NA, NA, NA, NA, 50635.8621327), b = c(NA, 10664.9199219,
5774.33398438, NA, NA, 29631.3618614, 14004.5195312, NA, NA,
NA), c = c(NA, NA, NA, 12750.3056855, NA, NA, NA, NA, NA, 75260.555946
)), .Names = c("country", "year", "Indicator", "a", "b", "c"), row.names = c(48996L,
16953L, 22973L, 8760L, 47795L, 30033L, 25796L, 39534L, 42255L,
7249L), class = "data.frame")
</code>```

Body:
I'm sitting in front of a dataframe that looks like this:

      country year Indicator         a         b        c
48996      US 2003      var1        NA        NA       NA
16953      FR 1988      var2        NA 10664.920       NA
22973      FR 1943      var3        NA  5774.334       NA
8760       CN 1995      var4  8804.565        NA 12750.31
47795      US 2012      var5        NA        NA       NA
30033      GB 1969      var6        NA 29631.362       NA
25796      FR 1921      var7        NA 14004.520       NA
39534      NL 1941      var8        NA        NA       NA
42255      NZ 1969      var8        NA        NA       NA
7249       CN 1995      var9 50635.862        NA 75260.56

What I want to do is basically a long to wide transformation with Indicator as key variable. I would usually use spread() from the tidyr package. However, spread() unfortunately does not accept multiple value columns (in this case a, b and c) and it does not fully do what I want to achieve:

Make the entries of Indicator the new columns

Keep the Country / Year combinations as rows

Creat a UNIQUE row for every old value from a, b and c

Create a Dummy Variable for every "old" value column name (i.e. a,
b, c)

So in the end, the Chinese observations of my example should become

country year var1 [...] var4       [...]   var9       dummy.a dummy.b dummy.c
CN      1995 NA         8804.565           50635.862        1       0       0
CN      1995 NA         12750.31           75260.56         0       0       1

As my original dataframe is 58.162x119, I would appreciate something that does not include a lot of manual work :-)

I hope I was clear in what I want to achieve. Thanks for your help!

The above mentioned dataframe can be reproduced using the following code:

structure(list(country = c("US", "FR", "FR", "CN", "US", "GB",
"FR", "NL", "NZ", "CN"), year = c(2003L, 1988L, 1943L, 1995L,
2012L, 1969L, 1921L, 1941L, 1969L, 1995L), Indicator = structure(c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 8L, 9L), .Label = c("var1", "var2",
"var3", "var4", "var5", "var6", "var7", "var8", "var9", "var10",
"var11", "var12", "var13", "var14", "var15", "var16", "var17",
"var18"), class = "factor"), a = c(NA, NA, NA, 8804.56480733,
NA, NA, NA, NA, NA, 50635.8621327), b = c(NA, 10664.9199219,
5774.33398438, NA, NA, 29631.3618614, 14004.5195312, NA, NA,
NA), c = c(NA, NA, NA, 12750.3056855, NA, NA, NA, NA, NA, 75260.555946
)), .Names = c("country", "year", "Indicator", "a", "b", "c"), row.names = c(48996L,
16953L, 22973L, 8760L, 47795L, 30033L, 25796L, 39534L, 42255L,
7249L), class = "data.frame")

Body:
Here's my solution:

require(tidyr)
mydf <- structure(list(country = c("US", "FR", "FR", "CN", "US", "GB",
    "FR", "NL", "NZ", "CN"), year = c(2003L, 1988L, 1943L, 1995L,
    2012L, 1969L, 1921L, 1941L, 1969L, 1995L), Indicator = structure(c(1L,
    2L, 3L, 4L, 5L, 6L, 7L, 8L, 8L, 9L), .Label = c("var1", "var2",
    "var3", "var4", "var5", "var6", "var7", "var8", "var9", "var10",
    "var11", "var12", "var13", "var14", "var15", "var16", "var17",
    "var18"), class = "factor"), a = c(NA, NA, NA, 8804.56480733,
    NA, NA, NA, NA, NA, 50635.8621327), b = c(NA, 10664.9199219,
    5774.33398438, NA, NA, 29631.3618614, 14004.5195312, NA, NA,
    NA), c = c(NA, NA, NA, 12750.3056855, NA, NA, NA, NA, NA, 75260.555946
    )), .Names = c("country", "year", "Indicator", "a", "b", "c"), row.names = c(48996L,
    16953L, 22973L, 8760L, 47795L, 30033L, 25796L, 39534L, 42255L,
    7249L), class = "data.frame")

mydf %>% gather(key=newIndicator,value=values, a,b,c) %>% filter(!is.na(values)) %>% spread(key=Indicator,values) %>% mutate(indicatorValues=1) %>% spread(newIndicator,indicatorValues,fill=0)

The output

# country year     var2     var3      var4     var6     var7     var9 a b c
# 1      CN 1995       NA       NA  8804.565       NA       NA 50635.86 1 0 0
# 2      CN 1995       NA       NA 12750.306       NA       NA 75260.56 0 0 1
# 3      FR 1921       NA       NA        NA       NA 14004.52       NA 0 1 0
# 4      FR 1943       NA 5774.334        NA       NA       NA       NA 0 1 0
# 5      FR 1988 10664.92       NA        NA       NA       NA       NA 0 1 0
# 6      GB 1969       NA       NA        NA 29631.36       NA       NA 0 1 0


问:
Multiple columns processing and dynamically naming new columns
Variables are mistakenly being entered into multiple columns eg: "aaa_1", "aaa_2" and "aaa_3", or "ccc_1, "ccc_2", and "ccc_3"). Need to create single new columns (eg "aaa", or "ccc"). Some variables are currently in a single column though ("hhh_1"), but more columns may be added (hhh_2 etc).

This is what I got:

```<code>aaa_1 <- c(43, 23, 65, NA, 45)
aaa_2 <- c(NA, NA, NA, NA, NA)
aaa_3 <- c(NA, NA, 92, NA, 82)
ccc_1 <- c("fra", NA, "spa", NA, NA)
ccc_2 <- c(NA, NA, NA, "wez", NA)
ccc_3 <- c(NA, "ija", NA, "fda", NA)
ccc_4 <- c(NA, NA, NA, NA, NA)
hhh_1 <- c(183, NA, 198, NA, 182)
dataf1 <- data.frame(aaa_1,aaa_2,aaa_3,ccc_1,ccc_2, ccc_3,ccc_4,hhh_1)
</code>```

This is what I want:

```<code>aaa <- c(43, 23, NA, NA, NA)
ccc <- c("fra", "ija", "spa", NA, NA)
hhh <- c(183, NA, 198, NA, 182)
dataf2 <- data.frame(aaa,ccc,hhh)
</code>```

General solution needed as there are ~100 variables (eg "aaa", "hhh", "ccc", "ttt", "eee", "hhh"etc).

Thanks!

答:
I'm not sure your example is right. For example in the third row you've got values for both age_1 and age_3, then in the desired output NA for that row.

If I've understood what you're trying to do though, it will be much easier if you transpose columns to rows, fix them and then transpose back again. Try this as a start point using the 'tidyverse' of dplyr and tidyr.

```<code>library(tidyverse)
library(stringr)

age_1 <- c(43, 23, 65, NA, 45)
age_2 <- c(NA, NA, NA, NA, NA)
age_3 <- c(NA, NA, 92, NA, 82)
country_1 <- c("fra", NA, "spa", NA, NA)
country_2 <- c(NA, NA, NA, "wez", NA)
country_3 <- c(NA, "ija", NA, "fda", NA)
country_4 <- c(NA, NA, NA, NA, NA)
hight_1 <- c(183, NA, 198, NA, 182)
dataf1 <- data.frame(age_1,age_2,age_3,country_1,country_2, country_3,country_4,hight_1)

data <- dataf1 %>%
  mutate(row_num = row_number()) %>%   #create a row number to track values
  gather(key, value, -row_num) %>%    #flatten your data
  drop_na() %>%    #drop na rows
  mutate(key = str_replace(key, "_.", "")) %>%   #remove the '_x' part of names
  group_by(row_num) %>%
  top_n(1) %>%
  spread(key, value)  #pivot back to columns
</code>```

For your example you need the group_by() and top_n() lines to make it run because you've got multiple values in the same row. If you only have one value (as I think you should?) then you can remove these two lines. It will be better without them because then it won't run if your data is wrong.

Edit following comment below. This will make any duplicated entries NA.

```<code>data <- dataf1 %>%
  mutate(row_num = row_number()) %>%   #create a row number to track values
  gather(key, value, -row_num) %>%    #flatten your data
  drop_na() %>%    #drop na rows
  mutate(key = str_replace(key, "_.", "")) %>%   #remove the '_x' part of names
  group_by(row_num, key) %>%
  mutate(count = n()) %>%  #count how many entries for each row/key combo
  mutate(value = ifelse(count > 1, NA, value)) %>%   #set NA for rows with duplicates
  drop_na() %>%
  spread(key, value) %>%  #pivot back to columns
  select(-count)  #drop the `count` variable
</code>```

Body:
Variables are mistakenly being entered into multiple columns eg: "aaa_1", "aaa_2" and "aaa_3", or "ccc_1, "ccc_2", and "ccc_3"). Need to create single new columns (eg "aaa", or "ccc"). Some variables are currently in a single column though ("hhh_1"), but more columns may be added (hhh_2 etc).

This is what I got:

aaa_1 <- c(43, 23, 65, NA, 45)
aaa_2 <- c(NA, NA, NA, NA, NA)
aaa_3 <- c(NA, NA, 92, NA, 82)
ccc_1 <- c("fra", NA, "spa", NA, NA)
ccc_2 <- c(NA, NA, NA, "wez", NA)
ccc_3 <- c(NA, "ija", NA, "fda", NA)
ccc_4 <- c(NA, NA, NA, NA, NA)
hhh_1 <- c(183, NA, 198, NA, 182)
dataf1 <- data.frame(aaa_1,aaa_2,aaa_3,ccc_1,ccc_2, ccc_3,ccc_4,hhh_1)

This is what I want:

aaa <- c(43, 23, NA, NA, NA)
ccc <- c("fra", "ija", "spa", NA, NA)
hhh <- c(183, NA, 198, NA, 182)
dataf2 <- data.frame(aaa,ccc,hhh)

General solution needed as there are ~100 variables (eg "aaa", "hhh", "ccc", "ttt", "eee", "hhh"etc).

Thanks!

Body:
I'm not sure your example is right. For example in the third row you've got values for both age_1 and age_3, then in the desired output NA for that row.

If I've understood what you're trying to do though, it will be much easier if you transpose columns to rows, fix them and then transpose back again. Try this as a start point using the 'tidyverse' of dplyr and tidyr.

library(tidyverse)
library(stringr)

age_1 <- c(43, 23, 65, NA, 45)
age_2 <- c(NA, NA, NA, NA, NA)
age_3 <- c(NA, NA, 92, NA, 82)
country_1 <- c("fra", NA, "spa", NA, NA)
country_2 <- c(NA, NA, NA, "wez", NA)
country_3 <- c(NA, "ija", NA, "fda", NA)
country_4 <- c(NA, NA, NA, NA, NA)
hight_1 <- c(183, NA, 198, NA, 182)
dataf1 <- data.frame(age_1,age_2,age_3,country_1,country_2, country_3,country_4,hight_1)

data <- dataf1 %>%
  mutate(row_num = row_number()) %>%   #create a row number to track values
  gather(key, value, -row_num) %>%    #flatten your data
  drop_na() %>%    #drop na rows
  mutate(key = str_replace(key, "_.", "")) %>%   #remove the '_x' part of names
  group_by(row_num) %>%
  top_n(1) %>%
  spread(key, value)  #pivot back to columns

For your example you need the group_by() and top_n() lines to make it run because you've got multiple values in the same row. If you only have one value (as I think you should?) then you can remove these two lines. It will be better without them because then it won't run if your data is wrong.

Edit following comment below. This will make any duplicated entries NA.

data <- dataf1 %>%
  mutate(row_num = row_number()) %>%   #create a row number to track values
  gather(key, value, -row_num) %>%    #flatten your data
  drop_na() %>%    #drop na rows
  mutate(key = str_replace(key, "_.", "")) %>%   #remove the '_x' part of names
  group_by(row_num, key) %>%
  mutate(count = n()) %>%  #count how many entries for each row/key combo
  mutate(value = ifelse(count > 1, NA, value)) %>%   #set NA for rows with duplicates
  drop_na() %>%
  spread(key, value) %>%  #pivot back to columns
  select(-count)  #drop the `count` variable


问:
ASP.NET MVC 3 ViewModels in a different project?
Is there anything from stopping you placing ViewModels in a different project?

I basically have a DataModel (Entity Framework) project, Data Access project (might merge this into the DataModel), Business Logic project and the ASP.NET MVC website. I want the Business Logic layer to return ViewModels so was wondering if these can be separate from the website code.

答:
Absolutely - you just need to reference the DLL in your MVC3 project and then reference those ViewModels in your strongly typed views.

Just make sure you declare

```<code>@model SeperateAssembly.ViewModelName
</code>```

At the top of your views to make them strongly typed.

Body:
Absolutely - you just need to reference the DLL in your MVC3 project and then reference those ViewModels in your strongly typed views.

Just make sure you declare

@model SeperateAssembly.ViewModelName

At the top of your views to make them strongly typed.


问:
How to upload changed files to my server via ftp, when i check in visual studio?
I am using Asp.Net Mvc with Visual Studio 2017 Enterprise.

I am synchronizing my files with Visual Studio Team Services(VSTS) in the cloud.

I dont want to use Publish in Visual Studio. When i Check In my files to VSTS, i want VSTS to send my files to my server via FTP Upload.

I tried some menus in VSTS but i couldn't managed it.

My purpose is Publishing my files (built in my local pc via Visual Studio) by clicking only Check In Button.

By the way i used an VSTS extension named "FTP Uploader", but i couldn't managed it. It didn't work.

So i need a solution for this. Thanks anyway.

答: Any way you go, you're going to need to create a build, which is how you should be building your software, not using local builds. Local builds run the risk of having different .DLLs on your machine as opposed to someone else's machine. A structured build validates that the solution can stand alone. Once you've constructed that, you can add a step to publish whatever you like to almost any destination. I'm not sure I understand your need for uploading to an FTP server, though - can you elaborate on that?</p>


问:
Tab-Navigation - Remember user selection
I'm using a TAB navigation for my subpage Products -> ?p=products (see code below, website is realized with HTML and PHP)

The problem:

The user clicks, for example, in the second TAB the link Details. Then he uses the back button. Now he comes back to the Product site, but not in the second tab, rather in the first.

I would like to remember the last used tab (here: href="#section-2"), if the user goes back to the product page.

How can I realize this?

```<code><div id="tabs" class="tabs">
    <nav>
        <ul>
            <li><a href="#section-1" class="icon-cross"><span>Product 1</span></a></li>
            <li><a href="#section-2" class="icon-cross"><span>Product 2</span></a></li>
            <li><a href="#section-3" class="icon-cross"><span>Product 3</span></a></li>
            <li><a href="#section-4" class="icon-cross"><span>Product 4</span></a></li>
        </ul>
    </nav>

    <div class="content">

        <section id="section-1">
            <div class="tab-heading">
                <hr>
                <h2 class="intro-text text-center"><strong>Product 1</strong></h2>
                <hr>
            </div>
            ...
        </section>

        <section id="section-2">
            <div class="tab-heading">
                <hr>
                <h2 class="intro-text text-center"><strong>Product 2</strong></h2>
                <hr>
            </div>

            <a href="?p=details">Details</a>

        </section>
    </div>
</div>
</code>```

答: I think you need look at this https://css-tricks.com/using-the-html5-history-api/</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm using a TAB navigation for my subpage Products -> ?p=products (see code below, website is realized with HTML and PHP)

The problem:

The user clicks, for example, in the second TAB the link Details. Then he uses the back button. Now he comes back to the Product site, but not in the second tab, rather in the first.

I would like to remember the last used tab (here: href="#section-2"), if the user goes back to the product page.

How can I realize this?

Product 1

Product 2

Product 3

Product 4

Product 1

            ...

Product 2

            Details


问:
Better way to use a map within a struct? Go Programming Language Exercise 1.4
I'm working on Exercise 1.4 from The Go Programming Language. The program reads stdin or files given as arguments and outputs lines that have duplicates.

I have working code, I'm just wondering if there is a better way to use maps within structs?  Right now I have a new map being made in the struct when a unique line is found. But it seems clumsy, and I want to know if I should approach this another way.

```<code>type dupCount struct {
        count int
        fileCount map[string]int
}

func main() {
        counts := make(map[string]dupCount)
        files := os.Args[1:]
        if len(files) == 0 {
                countLines(os.Stdin, counts, "stdin")
        } else {
                for _, arg := range files {
                        f, err := os.Open(arg)
                        if err != nil {
                                fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
                                continue
                        }
                        countLines(f, counts, arg)
                        f.Close()
                }
        }
func countLines(f *os.File, counts map[string]dupCount, filename string) {
        input := bufio.NewScanner(f)
        for input.Scan() {
                var tmp = counts[input.Text()]
                if tmp.count == 0 {
                        tmp.fileCount = make(map[string]int)
                }
                tmp.count++
                tmp.fileCount[filename]++
                counts[input.Text()] = tmp
        }
}
</code>```

I am using the tmp variable in countLines to get around the inability to assign directly to values in maps as outlined in the Go Github repo.

答:
I don't think it is particularly messy but I might be tempted to make some sort of addDupe helper function that takes a dupCount by value, makes whatever changes are required to add the line and returns the dupCount by value

```<code>func addDupe(dupes dupCount, filename string) dupCount {
    if dupes.count == 0 {
        dupes.fileCount = make(map[string]int)
    }
    dupes.fileCount[filename]++
    dupes.count++
    return dupes
}
</code>```

This is similar to the way the standard append function for slices works. Then countLines can be written as:

```<code>func countLines(r io.Reader, counts map[string]dupCount, filename string) {
    input := bufio.NewScanner(r)
    for input.Scan() {
        line := input.Text()
        counts[line] = addDupe(counts[line], filename)
    }
}
</code>```

But all I have done is replace your tmp with a function parameter.

Body:
I'm working on Exercise 1.4 from The Go Programming Language. The program reads stdin or files given as arguments and outputs lines that have duplicates.

I have working code, I'm just wondering if there is a better way to use maps within structs?  Right now I have a new map being made in the struct when a unique line is found. But it seems clumsy, and I want to know if I should approach this another way.

type dupCount struct {
        count int
        fileCount map[string]int
}

func main() {
        counts := make(map[string]dupCount)
        files := os.Args[1:]
        if len(files) == 0 {
                countLines(os.Stdin, counts, "stdin")
        } else {
                for _, arg := range files {
                        f, err := os.Open(arg)
                        if err != nil {
                                fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
                                continue
                        }
                        countLines(f, counts, arg)
                        f.Close()
                }
        }
func countLines(f *os.File, counts map[string]dupCount, filename string) {
        input := bufio.NewScanner(f)
        for input.Scan() {
                var tmp = counts[input.Text()]
                if tmp.count == 0 {
                        tmp.fileCount = make(map[string]int)
                }
                tmp.count++
                tmp.fileCount[filename]++
                counts[input.Text()] = tmp
        }
}

I am using the tmp variable in countLines to get around the inability to assign directly to values in maps as outlined in the Go Github repo.

Body:
I don't think it is particularly messy but I might be tempted to make some sort of addDupe helper function that takes a dupCount by value, makes whatever changes are required to add the line and returns the dupCount by value

func addDupe(dupes dupCount, filename string) dupCount {
    if dupes.count == 0 {
        dupes.fileCount = make(map[string]int)
    }
    dupes.fileCount[filename]++
    dupes.count++
    return dupes
}

This is similar to the way the standard append function for slices works. Then countLines can be written as:

func countLines(r io.Reader, counts map[string]dupCount, filename string) {
    input := bufio.NewScanner(r)
    for input.Scan() {
        line := input.Text()
        counts[line] = addDupe(counts[line], filename)
    }
}

But all I have done is replace your tmp with a function parameter.


问:
Android: How can I packed some shapes into one resource file?
I've made a few shapes in drawable folder, is it possible to packed them in one resource file? How?</p>

答:
u can take indivitual images and place them one after the other with the

android:layout_x="0px"
android:layout_y="6px" parameters..

but it is not possible by default in android


问:
CLR Procedure Not list in processes SQL Server
I created a CLR procedure to download email files. It works perfectly, the problem that when it is running it is not listed when I query the server processes.

Does anyone know a way to get it in sql server processes?

I'm using the query below

```<code>exec dbo.sp_download_files_mail
</code>```

答:
If you are expecting to see exec dbo.sp_download_files_mail in sys.dm_exec_sql_text via the sys.dm_exec_requests.plan_handle, then that's probably not going to happen. When you use EXEC it creates a sub-process that is probably a different execution plan. In the case of SQLCLR, SQL Server has no insight into what is happening unless you are executing T-SQL using SqlConnection, and then you will get the plan for the SQL being executed within the SQLCLR object and not the plan for the SQLCLR object itself. When you are executing a SQLCLR object and it is not executing any T-SQL statements, then both the sql_handle and plan_handle values are empty: 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.

However, you can see the SQLCLR object showing up in the plan_handle value coming back from sys.dm_exec_cached_plans. The SQLCLR object does seem to appear in this DMV upon being executed, but as this DMV reports cached objects, it does not necessarily get removed once the SQLCLR object completes. Hence, you can't use this DMV to indicate current running status of the object. Nor does the plan_handle value reported in sys.dm_exec_cached_plans show up in sys.dm_exec_requests while it is running.

You can test this behavior yourself by creating a SQLCLR Stored Procedure or SQLCLR scalar User-Defined Function that does nothing more than call System.Threading.Thread.Sleep() for at least 30 seconds. If you do not want to deal with creating this, a pre-made SQLCLR UDF – DB_WaitForDelay – exists in the Free version of the SQL# SQLCLR library (that I created) and is what I used in the example code below.

In SQL Server Management Studio (SSMS), open up two query tabs and paste in the following:

TAB 1

```<code>EXEC [SQL#].[DB_WaitForDelay] 30000, 1;
</code>```

TAB 2

```<code>SELECT txt.*, req.*
FROM sys.dm_exec_requests req
OUTER APPLY sys.dm_exec_sql_text(req.[plan_handle]) txt
WHERE req.[session_id] = <session_id_of_Tab1>;

DBCC INPUTBUFFER(<session_id_of_Tab1>);

SELECT txt.*, cp.*
FROM sys.dm_exec_cached_plans cp
OUTER APPLY sys.dm_exec_sql_text(cp.[plan_handle]) txt
WHERE cp.[cacheobjtype] LIKE N'CLR%';
</code>```

Once you have replaced the two instances of "<session_id_of_Tab1>" in the Tab 2 query, execute the Tab 1 query, then go back to Tab 2 and execute that batch of queries.

IF you really need to know if this SQLCLR object is executing as it is executing, then you will have to do something along the lines of using SqlConnection with a ConnectionString of Context Connection = true; and then execute (at the beginning of the SQLCLR object) something like SET CONTEXT_INFO 0x1234; (assuming that you are not already using CONTEXT_INFO for something else). At the end of the SQLCLR object, execute a 2nd SqlCommand for SET CONTEXT_INFO 0x00; to clear it out.

This approach allows you to use the following query to confirm that it is currently running:

```<code>SELECT req.*
FROM   sys.dm_exec_requests req
WHERE  req.[context_info] = 0x1234;
</code>```

Also, it is a rather bad practice to prefix Stored Procedure names with sp_ as that causes SQL Server to first check in [master] for the object and then the current Database. Using something like spDownloadEmailFiles is better, though still no real good reason to prefix Stored Procedure / Function / Table / View names with anything.

Body:
I created a CLR procedure to download email files. It works perfectly, the problem that when it is running it is not listed when I query the server processes.

Does anyone know a way to get it in sql server processes?

I'm using the query below

exec dbo.sp_download_files_mail

Body:
If you are expecting to see exec dbo.sp_download_files_mail in sys.dm_exec_sql_text via the sys.dm_exec_requests.plan_handle, then that's probably not going to happen. When you use EXEC it creates a sub-process that is probably a different execution plan. In the case of SQLCLR, SQL Server has no insight into what is happening unless you are executing T-SQL using SqlConnection, and then you will get the plan for the SQL being executed within the SQLCLR object and not the plan for the SQLCLR object itself. When you are executing a SQLCLR object and it is not executing any T-SQL statements, then both the sql_handle and plan_handle values are empty: 0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.

However, you can see the SQLCLR object showing up in the plan_handle value coming back from sys.dm_exec_cached_plans. The SQLCLR object does seem to appear in this DMV upon being executed, but as this DMV reports cached objects, it does not necessarily get removed once the SQLCLR object completes. Hence, you can't use this DMV to indicate current running status of the object. Nor does the plan_handle value reported in sys.dm_exec_cached_plans show up in sys.dm_exec_requests while it is running.

You can test this behavior yourself by creating a SQLCLR Stored Procedure or SQLCLR scalar User-Defined Function that does nothing more than call System.Threading.Thread.Sleep() for at least 30 seconds. If you do not want to deal with creating this, a pre-made SQLCLR UDF – DB_WaitForDelay – exists in the Free version of the SQL# SQLCLR library (that I created) and is what I used in the example code below.

In SQL Server Management Studio (SSMS), open up two query tabs and paste in the following:

TAB 1

EXEC [SQL#].[DB_WaitForDelay] 30000, 1;

TAB 2

SELECT txt.*, req.*
FROM sys.dm_exec_requests req
OUTER APPLY sys.dm_exec_sql_text(req.[plan_handle]) txt
WHERE req.[session_id] = <session_id_of_Tab1>;

DBCC INPUTBUFFER(<session_id_of_Tab1>);

SELECT txt.*, cp.*
FROM sys.dm_exec_cached_plans cp
OUTER APPLY sys.dm_exec_sql_text(cp.[plan_handle]) txt
WHERE cp.[cacheobjtype] LIKE N'CLR%';

Once you have replaced the two instances of "<session_id_of_Tab1>" in the Tab 2 query, execute the Tab 1 query, then go back to Tab 2 and execute that batch of queries.

IF you really need to know if this SQLCLR object is executing as it is executing, then you will have to do something along the lines of using SqlConnection with a ConnectionString of Context Connection = true; and then execute (at the beginning of the SQLCLR object) something like SET CONTEXT_INFO 0x1234; (assuming that you are not already using CONTEXT_INFO for something else). At the end of the SQLCLR object, execute a 2nd SqlCommand for SET CONTEXT_INFO 0x00; to clear it out.

This approach allows you to use the following query to confirm that it is currently running:

SELECT req.*
FROM   sys.dm_exec_requests req
WHERE  req.[context_info] = 0x1234;

Also, it is a rather bad practice to prefix Stored Procedure names with sp_ as that causes SQL Server to first check in [master] for the object and then the current Database. Using something like spDownloadEmailFiles is better, though still no real good reason to prefix Stored Procedure / Function / Table / View names with anything.


问:
Using Cassandra with PHP 7.1
From the research I've done, https://github.com/datastax/php-driver/ seems to be the best option for using Cassandra with PHP.

However when I try to install it, I get the error: pecl/cassandra requires PHP (version >= 5.6.0, version <= 7.0.99), installed version is 7.1.4-1+deb.sury.org~trusty+1

I tried installing https://github.com/aparkhomenko/php-cassandra but it didn't work, giving this error: warning: Could not find remote branch deprecated to clone.
fatal: Remote branch deprecated not found in upstream origin
Unexpected end of command stream

I tried http://evseevnn.github.io/php-cassandra-binary/ but it seems like Cassandra 3.1 isn't supported

Is there any way to use Cassandra with PHP 7.1? I'm willing to go back to PHP 7.0.x if necessary, but I'd like to avoid doing that if possible.

Thanks to anyone who can help

答: Currently the DataStax PHP driver for Apache Cassandra does not support PHP v7.1.x (only versions 5.6.x and 7.0.x). There is a JIRA ticket (PHP-155) to add support; contributions are always welcome.</p>

Title: Using Cassandra with PHP 7.1


问:
resources.ap_ does not exist when compile my android project
Compile Error:
Error generating final archive: java.io.FileNotFoundException: ..\bin\resources.ap_ does not exist.

Compile other simple sample works.
Same source file and project works on my college's machine.

Any tips ? Why resources.ap_ doesn't get generated ?

答: Did you do a Project > Clean? If that doesn't work, try forcing Eclipse to build the project again. Restart Eclipse if that still doesn't work.


问:
Yahoo finance.yahoo.com/quotes is redirecting
I use https://finance.yahoo.com/quotes/... for stock quotes and option data.  It continues to work well when viewed in a Safari browser.  I also take it in to an Objective C app as an NSURLSession dataTaskWithUrL.  Last week (circa April 28, 2017)it started forcing a redirect by calling willPerformHTTPRedirection: but the redirect loops to itself and generates the "too many HTTP redirects" error. </p>

<p>Does anyone have a workaround for this?  </p>

答:
Based on the work of 2 other people I seem to have a solution to this problem.  Actually there are 2 aspects to the issue of downloading historic data from Yahoo:

The redirection issue

Establishing a working cookie/crumb combination.

The solution which enables me to continue using my Excel spreadsheets and the associated VBA code is based on:

The work of Dennis Lee who demonstrates how to extract the cookie / crumb combination https://github.com/dennislwy/YahooFinanceAPI.

The work of Tim Hall who has written VBA-Web
https://vba-tools.github.io/VBA-Web/docs/#/WebClient/GetFullUrl

Body:
I use https://finance.yahoo.com/quotes/... for stock quotes and option data.  It continues to work well when viewed in a Safari browser.  I also take it in to an Objective C app as an NSURLSession dataTaskWithUrL.  Last week (circa April 28, 2017)it started forcing a redirect by calling willPerformHTTPRedirection: but the redirect loops to itself and generates the "too many HTTP redirects" error.

Does anyone have a workaround for this?


问:
C# Visual Studio 2015: IWebProxy certificate validation
I'm trying to create a C# proxy DLL that allow VS2015 Community, on my offline workstation, access to internet through a corporate HTTP proxy with authentication.

Following instruction of this MSDN blog post  I'm able to connect VisualStudio to HTTP pages in this way:

```<code>namespace VSProxy
{
    public class AuthProxyModule : IWebProxy
    {
        ICredentials crendential = new NetworkCredential("user", "password");

        public ICredentials Credentials
        {
            get
            {
                return crendential;
            }
            set
            {
                crendential = value;
            }
        }

        public Uri GetProxy(Uri destination)
        {
            ServicePointManager.ServerCertificateValidationCallback = (Header, Cer, Claim, SslPolicyErrors) => true;
            return new Uri("http://128.16.0.123:1234", UriKind.Absolute);
        }

        public bool IsBypassed(Uri host)
        {
            return host.IsLoopback;
        }
    }
}
</code>```

But I'm not able to connect to the account authentication page for Visual Studio Community access.

So, I'm trying to validate Microsoft certificate using DLL.

There is any way can I accomplish HTTPS and certificate issue?

How can I validate the certificate in the webProxy DLL?

答: ServicePointManager.ServerCertificateValidationCallback Is the main access for network certificate validation on .Net if you wish to validate a certificate you must do it here. What I suggest you is to bind the callback somewhere else than inside the GetProxy method. Put it where you initialize the proxy and the perform your certificate validation there.

Body:
I'm trying to create a C# proxy DLL that allow VS2015 Community, on my offline workstation, access to internet through a corporate HTTP proxy with authentication.

Following instruction of this MSDN blog post  I'm able to connect VisualStudio to HTTP pages in this way:

namespace VSProxy
{
    public class AuthProxyModule : IWebProxy
    {
        ICredentials crendential = new NetworkCredential("user", "password");

        public ICredentials Credentials
        {
            get
            {
                return crendential;
            }
            set
            {
                crendential = value;
            }
        }

        public Uri GetProxy(Uri destination)
        {
            ServicePointManager.ServerCertificateValidationCallback = (Header, Cer, Claim, SslPolicyErrors) => true;
            return new Uri("http://128.16.0.123:1234", UriKind.Absolute);
        }

        public bool IsBypassed(Uri host)
        {
            return host.IsLoopback;
        }
    }
}

But I'm not able to connect to the account authentication page for Visual Studio Community access.

So, I'm trying to validate Microsoft certificate using DLL.

There is any way can I accomplish HTTPS and certificate issue?

How can I validate the certificate in the webProxy DLL?


问:
Unexplained behaviour of Guile's make-c-struct of (system foreign)
Guile accepts the following code:

```<code>(use-modules (system foreign))
(define ptr (make-c-struct (list int int) '(300 43)))
</code>```

However, it throws an error when the second line is replaced by:

```<code>(define ptr (make-c-struct '(int int) '(300 43)))
</code>```

Is someone be able to infer what the issue could be?

```<code>$ guile --version
guile (GNU Guile) 2.0.13

$ uname -a
Linux <host> 4.8.0-1-amd64 #1 SMP Debian 4.8.5-1 (2016-10-28) x86_64 GNU/Linux

Backtrace:
In ice-9/boot-9.scm:
 160: 8 [catch #t #<catch-closure 55b8628b8600> ...]
In unknown file:
   ?: 7 [apply-smob/1 #<catch-closure 55b8628b8600>]
In ice-9/boot-9.scm:
  66: 6 [call-with-prompt prompt0 ...]
In ice-9/eval.scm:
 432: 5 [eval # #]
In ice-9/boot-9.scm:
2404: 4 [save-module-excursion #<procedure 55b8628d89c0 at ice-9/boot-9.scm:4051:3 ()>]
4058: 3 [#<procedure 55b8628d89c0 at ice-9/boot-9.scm:4051:3 ()>]
In /home/<user>/path/tofile.scm:
   7: 2 [#<procedure 55b862cf46c0 ()>]
In system/foreign.scm:
 158: 1 [make-c-struct (int int) (300 43)]
In unknown file:
   ?: 0 [sizeof (int int)]

ERROR: In procedure sizeof:
ERROR: In procedure alignof: Wrong type argument in position 1: int
</code>```

答:
This:

```<code>(list int int)
</code>```

Creates a list with the previously defined int value as elements, whereas this:

```<code>'(int int)
</code>```

Creates a list with two symbols as elements, they're not equivalent, remember that a single quote is a shorthand for (quote (int int)), not for (list int int).

Body:
Guile accepts the following code:

(use-modules (system foreign))
(define ptr (make-c-struct (list int int) '(300 43)))

However, it throws an error when the second line is replaced by:

(define ptr (make-c-struct '(int int) '(300 43)))

Is someone be able to infer what the issue could be?

$ guile --version
guile (GNU Guile) 2.0.13

$ uname -a
Linux <host> 4.8.0-1-amd64 #1 SMP Debian 4.8.5-1 (2016-10-28) x86_64 GNU/Linux

Backtrace:
In ice-9/boot-9.scm:
 160: 8 [catch #t #<catch-closure 55b8628b8600> ...]
In unknown file:
   ?: 7 [apply-smob/1 #<catch-closure 55b8628b8600>]
In ice-9/boot-9.scm:
  66: 6 [call-with-prompt prompt0 ...]
In ice-9/eval.scm:
 432: 5 [eval # #]
In ice-9/boot-9.scm:
2404: 4 [save-module-excursion #<procedure 55b8628d89c0 at ice-9/boot-9.scm:4051:3 ()>]
4058: 3 [#<procedure 55b8628d89c0 at ice-9/boot-9.scm:4051:3 ()>]
In /home/<user>/path/tofile.scm:
   7: 2 [#<procedure 55b862cf46c0 ()>]
In system/foreign.scm:
 158: 1 [make-c-struct (int int) (300 43)]
In unknown file:
   ?: 0 [sizeof (int int)]

ERROR: In procedure sizeof:
ERROR: In procedure alignof: Wrong type argument in position 1: int

Body:
This:

(list int int)

Creates a list with the previously defined int value as elements, whereas this:

'(int int)

Creates a list with two symbols as elements, they're not equivalent, remember that a single quote is a shorthand for (quote (int int)), not for (list int int).


问:
Actionscript 3 remove child at point
hi i'm new to AS3 and i was wondering what is the best way to remove a child at a point.
i tried

```<code>Holder.removeChild(Holder.getObjectsUnderPoint(new Point(exampleX, exampleY))[0]);
</code>```

however that returned ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

any suggestions?

答:
I don´t know why Patricks version does not work. Here is an alternative (ugly code) solution using the parent of the clip. </p>

```<code>var clips : Array =  _container.getObjectsUnderPoint(_point);

for each(var clip : DisplayObject in clips)
{
    clip.parent.removeChild(clip);
}
</code>```

Title: Actionscript 3 remove child at point

Body:
hi i'm new to AS3 and i was wondering what is the best way to remove a child at a point.
i tried

Holder.removeChild(Holder.getObjectsUnderPoint(new Point(exampleX, exampleY))[0]);

however that returned ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

any suggestions?

Body:
I don´t know why Patricks version does not work. Here is an alternative (ugly code) solution using the parent of the clip.

var clips : Array =  _container.getObjectsUnderPoint(_point);

for each(var clip : DisplayObject in clips)
{
    clip.parent.removeChild(clip);
}


问:
Closing Angular2 modal on click outside the modal
This is the Sample code to have click outside to disable the selection. In this example I am able to deselect but only after I click on the element to activate the listener. I want to use this example to close the modal on click outside of the modal anytime. Any example would be appreciated.

```<code>activeIndex = 0;

subscription: any;
init$: Subject<any> = new Subject();
stop$: Subject<any> = new Subject();

ngOnInit() {
  let click$ = Observable.fromEvent(document, 'click');

const clickOutside$ = this.init$.flatMap(() => {
  return click$.takeUntil(this.stop$);
});

this.subscription = clickOutside$.subscribe(() => {
  this.activeIndex = null;
  console.log(1);
  this.stop$.next();
});
}

onItemClicked(event, index: number) {
event.stopPropagation()
this.activeIndex = index;
this.init$.next()
}

ngOnDestroy() {
if(this.subscription) {
  this.subscription.unsubscribe();
}
}
</code>```

http://plnkr.co/edit/lx9eBU?p=preview

答:
So I have an example of how I handled closing a custom dropdown that I created but I believe it will work for this as well.

So inside of your component:

```<code>openModal() { document.addEventListener('click', this.offClickHandler.bind(this)); }

offClickHandler(event:any) {
    if (!event.target.closest(".select-options") && !event.target.closest(".select-input")) {
        // do whatever you want here
        // close the modal
        // call document.removeEventListener
    }
}
</code>```

So that will look for a click outside of button and div, but for you I would just set the .closest() to the modal you want to see closed. Then inside the if statement close your modal.

Body:
This is the Sample code to have click outside to disable the selection. In this example I am able to deselect but only after I click on the element to activate the listener. I want to use this example to close the modal on click outside of the modal anytime. Any example would be appreciated.

activeIndex = 0;

subscription: any;
init$: Subject<any> = new Subject();
stop$: Subject<any> = new Subject();

ngOnInit() {
  let click$ = Observable.fromEvent(document, 'click');

const clickOutside$ = this.init$.flatMap(() => {
  return click$.takeUntil(this.stop$);
});

this.subscription = clickOutside$.subscribe(() => {
  this.activeIndex = null;
  console.log(1);
  this.stop$.next();
});
}

onItemClicked(event, index: number) {
event.stopPropagation()
this.activeIndex = index;
this.init$.next()
}

ngOnDestroy() {
if(this.subscription) {
  this.subscription.unsubscribe();
}
}

http://plnkr.co/edit/lx9eBU?p=preview

Body:
So I have an example of how I handled closing a custom dropdown that I created but I believe it will work for this as well.

So inside of your component:

openModal() { document.addEventListener('click', this.offClickHandler.bind(this)); }

offClickHandler(event:any) {
    if (!event.target.closest(".select-options") && !event.target.closest(".select-input")) {
        // do whatever you want here
        // close the modal
        // call document.removeEventListener
    }
}

So that will look for a click outside of button and div, but for you I would just set the .closest() to the modal you want to see closed. Then inside the if statement close your modal.