问:
Why is Auth0.js giving me payload validation errors "None of the valid schemas were met" and "Missing required property" on Passwordless/Verify?
My SPA Client is using the Auth0.js Passwordless Start/Verify flow to authenticate users. My auth callback page is receiving the below Payload Validation Error. I have verified the user exists for the SMS connection in the Auth0 Dashboard and that the SPA Client has the SMS connection enabled.

Error:

```<code>https://localhost:9001/auth/callback#error=access_denied&error_description=
Payload%20validation%20error%253A%20'None%20of%20the%20valid%20schemas%20were%20met'
.%20Inner%20errors%253A%20%5B%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20blocked'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20email_verified'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20email'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20verify_email'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20phone_number'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20phone_verified'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20verify_phone_number'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20password'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20verify_password'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20user_metadata'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20app_metadata'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20username'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20client_id'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20groups'
.%20%5D.&state=statehash
</code>```

Auth0 Initialization:

```<code>this.auth0 = new auth0.WebAuth({
                audience: `https://${authSettings.domain}/userinfo`,
                clientID: authSettings.checkoutClientId,
                domain: authSettings.domain,
                redirectUri: authSettings.checkoutCallbackUrl,
                responseType: 'token id_token',
                scope: 'openid email profile'
            });
</code>```

Passwordless Start:

```<code>this.auth0.passwordlessStart({
        connection: 'sms',
        send: 'code',
        phoneNumber: phoneNumber,
        authParams: {
          responseType: 'token id_token',
          scope: 'openid email profile'
        }
      }
</code>```

Passwordless Verify:

```<code>this.auth0.passwordlessVerify({
          connection: 'sms',
          phoneNumber: phoneNumber,
          verificationCode: confirmationCode,
          type: 'sms',
          authParams: {
            responseType: 'token id_token',
            scope: 'openid email profile'
          }
        }
</code>```

The "missing required parameters" don't even make sense for a call to passwordless/verify.

答:
Turns out the error was actually being thrown inside a custom Auth0 Rule but was only surfacing via the auth callback.

Specifically, we had a rule that called auth0.users.updateAppMetadata and auth0.users.updateUserMetadata which apparently do not work with Passwordless SMS connections.

Body:
My SPA Client is using the Auth0.js Passwordless Start/Verify flow to authenticate users. My auth callback page is receiving the below Payload Validation Error. I have verified the user exists for the SMS connection in the Auth0 Dashboard and that the SPA Client has the SMS connection enabled.

Error:

https://localhost:9001/auth/callback#error=access_denied&error_description=
Payload%20validation%20error%253A%20'None%20of%20the%20valid%20schemas%20were%20met'
.%20Inner%20errors%253A%20%5B%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20blocked'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20email_verified'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20email'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20verify_email'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20phone_number'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20phone_verified'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20verify_phone_number'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20password'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20verify_password'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20user_metadata'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20app_metadata'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20username'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20client_id'
.%20(also)%20Payload%20validation%20error%253A%20'Missing%20required%20property%253A%20groups'
.%20%5D.&state=statehash

Auth0 Initialization:

this.auth0 = new auth0.WebAuth({
                audience: `https://${authSettings.domain}/userinfo`,
                clientID: authSettings.checkoutClientId,
                domain: authSettings.domain,
                redirectUri: authSettings.checkoutCallbackUrl,
                responseType: 'token id_token',
                scope: 'openid email profile'
            });

Passwordless Start:

this.auth0.passwordlessStart({
        connection: 'sms',
        send: 'code',
        phoneNumber: phoneNumber,
        authParams: {
          responseType: 'token id_token',
          scope: 'openid email profile'
        }
      }

Passwordless Verify:

this.auth0.passwordlessVerify({
          connection: 'sms',
          phoneNumber: phoneNumber,
          verificationCode: confirmationCode,
          type: 'sms',
          authParams: {
            responseType: 'token id_token',
            scope: 'openid email profile'
          }
        }

The "missing required parameters" don't even make sense for a call to passwordless/verify.


来源: stackexchange

问:
open graph Meta Tags in Vue JS don't show image
I design a blog and I would like that when sharing to social networks, the preview image displays like in Medium's posts

```<code><meta property="og:image" content="https://medium.com/js-dojo/getting-your-head-around-vue-js-scoped-slots-281bf82a1e4e"/>
</code>```

I using vuejs2 with webpack and vue-meta to change the dynamic image of my post.
 But for Facebook, there don't working even when I put them in index.html.

I find this article on medium  where it is said that it is necessary to use Server Side Rendered, but it is not said how to migrate from a totally designed project with a basic configuration (without SSR) to a project solving the problem. already the architecture is different and I have no reference

here is my code vue-meta

```<code>metaInfo () {
  return {
    title: '41devs | blog',
    titleTemplate: '%s - le titre',
    meta: [
      {name: 'viewport', content: 'user-scalable=no'},
      {property: 'og:title', content: 'title'},
      {property: 'og:type', content: 'article'},
      {property: 'og:url', content: 'http://c5e3b0ec.ngrok.io/blog/s'},// here it is just ngrok for my test
      {property: 'og:description', content: 'description'},
      {property: 'og:image', content: 'https://firebasestorage.googleapis.com/v0/b/dev-blog-2503f.appspot.com/o/postsStorage%2F-KxXdvvLqDHBcxdUfLgn%2Fonfleck?alt=media&token=24a9bf5b-dce2-46e8-b175-fb63f7501c98'},
      {property: 'twitter:image:src', content: 'https://firebasestorage.googleapis.com/v0/b/dev-blog-2503f.appspot.com/o/postsStorage%2F-KxXdvvLqDHBcxdUfLgn%2Fonfleck?alt=media&token=24a9bf5b-dce2-46e8-b175-fb63f7501c98'},
      {property: 'og:image:width', content: '1000'},
      {property: 'og:site_name', content: '41devs | blog'}
    ]
  }
}
</code>```

答:
When Facebook checks your page to find the meta data, they don't run your Javascript.  Vue never runs, your tags are never replaced.  This is a limitation of Facebook's crawler.

This means you would indeed have to render those tags at the server level, whether by Vue's server side rendering or by some other method (I don't know what type of server you are running).  But yes, ultimately, you must be able to hard-code this value into your server response, otherwise it won't display in Facebook.

ContentLicense: CC BY-SA 4.0

Body:
I design a blog and I would like that when sharing to social networks, the preview image displays like in Medium's posts

<meta property="og:image" content="https://medium.com/js-dojo/getting-your-head-around-vue-js-scoped-slots-281bf82a1e4e"/>

I using vuejs2 with webpack and vue-meta to change the dynamic image of my post.
 But for Facebook, there don't working even when I put them in index.html.

I find this article on medium  where it is said that it is necessary to use Server Side Rendered, but it is not said how to migrate from a totally designed project with a basic configuration (without SSR) to a project solving the problem. already the architecture is different and I have no reference

here is my code vue-meta

metaInfo () {
  return {
    title: '41devs | blog',
    titleTemplate: '%s - le titre',
    meta: [
      {name: 'viewport', content: 'user-scalable=no'},
      {property: 'og:title', content: 'title'},
      {property: 'og:type', content: 'article'},
      {property: 'og:url', content: 'http://c5e3b0ec.ngrok.io/blog/s'},// here it is just ngrok for my test
      {property: 'og:description', content: 'description'},
      {property: 'og:image', content: 'https://firebasestorage.googleapis.com/v0/b/dev-blog-2503f.appspot.com/o/postsStorage%2F-KxXdvvLqDHBcxdUfLgn%2Fonfleck?alt=media&token=24a9bf5b-dce2-46e8-b175-fb63f7501c98'},
      {property: 'twitter:image:src', content: 'https://firebasestorage.googleapis.com/v0/b/dev-blog-2503f.appspot.com/o/postsStorage%2F-KxXdvvLqDHBcxdUfLgn%2Fonfleck?alt=media&token=24a9bf5b-dce2-46e8-b175-fb63f7501c98'},
      {property: 'og:image:width', content: '1000'},
      {property: 'og:site_name', content: '41devs | blog'}
    ]
  }
}

ContentLicense: CC BY-SA 3.0


问:
PHP - json_decode from url to variables
i had this url

```<code> https://poloniex.com/public?command=returnTicker
</code>```

thats the json output of the first 2 (for example)

```<code> {"BTC_BCN":{"id":7,"last":"0.00000018","lowestAsk":"0.00000018","highestBid":"0.00000017","percentChange":"0.00000000","baseVolume":"58.73610647","quoteVolume":"328275043.97652394","isFrozen":"0","high24hr":"0.00000019","low24hr":"0.00000017"},"BTC_BELA":{"id":8,"last":"0.00001191","lowestAsk":"0.00001191","highestBid":"0.00001174","percentChange":"0.13536701","baseVolume":"6.33896473","quoteVolume":"572949.02508918","isFrozen":"0","high24hr":"0.00001200","low24hr":"0.00001033"},
</code>```

now i want to get all datas to varialbles. Like... $curreny = xxx; $last = xxx,..

i have tried it with that..

```<code>$url = "https://poloniex.com/public?command=returnTicker";
$response = file_get_contents($url);
$obj = json_decode($response,true);
$keys = array_keys((array)$obj);

foreach($keys as $result) {
$marketname = $result; }
</code>```

that works for the first level .
then i get a list of all currencies. But.. how can i get all other data to the currency?

a second foreach? like..

```<code> foreach($result[$marketname] as $result2) { }
</code>```

doesn't make sense, i think!?

i would like to have it in that form

$currency = BTC_BCN;
$last = 0.00003223;
and so on..

Any idea?

答:
```<code><?php
$url = "https://poloniex.com/public?command=returnTicker";
$response = file_get_contents($url);
$obj = json_decode($response,true);
$keys = array_keys((array)$obj);
for($i=0;$i<count($keys);$i++)
{
    echo 'Currency <strong>'.$keys[$i].'</strong>, last <strong>'.$obj[$keys[$i]]['last'].'</strong><br>';
}
?>
</code>```

You already done all job of getting the information, just needed to use it :D

Use print_r($variable) to see what you have in an array and what indexes it has.

Title: PHP - json_decode from url to variables

Body:
i had this url

 https://poloniex.com/public?command=returnTicker

thats the json output of the first 2 (for example)

 {"BTC_BCN":{"id":7,"last":"0.00000018","lowestAsk":"0.00000018","highestBid":"0.00000017","percentChange":"0.00000000","baseVolume":"58.73610647","quoteVolume":"328275043.97652394","isFrozen":"0","high24hr":"0.00000019","low24hr":"0.00000017"},"BTC_BELA":{"id":8,"last":"0.00001191","lowestAsk":"0.00001191","highestBid":"0.00001174","percentChange":"0.13536701","baseVolume":"6.33896473","quoteVolume":"572949.02508918","isFrozen":"0","high24hr":"0.00001200","low24hr":"0.00001033"},

now i want to get all datas to varialbles. Like... $curreny = xxx; $last = xxx,..

i have tried it with that..

$url = "https://poloniex.com/public?command=returnTicker";
$response = file_get_contents($url);
$obj = json_decode($response,true);
$keys = array_keys((array)$obj);

foreach($keys as $result) {
$marketname = $result; }

that works for the first level .
then i get a list of all currencies. But.. how can i get all other data to the currency?

a second foreach? like..

 foreach($result[$marketname] as $result2) { }

doesn't make sense, i think!?

i would like to have it in that form

$currency = BTC_BCN;
$last = 0.00003223;
and so on..

Any idea?

Body:
<?php
$url = "https://poloniex.com/public?command=returnTicker";
$response = file_get_contents($url);
$obj = json_decode($response,true);
$keys = array_keys((array)$obj);
for($i=0;$i<count($keys);$i++)
{
    echo 'Currency <strong>'.$keys[$i].'</strong>, last <strong>'.$obj[$keys[$i]]['last'].'</strong><br>';
}
?>

You already done all job of getting the information, just needed to use it :D

Use print_r($variable) to see what you have in an array and what indexes it has.


问:
How do I add a custom button to Outlook's reminders dialog?
I have a custom Outlook AddIn, and would like to add a custom button to the reminders dialog, like Skype for business does with their meetings.

Example of Skype's "Join Online" button

Example of where I'd like my custom button

I would like the ability for the user to click the custom button and a dynamic  web page to load (https://example.com/appt/123)

Thank you for your help!

答: There is no officially supported way to do that. You can of course hack something using straight Windows API on the HWND level. I don't think you'd be able to do that in .Net.</p>


问:
why SHA changed but commit message stays the same
I'm exploring git and did something that results in a strange behavior. As git log shows below, the 2nd commit's SHA hash has changed but the message stays the same. Could someone please point out to me how to find the differences between the 2nd commit of yesterday and today? Thank you

```<code>TODAY:
* 09ed1fc (HEAD -> master) third commit
* 0d7f23f second commit
* c02a2ea first commit

YESTERDAY:
* 8e5cf1e second commit
* c02a2ea first commit
</code>```

What puzzles me is that the 2 different commits for the 2nd commit (8e5cf1e and 0d7f23f) were created at the same time:

```<code>>git log -1 8e5cf1e
commit 8e5cf1ea4fae4a9568b5e8c1622b63efd0e5b27f
Author: Me
Date:   Sun Dec 3 11:30:40 2017 -0500

    second commit

>git log -1 0d7f23f
commit 0d7f23fb8dd1db6728579eae0c8c272a17b6ad40
Author: Me
Date:   Sun Dec 3 11:30:40 2017 -0500

    second commit
</code>```

答: You should be able to do a git diff 0d7f23f 8e5cf1e to see the changes. The SHA may have changed due to a rebase, an amended commit, or a few other reasons.

Body:
I'm exploring git and did something that results in a strange behavior. As git log shows below, the 2nd commit's SHA hash has changed but the message stays the same. Could someone please point out to me how to find the differences between the 2nd commit of yesterday and today? Thank you

TODAY:
* 09ed1fc (HEAD -> master) third commit
* 0d7f23f second commit
* c02a2ea first commit

YESTERDAY:
* 8e5cf1e second commit
* c02a2ea first commit

What puzzles me is that the 2 different commits for the 2nd commit (8e5cf1e and 0d7f23f) were created at the same time:

>git log -1 8e5cf1e
commit 8e5cf1ea4fae4a9568b5e8c1622b63efd0e5b27f
Author: Me
Date:   Sun Dec 3 11:30:40 2017 -0500

    second commit

>git log -1 0d7f23f
commit 0d7f23fb8dd1db6728579eae0c8c272a17b6ad40
Author: Me
Date:   Sun Dec 3 11:30:40 2017 -0500

    second commit


问:
Wait for the UI to redraw before "taking a screenshot" of it

The challenge

I'm trying to create a Window that'll draw a card on a page of a PDF document.

The idea is to receive a collection (of the items that should be drawn on the card), then go through them, and for each of the items, load it to a UniformGrid (to give the impression of a actual card), capture an image of the screen and draw it to a page of a PDF document.

So far so good.

What I've tried (and partially succeeded)

Here's what I've tried:

(the following code was added to a Loaded event handler of the window)

```<code>PdfDocument document = new PdfDocument();

// This is just an example
int[][] items = new int[10][];

// Fill the matrix

foreach (int[] array in items)
{
    Dispatcher.Invoke(() =>
    {
        // uGrid is an UniformGrid
        uGrid.Children.Clear();

        foreach (int id in array)
        {
            Border child = null;

            // Create child element and add it to the Uniform Grid

            uGrid.Children.Add(child);
        }
    });

    Dispatcher.Invoke(new Action(() =>
    {
        // Draws an image of 'this' to the PDFDocument 'document'
        PdfHelper.DrawPictureOfControlToPdf(document, this);

        // DispatcherPriority.ContextIdle here is responsible for executing the DrawPicture method only after the uGrid has been redrawed
    }), DispatcherPriority.ContextIdle, null);

}

// This will save the PDF on your documents folder
document.Save(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyTestPDF.pdf"));
</code>```

A full (but very short, I promise) working example can be found on my GitHub

Also, the produced PDFs (when debugging and when not - see problem below), can be found here

The problem

The above code works great when on debugging mode.

When debugging: the code runs without errors, the PDF is created with the correct number of pages, and the cards are correctly drawn on it.

When not: the code runs without errors, the PDF is created with the correct number of pages, but the cards are not drawn on it.

I think that what's causing the issue is the DispatcherPriority.ContextIdle on the following piece of code:

```<code>Dispatcher.Invoke(new Action(() =>
{
    PdfHelper.DrawPictureOfControlToPdf(document, this);

}), DispatcherPriority.ContextIdle, null);
</code>```

It should indicate that the Action must only be run when the UniformGrid finished redrawing (or after the Dispatcher took care of it, more precisely). But apparently this only works inside debugging mode.

Does someone know how to solve this?

If not, is there any alternative that I'm not thinking of?

@EDIT

I don't think this is important, but I'm using PDFSharp to generate/handle the PDF

答:
Remove all Dispatcher.Invoke in your code (they are not doing anything good here), and then call

```<code>this.UpdateLayout();
</code>```

to force redraw of current control, before calling PdfHelper.DrawPictureOfControlToPdf(document, this);.

Body:
The challenge

I'm trying to create a Window that'll draw a card on a page of a PDF document.

The idea is to receive a collection (of the items that should be drawn on the card), then go through them, and for each of the items, load it to a UniformGrid (to give the impression of a actual card), capture an image of the screen and draw it to a page of a PDF document.

So far so good.

What I've tried (and partially succeeded)

Here's what I've tried:

(the following code was added to a Loaded event handler of the window)

PdfDocument document = new PdfDocument();

// This is just an example
int[][] items = new int[10][];

// Fill the matrix

foreach (int[] array in items)
{
    Dispatcher.Invoke(() =>
    {
        // uGrid is an UniformGrid
        uGrid.Children.Clear();

        foreach (int id in array)
        {
            Border child = null;

            // Create child element and add it to the Uniform Grid

            uGrid.Children.Add(child);
        }
    });

    Dispatcher.Invoke(new Action(() =>
    {
        // Draws an image of 'this' to the PDFDocument 'document'
        PdfHelper.DrawPictureOfControlToPdf(document, this);

        // DispatcherPriority.ContextIdle here is responsible for executing the DrawPicture method only after the uGrid has been redrawed
    }), DispatcherPriority.ContextIdle, null);

}

// This will save the PDF on your documents folder
document.Save(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyTestPDF.pdf"));

A full (but very short, I promise) working example can be found on my GitHub

Also, the produced PDFs (when debugging and when not - see problem below), can be found here

The problem

The above code works great when on debugging mode.

When debugging: the code runs without errors, the PDF is created with the correct number of pages, and the cards are correctly drawn on it.

When not: the code runs without errors, the PDF is created with the correct number of pages, but the cards are not drawn on it.

I think that what's causing the issue is the DispatcherPriority.ContextIdle on the following piece of code:

Dispatcher.Invoke(new Action(() =>
{
    PdfHelper.DrawPictureOfControlToPdf(document, this);

}), DispatcherPriority.ContextIdle, null);

It should indicate that the Action must only be run when the UniformGrid finished redrawing (or after the Dispatcher took care of it, more precisely). But apparently this only works inside debugging mode.

Does someone know how to solve this?

If not, is there any alternative that I'm not thinking of?

@EDIT

I don't think this is important, but I'm using PDFSharp to generate/handle the PDF

Body:
Remove all Dispatcher.Invoke in your code (they are not doing anything good here), and then call

this.UpdateLayout();

to force redraw of current control, before calling PdfHelper.DrawPictureOfControlToPdf(document, this);.


问:
c# sql server backup percent read
sql command

```<code>BACKUP DATABASE [databasesample] TO  DISK = N'D:\kkk\test.bat' WITH  INIT ,  NOUNLOAD ,
NAME = N'name test',  NOSKIP ,
STATS = 5,  DESCRIPTION = N'test',  NOFORMAT
</code>```

result

```<code>5 percent processed.
10 percent processed.
15 percent processed.
20 percent processed.
25 percent processed.
30 percent processed.
35 percent processed.
40 percent processed.
45 percent processed.
50 percent processed.
55 percent processed.
60 percent processed.
65 percent processed.
70 percent processed.
75 percent processed.
80 percent processed.
85 percent processed.
90 percent processed.
95 percent processed.
Processed 30960 pages for database 'databasesample', file 'sample_Data' on file 1.
100 percent processed.
</code>```

I want to catch the percentage with C#. I think BeginExecuteNonQuery() function is done. but I do not know exactly how. Suggestions?

答:
What shaunmartin said!

Last time I did this, I used code somewhat like this. YMMV.

```<code>  Server server = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection));

  // Create a backup device
  Backup backup = new Backup();
  backup.Action = BackupActionType.Database;
  backup.Database = database;
  backup.Incremental = false;
  backup.Initialize = true;

  BackupDeviceItem backupDeviceItem = new BackupDeviceItem(backupPath, DeviceType.File);
  backup.Devices.Add(backupDeviceItem);

  backup.PercentCompleteNotification = 1;
  backup.Information += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(backup_Information);
  backup.PercentComplete += new PercentCompleteEventHandler(backup_PercentComplete);
  backup.Complete += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(backup_Complete);

  backup.SqlBackupAsync(server);
</code>```

ContentLicense: CC BY-SA 2.5

Title: c# sql server backup percent read

Body:
sql command

BACKUP DATABASE [databasesample] TO  DISK = N'D:\kkk\test.bat' WITH  INIT ,  NOUNLOAD ,
NAME = N'name test',  NOSKIP ,
STATS = 5,  DESCRIPTION = N'test',  NOFORMAT

result

5 percent processed.
10 percent processed.
15 percent processed.
20 percent processed.
25 percent processed.
30 percent processed.
35 percent processed.
40 percent processed.
45 percent processed.
50 percent processed.
55 percent processed.
60 percent processed.
65 percent processed.
70 percent processed.
75 percent processed.
80 percent processed.
85 percent processed.
90 percent processed.
95 percent processed.
Processed 30960 pages for database 'databasesample', file 'sample_Data' on file 1.
100 percent processed.

I want to catch the percentage with C#. I think BeginExecuteNonQuery() function is done. but I do not know exactly how. Suggestions?

Body:
What shaunmartin said!

Last time I did this, I used code somewhat like this. YMMV.

  Server server = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection));

  // Create a backup device
  Backup backup = new Backup();
  backup.Action = BackupActionType.Database;
  backup.Database = database;
  backup.Incremental = false;
  backup.Initialize = true;

  BackupDeviceItem backupDeviceItem = new BackupDeviceItem(backupPath, DeviceType.File);
  backup.Devices.Add(backupDeviceItem);

  backup.PercentCompleteNotification = 1;
  backup.Information += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(backup_Information);
  backup.PercentComplete += new PercentCompleteEventHandler(backup_PercentComplete);
  backup.Complete += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(backup_Complete);

  backup.SqlBackupAsync(server);


问:
Filter using Underscore.js
I need to filter the JSON above using Underscore.js

How can I return just the items that "Balance" is different from 0

{
 Currency: 'BCC',
 Balance: 0,
 Available: 0,
 Pending: 0,
 CryptoAddress: null
}, {
 Currency: 'BLOCK',
 Balance: 0,
 Available: 0,
 Pending: 0,
 CryptoAddress: 'Bd24akqYDG97k6xmUqsnxAtrBRoXeffQhx'
}, {
 Currency: 'BTC',
 Balance: 0.00153928,
 Available: 0.00153928,
 Pending: 0,
 CryptoAddress: '1BgWkjF1mwe1MZoCvxMmfSJ6fppNMD5GSx'
}, {
 Currency: 'BTG',
 Balance: 2e-8,
 Available: 2e-8,
 Pending: 0,
 CryptoAddress: null
}```

答:
Here's a codepen example:

https://codepen.io/anon/pen/EbMRKY?editors=1111

```<code>let filtered = _.filter(transactions, (transaction) => {
 return transaction.Balance !== 0;
})
</code>```

Title: Filter using Underscore.js

Body:
Here's a codepen example:

https://codepen.io/anon/pen/EbMRKY?editors=1111

let filtered = _.filter(transactions, (transaction) => {
 return transaction.Balance !== 0;
})


问:
Android Studio recognizes physical Device as Null?
I've been developing an Android Application for Android (SDK min version 14) and I have testing it normally with tablets such as Samsung Galaxy 2 and Nexus 7.
However when I tried to run the application (by clicking run in AndroidStudio), AS does not recognise the tablet information, which is shown in the picture below.

The interesting thing is that as shown in the picture above, AS is also detecting the device sdk as API 1 when it's Android version is 4.2.2
The tablet is already set to accept "USB debugging" in the developer options, I'have tried rebooting the tablet, and restarting AS, but still I get the same problem(everything is fine with nexus 7 and Samsung Galaxy 2).

The tablet/device I'm working on is a "VeryKool" T742

```<code>Environment information:
 OS: ubuntu
 AndroidStudio version: 0.8.6

 Tablet Android version:4.2.2
 Tablet Kernel version: 3.4.5
 App min SDK: 14
</code>```

答:
On Ubuntu, with my Pixel XL on 8.0, I had to do this while plugged into computer:

Settings -> Connected Devices -> USB --> Change to 'Transferring Files'

Body:
I've been developing an Android Application for Android (SDK min version 14) and I have testing it normally with tablets such as Samsung Galaxy 2 and Nexus 7.
However when I tried to run the application (by clicking run in AndroidStudio), AS does not recognise the tablet information, which is shown in the picture below.

The interesting thing is that as shown in the picture above, AS is also detecting the device sdk as API 1 when it's Android version is 4.2.2
The tablet is already set to accept "USB debugging" in the developer options, I'have tried rebooting the tablet, and restarting AS, but still I get the same problem(everything is fine with nexus 7 and Samsung Galaxy 2).

The tablet/device I'm working on is a "VeryKool" T742

Environment information:
 OS: ubuntu
 AndroidStudio version: 0.8.6

 Tablet Android version:4.2.2
 Tablet Kernel version: 3.4.5
 App min SDK: 14


问:
Specific grouping in Tableau (Heatmap)
I would like to join an Excel dataset which contain (but I don't know if its possible in here) :

The name of a course

The ID of a problem from this course (many pb per course)

The ID of a user that has submitted an answer for this problem from this course

the grade that the user has obtained at this pb from this course

What I try to achieve, it is a graph like those ! It's supposed to be call : Gradient-map, Colormap or Heat-map.

Axe x : Every problem for each course

Axe y : value of the grade (from 0 to 100)

Axe z : Number of user for each Note value

So, if for the pb A of the Course A, the dispersion is like this:

9 users have 100

21 users have 80

40 users have 60

5 users have 40

10 users have 20

15 users have 0

I would like to have every value displayed on a bar and each value would be displayed by a square. Each square having a different color regarding the value represented.
So, here, 60 would be darker than any other value (since the amount of people having this grade is the greatest) and 20 would be clearer than 0, 60, 80 & 100 but darker than 40
Then, just next to this bar, the same but for the pb B & C. Then, next to it, the pb A, B & C for the course B, etc

答:
Move grade, name of a course, ID of a problem to Dimensions.

Put name of a course and ID of a problem on the columns.

Put grade on the rows.

Find a drop down list on the Marks tab and select Square.

Put COUNT(ID of a user) on the Color on the Marks tab

Title: Specific grouping in Tableau (Heatmap)


问:
Trying to populate two comboboxes based upon selection of another combobox
I've been searching this issue on Microsoft, Stackoverflow, techinthenet.com and several others, with no real solution that I can find.

I am trying to get two comboboxes (cboCourse and cboVols) to populate based on the selection of cboTrainee_Name.  The code for the first combobox is:

```<code>SELECT DISTINCT [qryBooks].[PName] FROM qryBooks WHERE qryBooks.Complete=No ORDER BY [qryBooks].[PName];
</code>```

Everywhere I've searched gives assistance and samples to populate the first combobox, then the second combobox based upon what is selected in the first.  I need both cboCourse and cboVols to populate based on the result of the same query.  What I have so far is:

```<code>Private Sub cboTrainee_Name_AfterUpdate()

    cboCourse.RowSource = "SELECT DISTINCT [qryBooks].[Book] FROM qryBooks WHERE [qryBooks].[PName]=[Forms]![frmIntro]![cboTrainee_Name] ORDER BY [qryBooks].[Book];"

    cboVol.RowSource = "SELECT DISTINCT [qryBooks].[Vols] FROM qryBooks WHERE [qryBooks].[PName]=[Forms]![frmIntro]![cboTrainee_Name] ORDER BY [qryBooks].[Vols];"

End Sub
</code>```

This works for cboCourse, but cboVols will not populate.  I know there has to be a simple explanation.  Any suggestions?

ADDED!  I used SELECT DISTINCT because each column in the query contains multiple instances of the same data.

答:
I don't see any problems with your SQL.

You might need to call the Requery method on both combo boxes to get them to refresh after cboTrainee_Name is changed:

```<code>cboCourse.Requery
cboVol.Requery
</code>```

Note that you don't have to set the RowSource property in code for this to work. You should be able to plug in your SQL statements as is in the RowSource property and just the Requery method on the dependent combo boxes in the AfterUpdate event of your cboTrainee_Name combo box.

Body:
I've been searching this issue on Microsoft, Stackoverflow, techinthenet.com and several others, with no real solution that I can find.

I am trying to get two comboboxes (cboCourse and cboVols) to populate based on the selection of cboTrainee_Name.  The code for the first combobox is:

SELECT DISTINCT [qryBooks].[PName] FROM qryBooks WHERE qryBooks.Complete=No ORDER BY [qryBooks].[PName];

Everywhere I've searched gives assistance and samples to populate the first combobox, then the second combobox based upon what is selected in the first.  I need both cboCourse and cboVols to populate based on the result of the same query.  What I have so far is:

Private Sub cboTrainee_Name_AfterUpdate()

    cboCourse.RowSource = "SELECT DISTINCT [qryBooks].[Book] FROM qryBooks WHERE [qryBooks].[PName]=[Forms]![frmIntro]![cboTrainee_Name] ORDER BY [qryBooks].[Book];"

    cboVol.RowSource = "SELECT DISTINCT [qryBooks].[Vols] FROM qryBooks WHERE [qryBooks].[PName]=[Forms]![frmIntro]![cboTrainee_Name] ORDER BY [qryBooks].[Vols];"

End Sub

This works for cboCourse, but cboVols will not populate.  I know there has to be a simple explanation.  Any suggestions?

ADDED!  I used SELECT DISTINCT because each column in the query contains multiple instances of the same data.

Body:
I don't see any problems with your SQL.

You might need to call the Requery method on both combo boxes to get them to refresh after cboTrainee_Name is changed:

cboCourse.Requery
cboVol.Requery

Note that you don't have to set the RowSource property in code for this to work. You should be able to plug in your SQL statements as is in the RowSource property and just the Requery method on the dependent combo boxes in the AfterUpdate event of your cboTrainee_Name combo box.


问:
Jenkins pipeline/docker :Jenkins does not seem to be running inside a container
I'm trying to execute the sample of code found in Jenkins Pipeline here : https://jenkins.io/doc/book/pipeline/docker/

```<code>node {
/* Requires the Docker Pipeline plugin to be installed */
    docker.image('maven:3-alpine').inside('-v $HOME/.m2:/root/.m2') {
        stage('Build') {
            sh 'mvn -B'
        }
    }
}
</code>```

And give me this error:

```<code>[Pipeline] withDockerContainer
Jenkins does not seem to be running inside a container
[Pipeline] // withDockerContainer
</code>```

I don't know why is it stopping like that without doing anything.

I have already install docker, docker plugin/docker pipeline on the latest version.

In configuration tool, i add the installation root path.

Did I miss something ?
Thanks in advance

答:
This message is a normal debug message, maybe a little confusing, but not an error.   As the Jenkins Pipeline code is written, during initialization it checks whether the step is already running in a container.  I think the message could be written better.

If you have more problems than this message, please provide the entire log.  Sounds like maybe a node cannot be assigned, or the docker client is not installed, or the docker image cannot be pulled.

Body:
I'm trying to execute the sample of code found in Jenkins Pipeline here : https://jenkins.io/doc/book/pipeline/docker/

node {
/* Requires the Docker Pipeline plugin to be installed */
    docker.image('maven:3-alpine').inside('-v $HOME/.m2:/root/.m2') {
        stage('Build') {
            sh 'mvn -B'
        }
    }
}

And give me this error:

[Pipeline] withDockerContainer
Jenkins does not seem to be running inside a container
[Pipeline] // withDockerContainer

I don't know why is it stopping like that without doing anything.

I have already install docker, docker plugin/docker pipeline on the latest version.

In configuration tool, i add the installation root path.

Did I miss something ?
Thanks in advance


问:
Is the aliasing rule symmetric?
I had a discussion with someone on IRC and this question turned up. We are allowed by the Standard to change an object of type int by a char lvalue.

```<code>int a;
char *b = (char*) &a;
*b = 0;
</code>```

Would we be allowed to do this in the opposite direction, if we know that the alignment is fine?

The issue I'm seeing is that the aliasing rule does not cover the simple case of the following, if one considers the aliasing rule as a non-symmetric relation

```<code>int a;
a = 0;
</code>```

The reason is, that each object contains a sequence of sizeof(obj) unsigned char objects (called the "object representation"). If we change the int, we will change some or all of those objects. However, the aliasing rule only states we are allowed to change a int by an char or unsigned char, but not the other way around. Another example

```<code>int a[1];
int *ra = a;
*ra = 0;
</code>```

Only one direction is described by 3.10/15 ("An aggregate or union type that includes..."), but this time we need the other way around ("A type that is the element or non-static data member type of an aggregate...").

Is the other direction implied? This question also applies to C.

答:
I think I'm a bit confused by the question, but the 2nd and 3rd examples are accessing the int through an lvalue that has the object's type (int in the examples).

C++ 3.10/15 states as it's first item that it's OK to access the object through an lvalue that has the the type of "the dynamic type of the object".

What am I misunderstanding in the question?

Title: Is the aliasing rule symmetric?

Body:
I had a discussion with someone on IRC and this question turned up. We are allowed by the Standard to change an object of type int by a char lvalue.

int a;
char *b = (char*) &a;
*b = 0;

Would we be allowed to do this in the opposite direction, if we know that the alignment is fine?

The issue I'm seeing is that the aliasing rule does not cover the simple case of the following, if one considers the aliasing rule as a non-symmetric relation

int a;
a = 0;

The reason is, that each object contains a sequence of sizeof(obj) unsigned char objects (called the "object representation"). If we change the int, we will change some or all of those objects. However, the aliasing rule only states we are allowed to change a int by an char or unsigned char, but not the other way around. Another example

int a[1];
int *ra = a;
*ra = 0;

Only one direction is described by 3.10/15 ("An aggregate or union type that includes..."), but this time we need the other way around ("A type that is the element or non-static data member type of an aggregate...").

Is the other direction implied? This question also applies to C.


问:
Map one JSON schema to a different JSON schema
I have a bunch of JSON files, thousands of different schemas. Using GenSON (the Python JSON schema generator), I managed to create schema files for each of the input files. Now, what I'd like to do is standardize all these different files to one defined schema. Here's an example:

Input

```<code>{
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": "United States"
     },
     "age": 62,
     "status": "Active"
}
</code>```

Output

```<code>{
     "names": ["Bob Odenkirk"],
     "occupations": ["Software Engineer"],
     "locations": ["San Francisco, CA"]
}
</code>```

Essentially, I am looking for a language agnostic method (i.e., I don't care what programming language is used) of defining how an input JSON file should be parsed to an output JSON file.

答:
I am not sure is your expecting like below. Long time back I have created flat object and output format object. It will return output format object with data filled.

```<code>var input = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": "United States"
     },
     "age": 62,
     "status": "Active"
};

var outputFormat = {
    "name": "name",
  "occupations": "title",
  "locations": "location.locality, location.region"
};

var flatInput = {};

function generateFlatInput(input, parent){
     for (var prop in input) {
        if(input.hasOwnProperty(prop) && typeof input[prop] === 'object')
            flatInput = generateFlatInput(input[prop], parent + prop + '.');
        else
         flatInput[parent + prop] =  input[prop];
    }

    return flatInput;
}

function generateOutput(input, outputFormat, delimiter){
     input = generateFlatInput(input, '');

     for (var prop in outputFormat) {
        var fields = outputFormat[prop].split(delimiter);
      var fieldValue = [];
      for(i = 0; i < fields.length; i++){
                    if(!input.hasOwnProperty(fields[i].trim())) continue;

          fieldValue.push(input[fields[i].trim()]);
      }
      outputFormat[prop] = fieldValue.join(delimiter);
   }

   return outputFormat;
}

console.log(generateOutput(input, outputFormat, ', '));
</code>```

https://jsfiddle.net/u2yyuguk/1/

Body:
I have a bunch of JSON files, thousands of different schemas. Using GenSON (the Python JSON schema generator), I managed to create schema files for each of the input files. Now, what I'd like to do is standardize all these different files to one defined schema. Here's an example:

Input

{
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": "United States"
     },
     "age": 62,
     "status": "Active"
}

Output

{
     "names": ["Bob Odenkirk"],
     "occupations": ["Software Engineer"],
     "locations": ["San Francisco, CA"]
}

Essentially, I am looking for a language agnostic method (i.e., I don't care what programming language is used) of defining how an input JSON file should be parsed to an output JSON file.

Body:
I am not sure is your expecting like below. Long time back I have created flat object and output format object. It will return output format object with data filled.

var input = {
     "name": "Bob Odenkirk",
     "title": "Software Engineer",
     "location": {
         "locality": "San Francisco",
         "region": "CA",
         "country": "United States"
     },
     "age": 62,
     "status": "Active"
};

var outputFormat = {
    "name": "name",
  "occupations": "title",
  "locations": "location.locality, location.region"
};

var flatInput = {};

function generateFlatInput(input, parent){
     for (var prop in input) {
        if(input.hasOwnProperty(prop) && typeof input[prop] === 'object')
            flatInput = generateFlatInput(input[prop], parent + prop + '.');
        else
         flatInput[parent + prop] =  input[prop];
    }

    return flatInput;
}

function generateOutput(input, outputFormat, delimiter){
     input = generateFlatInput(input, '');

     for (var prop in outputFormat) {
        var fields = outputFormat[prop].split(delimiter);
      var fieldValue = [];
      for(i = 0; i < fields.length; i++){
                    if(!input.hasOwnProperty(fields[i].trim())) continue;

          fieldValue.push(input[fields[i].trim()]);
      }
      outputFormat[prop] = fieldValue.join(delimiter);
   }

   return outputFormat;
}

console.log(generateOutput(input, outputFormat, ', '));

https://jsfiddle.net/u2yyuguk/1/


问:
Android, how to close ListView when "Back" button pressed to close searchView
I have an actionBar with a searchView icon. I click on searchView icon and softInputMode keyboard appears and my ListView appears for searching. However, when you go to close searchView, the searchView closes but I can't get the ListView to also close when searchView closes.

Here's my code for ListView in activity_maps.xml

```<code><ListView
    android:id="@+id/list"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="#ffffff"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    tools:layout_editor_absoluteX="0dp"
    />
</code>```

MapsActivity.java

```<code>    ArrayAdapter<String> adapter;

    @Override
   public boolean onCreateOptionsMenu(final Menu menu){

    final ListView lv = (ListView) findViewById(R.id.list);

    ArrayList<String> arrayList = new ArrayList<>();

      arrayList.addAll(Arrays.asList(getResources().getStringArray(R.array.array_states_trial)));

    adapter = new ArrayAdapter<>(MapsActivity.this, android.R.layout.simple_list_item_1, arrayList);

    lv.setAdapter(adapter);

    lv.setVisibility(View.INVISIBLE);
</code>```

So initially when MapsActivity.java loads I don't want the ListView to show right away.

```<code>    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            lv.setVisibility(View.VISIBLE);

        }
    });
</code>```

I want the listView to show when searchView is clicked open and keyboard pops up.

```<code>    searchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {

               lv.setVisibility(View.INVISIBLE);

            return false;
        }
    });
</code>```

In the above code, I want the listView to close, disappear, be invisible, but it doesn't.

btw I'm referring to the "Back" button in the actionBar that comes with closing searchView.

When searchView and keyboard closes, I want the ListView to also close but for some reason the code isn't recognized and listView never closes.

How do I close ListView?

答:
What you can simply do is override this method in your activity:

```<code>@Override
public void onBackPressed() {
    if(lv.getVisibility()==View.VISIBLE){
      lv.setVisibility(View.INVISIBLE);
      return;
    }
    super.onBackPressed();
}
</code>```

Hope this helps.

Body:
I have an actionBar with a searchView icon. I click on searchView icon and softInputMode keyboard appears and my ListView appears for searching. However, when you go to close searchView, the searchView closes but I can't get the ListView to also close when searchView closes.

Here's my code for ListView in activity_maps.xml

<ListView
    android:id="@+id/list"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="#ffffff"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    tools:layout_editor_absoluteX="0dp"
    />

MapsActivity.java

    ArrayAdapter<String> adapter;

    @Override
   public boolean onCreateOptionsMenu(final Menu menu){

    final ListView lv = (ListView) findViewById(R.id.list);

    ArrayList<String> arrayList = new ArrayList<>();

      arrayList.addAll(Arrays.asList(getResources().getStringArray(R.array.array_states_trial)));

    adapter = new ArrayAdapter<>(MapsActivity.this, android.R.layout.simple_list_item_1, arrayList);

    lv.setAdapter(adapter);

    lv.setVisibility(View.INVISIBLE);

So initially when MapsActivity.java loads I don't want the ListView to show right away.

    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            lv.setVisibility(View.VISIBLE);

        }
    });

I want the listView to show when searchView is clicked open and keyboard pops up.

    searchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {

               lv.setVisibility(View.INVISIBLE);

            return false;
        }
    });

In the above code, I want the listView to close, disappear, be invisible, but it doesn't.

btw I'm referring to the "Back" button in the actionBar that comes with closing searchView.

When searchView and keyboard closes, I want the ListView to also close but for some reason the code isn't recognized and listView never closes.

How do I close ListView?

Body:
What you can simply do is override this method in your activity:

@Override
public void onBackPressed() {
    if(lv.getVisibility()==View.VISIBLE){
      lv.setVisibility(View.INVISIBLE);
      return;
    }
    super.onBackPressed();
}

Hope this helps.


问:
Error during web socket handshake; websocket connection failed, using autobahn.js
I am trying to create a websocket server using Ratchet, React and Autobahn. When trying to connect I get this error in console

autobahn.min.js:196 WebSocket connection to 'ws://localhost:8090/'
  failed: Error during WebSocket handshake: Unexpected response code:
  426

During some digging in Google I found out that Ratchet supports only WAMP1, but that information was 2014. Is this still relevant?

This is the JS

```<code>   var connection = new autobahn.Connection({
    transports: [{
      type: 'websocket',
      port: 8090,
      host: 'localhost',
      url: 'ws://localhost:8090'
    }],
    realm: 'realm1'
  });
  connection.open();
</code>```

This is the WebsocketController class

```<code><?php

namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Wamp\WampServerInterface;

class WebSocketController extends Controller implements WampServerInterface{
    private $connections = [];
    protected $subscribedTopics = array();

    public function onSubscribe(ConnectionInterface $conn, $topic) {
        $this->subscribedTopics[$topic->getId()] = $topic;
    }
    public function onUnSubscribe(ConnectionInterface $conn, $topic) {
    }
    public function onOpen(ConnectionInterface $conn) {
        $this->connections->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }
    public function onClose(ConnectionInterface $conn) {
    }
    public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->callError($id, $topic, 'You are not allowed to make calls')->close();
    }
    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->close();
    }
    public function onError(ConnectionInterface $conn, \Exception $e) {
      echo "New error!".$e;
    }

        /**
         * @param string JSON'ified string we'll receive from ZeroMQ
         */
        public function onBlogEntry($entry) {
            $entryData = json_decode($entry, true);

            // If the lookup topic object isn't set there is no one to publish to
            if (!array_key_exists($entryData['category'], $this->subscribedTopics)) {
                return;
            }

            $topic = $this->subscribedTopics[$entryData['category']];

            // re-send the data to all the clients subscribed to that category
            $topic->broadcast($entryData);
        }
}
</code>```

This is the server:

```<code>$loop   = Factory::create();
$pusher = new WebsocketController;

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new Context($loop);
$pull = $context->getSocket(\ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onBlogEntry'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new \React\Socket\Server('0.0.0.0:8090', $loop); // Binding to 0.0.0.0 means remotes can connect
$webServer = new \Ratchet\Server\IoServer(
    new \Ratchet\Http\HttpServer(
        new \Ratchet\WebSocket\WsServer(
            new \Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();
</code>```

Headers

```<code>Request URL:ws://localhost:8090/
Request Method:GET
Status Code:426 No Sec-WebSocket-Protocols requested supported
Response Headers
view source
Connection:Upgrade
Sec-WebSocket-Protocol:0
Sec-WebSocket-Version:13
Transfer-Encoding:chunked
Upgrade:websocket
X-Powered-By:Ratchet/0.4
Request Headers
view source
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9,et;q=0.8
Cache-Control:no-cache
Connection:Upgrade
Host:localhost:8090
Origin:http://ermp.ee:8000
Pragma:no-cache
Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
Sec-WebSocket-Key:GbJ7qf3lzKDE2hmh3mxJpQ==
Sec-WebSocket-Protocol:wamp.2.json, wamp.2.msgpack
Sec-WebSocket-Version:13
Upgrade:websocket
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
</code>```

What am I doing wrong here?

答:
I was making something similar to your program when I encountered with this problem. I realized that I was running localhost on the wrong port AND I had processes like Skype running in background on my desired selected port.
Local host runs on port 8000.
Change your code above to this and try as this worked for me in one of my projects

```<code>var connection = new     autobahn.Connection({
transports: [{
  type: 'websocket',
  port: 8000,
  host: 'localhost',
  url: 'ws://localhost:8000'
}],
realm: 'realm1'
</code>```

});
connection.open();

Also check on your computer if there is already an application running on port 8000, if it is end the program/process to solve the problem.

In Server:

```<code>$webSock = new \React\Socket\Server('0.0.0.0:8000', $loop); // Binding to 0.0.0.0 means remotes can connect
</code>```

In Headers:

```<code>Host:localhost:8000
</code>```

And you right ratchet does support only wamp1
Maybe you can switch ratchet to thruway which may solve problem

Body:
I am trying to create a websocket server using Ratchet, React and Autobahn. When trying to connect I get this error in console

autobahn.min.js:196 WebSocket connection to 'ws://localhost:8090/'
  failed: Error during WebSocket handshake: Unexpected response code:
  426

During some digging in Google I found out that Ratchet supports only WAMP1, but that information was 2014. Is this still relevant?

This is the JS

   var connection = new autobahn.Connection({
    transports: [{
      type: 'websocket',
      port: 8090,
      host: 'localhost',
      url: 'ws://localhost:8090'
    }],
    realm: 'realm1'
  });
  connection.open();

This is the WebsocketController class

<?php

namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Wamp\WampServerInterface;

class WebSocketController extends Controller implements WampServerInterface{
    private $connections = [];
    protected $subscribedTopics = array();

    public function onSubscribe(ConnectionInterface $conn, $topic) {
        $this->subscribedTopics[$topic->getId()] = $topic;
    }
    public function onUnSubscribe(ConnectionInterface $conn, $topic) {
    }
    public function onOpen(ConnectionInterface $conn) {
        $this->connections->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }
    public function onClose(ConnectionInterface $conn) {
    }
    public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->callError($id, $topic, 'You are not allowed to make calls')->close();
    }
    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {
        // In this application if clients send data it's because the user hacked around in console
        $conn->close();
    }
    public function onError(ConnectionInterface $conn, \Exception $e) {
      echo "New error!".$e;
    }

        /**
         * @param string JSON'ified string we'll receive from ZeroMQ
         */
        public function onBlogEntry($entry) {
            $entryData = json_decode($entry, true);

            // If the lookup topic object isn't set there is no one to publish to
            if (!array_key_exists($entryData['category'], $this->subscribedTopics)) {
                return;
            }

            $topic = $this->subscribedTopics[$entryData['category']];

            // re-send the data to all the clients subscribed to that category
            $topic->broadcast($entryData);
        }
}

This is the server:

$loop   = Factory::create();
$pusher = new WebsocketController;

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new Context($loop);
$pull = $context->getSocket(\ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onBlogEntry'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new \React\Socket\Server('0.0.0.0:8090', $loop); // Binding to 0.0.0.0 means remotes can connect
$webServer = new \Ratchet\Server\IoServer(
    new \Ratchet\Http\HttpServer(
        new \Ratchet\WebSocket\WsServer(
            new \Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();

Headers

Request URL:ws://localhost:8090/
Request Method:GET
Status Code:426 No Sec-WebSocket-Protocols requested supported
Response Headers
view source
Connection:Upgrade
Sec-WebSocket-Protocol:0
Sec-WebSocket-Version:13
Transfer-Encoding:chunked
Upgrade:websocket
X-Powered-By:Ratchet/0.4
Request Headers
view source
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9,et;q=0.8
Cache-Control:no-cache
Connection:Upgrade
Host:localhost:8090
Origin:http://ermp.ee:8000
Pragma:no-cache
Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
Sec-WebSocket-Key:GbJ7qf3lzKDE2hmh3mxJpQ==
Sec-WebSocket-Protocol:wamp.2.json, wamp.2.msgpack
Sec-WebSocket-Version:13
Upgrade:websocket
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

What am I doing wrong here?

Body:
I was making something similar to your program when I encountered with this problem. I realized that I was running localhost on the wrong port AND I had processes like Skype running in background on my desired selected port.
Local host runs on port 8000.
Change your code above to this and try as this worked for me in one of my projects

var connection = new     autobahn.Connection({
transports: [{
  type: 'websocket',
  port: 8000,
  host: 'localhost',
  url: 'ws://localhost:8000'
}],
realm: 'realm1'

});
connection.open();

Also check on your computer if there is already an application running on port 8000, if it is end the program/process to solve the problem.

In Server:

$webSock = new \React\Socket\Server('0.0.0.0:8000', $loop); // Binding to 0.0.0.0 means remotes can connect

In Headers:

Host:localhost:8000

And you right ratchet does support only wamp1
Maybe you can switch ratchet to thruway which may solve problem


问:
How to increment (add value to) decimal in a thread-safe way?
I have a decimal variable that is accessed from multiple threads at the same time. Interlocked class functions do not support decimals at all, so the only approach I'm left with is using lock(){}. It seems to be an overkill.

It there some other way to add value to decimal variable in a thread-safe way?

答:
If you do not mind keeping the total as an object-wrapped decimal, you could use this approach:

```<code>private static object myTotal = 0M;
static void InterlockedAddTotal(decimal val) {
    object next;
    object current;
    do {
        current = myTotal;
        next = val + (decimal)current;
    } while (Interlocked.CompareExchange(ref myTotal, next, current) != current);
}
</code>```

Although this approach does not use a lock, it wraps decimal in an object, which carries its own performance implications. Depending on the situation, using a lock may be cheaper.

Body:
If you do not mind keeping the total as an object-wrapped decimal, you could use this approach:

private static object myTotal = 0M;
static void InterlockedAddTotal(decimal val) {
    object next;
    object current;
    do {
        current = myTotal;
        next = val + (decimal)current;
    } while (Interlocked.CompareExchange(ref myTotal, next, current) != current);
}

Although this approach does not use a lock, it wraps decimal in an object, which carries its own performance implications. Depending on the situation, using a lock may be cheaper.


问:
Accessing the outer scope in Python 2.6
Say, I have some scope with variables, and a function called in this scope wants to change some immutable variables:

```
def outer():
    s = 'qwerty'
    n = 123
    modify()

def modify():
    s = 'abcd'
    n = 456
```

Is it possible somehow to access the outer scope? Something like nonlocal variables from Py3k.

Sure I can do s,n = modify(s,n) in this case, but what if I need some generic 'injection' which executes there and must be able to reassign to arbitrary variables?

I have performance in mind, so, if possible, eval & stack frame inspection is not welcome :)

UPD: It's impossible. Period. However, there are some options how to access variables in the outer scope:

Use globals. By the way, func.__globals__ is a mutable dictionary ;)

Store variables in a dict/class-instance/any other mutable container

Give variables as arguments & get them back as a tuple: a,b,c = innerfunc(a,b,c)

Inject other function's bytecode. This is possible with byteplay python module.

答:
Sometimes I run across code like this. A nested function modifies a mutable object instead of assigning to a nonlocal:

```<code>def outer():
    s = [4]
    def inner():
        s[0] = 5
    inner()
</code>```

Title: Accessing the outer scope in Python 2.6

Body:
Say, I have some scope with variables, and a function called in this scope wants to change some immutable variables:

def outer():
    s = 'qwerty'
    n = 123
    modify()

def modify():
    s = 'abcd'
    n = 456

Is it possible somehow to access the outer scope? Something like nonlocal variables from Py3k.

Sure I can do s,n = modify(s,n) in this case, but what if I need some generic 'injection' which executes there and must be able to reassign to arbitrary variables?

I have performance in mind, so, if possible, eval & stack frame inspection is not welcome :)

UPD: It's impossible. Period. However, there are some options how to access variables in the outer scope:

Use globals. By the way, func.__globals__ is a mutable dictionary ;)

Store variables in a dict/class-instance/any other mutable container

Give variables as arguments & get them back as a tuple: a,b,c = innerfunc(a,b,c)

Inject other function's bytecode. This is possible with byteplay python module.

Body:
Sometimes I run across code like this. A nested function modifies a mutable object instead of assigning to a nonlocal:

def outer():
    s = [4]
    def inner():
        s[0] = 5
    inner()


问:
R: Color branches of dendrogram while preserving the color legend
Objective: Create a dendrogram with branches colored by a factor variable with the resultant plot containing a legend to translate the branch colors to each factor variable value.

I have some data with factor variables followed by the numeric data that I am creating a dendrogram with:

```<code>> cleaned_mayo[1:5,1:20]
          patient                Source         Tissue RIN Diagnosis Gender  AgeAtDeath ApoE   FLOWCELL PMI N_unmapped N_multimapping N_noFeature N_ambiguous ENSG00000223972
1924_TCX 1924_TCX MayoBrainBank_Dickson TemporalCortex 5.6   Control      F 90_or_above   33 AC5R6PACXX   2    2773880        9656114     8225967     2876479               1
1926_TCX 1926_TCX MayoBrainBank_Dickson TemporalCortex 7.8   Control      F          88   33 AC44HKACXX   2    2279283       12410116     9503353     3600252               2
1935_TCX 1935_TCX MayoBrainBank_Dickson TemporalCortex 8.6   Control      F          88   33 AC5T2GACXX   3    3120169        8650081     9640468     4603751               0
1925_TCX 1925_TCX MayoBrainBank_Dickson TemporalCortex 6.6   Control      F          89   33 BC6178ACXX   4    2046886       10627577     7533671     3361385               1
1963_TCX 1963_TCX MayoBrainBank_Dickson TemporalCortex 9.7   Control      M 90_or_above   33 AC5T1WACXX   4    1810116        9611375     5343437     2983079               2
         ENSG00000227232 ENSG00000278267 ENSG00000243485 ENSG00000274890 ENSG00000237613
1924_TCX              80               7               1               0               0
1926_TCX             113              22               9               0               0
1935_TCX             181              21               2               0               0
1925_TCX              75               9               5               0               0
1963_TCX              73              14               1               0               0
</code>```

The data dimensions are: 161 x 60,739. With this data I have achieved a dendrogram with colored branches but no legend, and a dendrogram with colored labels (not branches) with a legend. I would like to combine the two.

Create dendrogram with colored branches but no legend:

```<code># Create the dendrogram for visualization
dend_expr<- cleaned_mayo[,15:60739] %>% # Isolate expression data
                  scale %>% # Normalize
                  dist  %>% # Compute distance measure
                  hclust %>% # Cluster hierarchically
                  as.dendrogram()

# Arrange labels in order with tree
tree_labels<- cleaned_mayo[order.dendrogram(dend_expr),]

# Color branches by diagnosis
dend_expr<- assign_values_to_leaves_edgePar(dend_expr, value= tree_labels$Diagnosis, edgePar= "col") %>%
            as.ggdend()

# Plot dendrogram
ggplot(dend_expr, horiz= T, theme= NULL, labels= F) +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")
</code>```

Create dendrogram with colored labels (not branches) and a legend:

```<code># Create the dendrogram for visualization
dend_expr<- cleaned_mayo[,15:60739] %>% # Isolate expression data
                  scale %>% # Normalize
                  dist  %>% # Compute distance measure
                  hclust %>% # Cluster hierarchically
                  as.dendrogram()

tree_labels<- dendro_data(dend_expr, type = "rectangle")
tree_labels$labels<- merge(x= tree_labels$labels, y= cleaned_mayo, by.x= "label", by.y= "patient")

ggplot() +
  geom_segment(data=segment(tree_labels), aes(x=x, y=y, xend=xend, yend=yend)) +
  geom_text(data = label(tree_labels), aes(x=x, y=y, label=label, colour = Diagnosis, hjust=0), size=3) +
  #geom_point(data = label(tree_labels), aes(x=x, y=y), size=2, shape = 21) +
  coord_flip() +
  scale_y_reverse(expand=c(0.2, 0)) +
  scale_colour_brewer(palette = "Dark2") +
  theme_dendro() +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")
</code>```

Examples of the respective outputs:
Colored branches; Colored labels with legend.

Any help is appreciated. Thanks!

答:
Here is an example on how to achieve the desired coloring:

```<code>library(tidyverse)
library(ggdendro)
library(dendextend)
</code>```

some data:

```<code>matrix(rnorm(1000), ncol = 10) %>%
  scale %>%
  dist  %>%
  hclust %>%
  as.dendrogram() -> dend_expr

tree_labels<- dendro_data(dend_expr, type = "rectangle")
tree_labels$labels <- cbind(tree_labels$labels, Diagnosis = as.factor(sample(1:2, 100, replace = T)))
</code>```

Plot:

```<code>ggplot() +
  geom_segment(data = segment(tree_labels), aes(x=x, y=y, xend=xend, yend=yend))+
  geom_segment(data = tree_labels$segments %>%
                 filter(yend == 0) %>%
                 left_join(tree_labels$labels, by = "x"), aes(x=x, y=y.x, xend=xend, yend=yend, color = Diagnosis)) +
  geom_text(data = label(tree_labels), aes(x=x, y=y, label=label, colour = Diagnosis, hjust=0), size=3) +
  coord_flip() +
  scale_y_reverse(expand=c(0.2, 0)) +
  scale_colour_brewer(palette = "Dark2") +
  theme_dendro() +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")
</code>```

The key is in the second geom_segment call where I do:

```<code>tree_labels$segments %>%
     filter(yend == 0) %>%
     left_join(tree_labels$labels, by = "x")
</code>```

Filter all the leaves yend == 0 and left join tree_labels$labels by x

Body:
Objective: Create a dendrogram with branches colored by a factor variable with the resultant plot containing a legend to translate the branch colors to each factor variable value.

I have some data with factor variables followed by the numeric data that I am creating a dendrogram with:

> cleaned_mayo[1:5,1:20]
          patient                Source         Tissue RIN Diagnosis Gender  AgeAtDeath ApoE   FLOWCELL PMI N_unmapped N_multimapping N_noFeature N_ambiguous ENSG00000223972
1924_TCX 1924_TCX MayoBrainBank_Dickson TemporalCortex 5.6   Control      F 90_or_above   33 AC5R6PACXX   2    2773880        9656114     8225967     2876479               1
1926_TCX 1926_TCX MayoBrainBank_Dickson TemporalCortex 7.8   Control      F          88   33 AC44HKACXX   2    2279283       12410116     9503353     3600252               2
1935_TCX 1935_TCX MayoBrainBank_Dickson TemporalCortex 8.6   Control      F          88   33 AC5T2GACXX   3    3120169        8650081     9640468     4603751               0
1925_TCX 1925_TCX MayoBrainBank_Dickson TemporalCortex 6.6   Control      F          89   33 BC6178ACXX   4    2046886       10627577     7533671     3361385               1
1963_TCX 1963_TCX MayoBrainBank_Dickson TemporalCortex 9.7   Control      M 90_or_above   33 AC5T1WACXX   4    1810116        9611375     5343437     2983079               2
         ENSG00000227232 ENSG00000278267 ENSG00000243485 ENSG00000274890 ENSG00000237613
1924_TCX              80               7               1               0               0
1926_TCX             113              22               9               0               0
1935_TCX             181              21               2               0               0
1925_TCX              75               9               5               0               0
1963_TCX              73              14               1               0               0

The data dimensions are: 161 x 60,739. With this data I have achieved a dendrogram with colored branches but no legend, and a dendrogram with colored labels (not branches) with a legend. I would like to combine the two.

Create dendrogram with colored branches but no legend:

# Create the dendrogram for visualization
dend_expr<- cleaned_mayo[,15:60739] %>% # Isolate expression data
                  scale %>% # Normalize
                  dist  %>% # Compute distance measure
                  hclust %>% # Cluster hierarchically
                  as.dendrogram()

# Arrange labels in order with tree
tree_labels<- cleaned_mayo[order.dendrogram(dend_expr),]

# Color branches by diagnosis
dend_expr<- assign_values_to_leaves_edgePar(dend_expr, value= tree_labels$Diagnosis, edgePar= "col") %>%
            as.ggdend()

# Plot dendrogram
ggplot(dend_expr, horiz= T, theme= NULL, labels= F) +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")

Create dendrogram with colored labels (not branches) and a legend:

# Create the dendrogram for visualization
dend_expr<- cleaned_mayo[,15:60739] %>% # Isolate expression data
                  scale %>% # Normalize
                  dist  %>% # Compute distance measure
                  hclust %>% # Cluster hierarchically
                  as.dendrogram()

tree_labels<- dendro_data(dend_expr, type = "rectangle")
tree_labels$labels<- merge(x= tree_labels$labels, y= cleaned_mayo, by.x= "label", by.y= "patient")

ggplot() +
  geom_segment(data=segment(tree_labels), aes(x=x, y=y, xend=xend, yend=yend)) +
  geom_text(data = label(tree_labels), aes(x=x, y=y, label=label, colour = Diagnosis, hjust=0), size=3) +
  #geom_point(data = label(tree_labels), aes(x=x, y=y), size=2, shape = 21) +
  coord_flip() +
  scale_y_reverse(expand=c(0.2, 0)) +
  scale_colour_brewer(palette = "Dark2") +
  theme_dendro() +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")

Examples of the respective outputs:
Colored branches; Colored labels with legend.

Any help is appreciated. Thanks!

Body:
Here is an example on how to achieve the desired coloring:

library(tidyverse)
library(ggdendro)
library(dendextend)

some data:

matrix(rnorm(1000), ncol = 10) %>%
  scale %>%
  dist  %>%
  hclust %>%
  as.dendrogram() -> dend_expr

tree_labels<- dendro_data(dend_expr, type = "rectangle")
tree_labels$labels <- cbind(tree_labels$labels, Diagnosis = as.factor(sample(1:2, 100, replace = T)))

Plot:

ggplot() +
  geom_segment(data = segment(tree_labels), aes(x=x, y=y, xend=xend, yend=yend))+
  geom_segment(data = tree_labels$segments %>%
                 filter(yend == 0) %>%
                 left_join(tree_labels$labels, by = "x"), aes(x=x, y=y.x, xend=xend, yend=yend, color = Diagnosis)) +
  geom_text(data = label(tree_labels), aes(x=x, y=y, label=label, colour = Diagnosis, hjust=0), size=3) +
  coord_flip() +
  scale_y_reverse(expand=c(0.2, 0)) +
  scale_colour_brewer(palette = "Dark2") +
  theme_dendro() +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")

The key is in the second geom_segment call where I do:

tree_labels$segments %>%
     filter(yend == 0) %>%
     left_join(tree_labels$labels, by = "x")

Filter all the leaves yend == 0 and left join tree_labels$labels by x


问:
Warning in java changes with the scope of cast
When I compile a program in java containing this  :

```<code>ch = (char) ch - 32;
</code>```

the terminal shows :

```<code>    incompatible types: possible lossy conversion from int to char
                    ch = (char) ch - 32;
                                   ^
    1 error
</code>```

but this works

```<code>    ch = (char) (ch - 32);
</code>```

why is this happening?
Thanks in advance.

答:
Because

```<code>ch = (char) ch - 32;
</code>```

is the same as

```<code>ch = ( (char) ch ) - 32;
</code>```

As in:

```<code>ch = ch - 32;
</code>```

Which first turns ch into an int value. To subtract 32. Resulting in an int value. Which doesn't fit into a char (easily). Thus the compiler error.

One way around that: make sure that the cast applies to the result of the operation, not to the first operand.

```<code> ch = (char) ( ch - 32 );
</code>```

Body:
When I compile a program in java containing this  :

ch = (char) ch - 32;

the terminal shows :

    incompatible types: possible lossy conversion from int to char
                    ch = (char) ch - 32;
                                   ^
    1 error

but this works

    ch = (char) (ch - 32);

why is this happening?
Thanks in advance.

Body:
Because

ch = (char) ch - 32;

is the same as

ch = ( (char) ch ) - 32;

As in:

ch = ch - 32;

Which first turns ch into an int value. To subtract 32. Resulting in an int value. Which doesn't fit into a char (easily). Thus the compiler error.

One way around that: make sure that the cast applies to the result of the operation, not to the first operand.

 ch = (char) ( ch - 32 );


问:
Validate multiple emails separated by semicolons and all must match a specific domain
I want to validate this text field email which contains Multiple emails; all separated by semi colons but this isn't working. It should break when msn.com have been entered along with other emails.

```<code>var isMsn = ["msn.com"];
function myFunction() {
    var str = email.value;
    //var isMsn = str.includes("msn.com");
    var res = str.split(";");
    var isValid = false;
    //alert(res.length);
    for (var i = 0; i < res.length; i++){
        //alert(res[i]);
        var x = res[i];
        //check to see if this is an valid emAIL then
        var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if(x.match(mailformat)){
           alert("valid email address!");
           //IF isMsn = TRUE then check to see if is contains msn.com
           if (x.contains(isMsn) ){
               alert("it is MSN");
               //res[+1];
               isValid = true;
           }
           else {
               alert('no MSN');
               if (res.includes(isMsn)){
                   //alert('Cannot mix MSN emails with other');
                   //isValid = false;
                   //res[-1];
                   break;
               }
               //else{
               //alert('it is other');
               //isValid = true;
               //}
           }
       }
       else{
           alert("You have entered an invalid email address!");
           isValid = false;
       }
   }
}
</code>```

I want it to loop through and all the emails must either match a msn.com or other NOT Both. for example, user@msn.com;user1@msn.com or user@hotmail.com;user1@hotmail.com but NOT user@msn.com;user1@hotmail.com

Not sure if .includes is the best option or not!

答:
1) You should use includes instead of contains;

2) The includes or contains method accepts a string, not an array, so it should be res.includes(isMsn[0]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

And if you want to validate by multiple domains - you should not name it isMsn, but prohibitedDomains and then to Array.some (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) over this array.

```<code>prohibitedDomains.some((domain) => res.includes(domain))
</code>```

Body:
I want to validate this text field email which contains Multiple emails; all separated by semi colons but this isn't working. It should break when msn.com have been entered along with other emails.

var isMsn = ["msn.com"];
function myFunction() {
    var str = email.value;
    //var isMsn = str.includes("msn.com");
    var res = str.split(";");
    var isValid = false;
    //alert(res.length);
    for (var i = 0; i < res.length; i++){
        //alert(res[i]);
        var x = res[i];
        //check to see if this is an valid emAIL then
        var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if(x.match(mailformat)){
           alert("valid email address!");
           //IF isMsn = TRUE then check to see if is contains msn.com
           if (x.contains(isMsn) ){
               alert("it is MSN");
               //res[+1];
               isValid = true;
           }
           else {
               alert('no MSN');
               if (res.includes(isMsn)){
                   //alert('Cannot mix MSN emails with other');
                   //isValid = false;
                   //res[-1];
                   break;
               }
               //else{
               //alert('it is other');
               //isValid = true;
               //}
           }
       }
       else{
           alert("You have entered an invalid email address!");
           isValid = false;
       }
   }
}

I want it to loop through and all the emails must either match a msn.com or other NOT Both. for example, user@msn.com;user1@msn.com or user@hotmail.com;user1@hotmail.com but NOT user@msn.com;user1@hotmail.com

Not sure if .includes is the best option or not!

Body:
1) You should use includes instead of contains;

2) The includes or contains method accepts a string, not an array, so it should be res.includes(isMsn[0]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

And if you want to validate by multiple domains - you should not name it isMsn, but prohibitedDomains and then to Array.some (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) over this array.

prohibitedDomains.some((domain) => res.includes(domain))


问:
VBA Calling a private function inside of a userform
I have a userform defined as "SingleListForm".
I have a private sub named "loadSingleListForm(ID As Double)"
I am attempting to pass a variable into the form and I was implementing it in the fashion that loadSingleListForm would set the form up based on ID, basically re-using one form to show variable data from variable sources in the listbox.

But calling a standard Intersect from  outside the form (Worksheet_SelectionChange) these two options compile but do not work.

```<code>Application.Run "SingleListForm.loadSingleListForm", ID 'ID already declared and assigned
</code>```

This doesn't work either

```<code>Call ActiveWorkbook.UserForm("SingleListForm").loadSingleListForm(ID)
</code>```

Where it says UserForm I have also tried SingleListForm.
Here the runtime error is:

I am trying hard not to use a Global Variable here to pass to the form.
Perhaps I should go to Initialize and try something there.
I am trying to pass the variable to the form and then of course set up the form based on this case and then show the form.  you can't pass with show so you have to find another way to set up.

I just realized I have not called a userform private function from outside of the form before, but I do it with modules all the time.  The first case works in that instance.

Cheers,
-WWC

答:
Just to cover this.  Empty workbook, one button.
The button calls to a private function in the form that does nothing but open a message box.  Testing concept here.
This is all there is:

Doesn't work:

```<code>UserForm1.you_made_it
</code>```

Error at compile, method or data member not found
Same if this:

```<code>With ThisWorkbook
    UserForm1.you_made_it
  End With
</code>```

Then try this:

```<code>Application.Run "UserForm1.you_made_it"
</code>```

Error: Cannot run macro . . . .

Try this from first comment:

```<code>ActiveWorkbook.UserForm("UserForm1").you_made_it
</code>```

Error: Object doesn't support this property or method

So this is the winner from above. Not sure I wanted to go Public but it works.
Doesn't solve how to use a private member in the form but it gets the coding going forward.

```<code>Public Sub you_made_it()

    MsgBox ("you made it")

End Sub
</code>```

So far:
1) Move the private to a module and then call it
2) make the function Public and it works

Thank you,
-WWC

Body:
I have a userform defined as "SingleListForm".
I have a private sub named "loadSingleListForm(ID As Double)"
I am attempting to pass a variable into the form and I was implementing it in the fashion that loadSingleListForm would set the form up based on ID, basically re-using one form to show variable data from variable sources in the listbox.

But calling a standard Intersect from  outside the form (Worksheet_SelectionChange) these two options compile but do not work.

Application.Run "SingleListForm.loadSingleListForm", ID 'ID already declared and assigned

This doesn't work either

Call ActiveWorkbook.UserForm("SingleListForm").loadSingleListForm(ID)

Where it says UserForm I have also tried SingleListForm.
Here the runtime error is:

I am trying hard not to use a Global Variable here to pass to the form.
Perhaps I should go to Initialize and try something there.
I am trying to pass the variable to the form and then of course set up the form based on this case and then show the form.  you can't pass with show so you have to find another way to set up.

I just realized I have not called a userform private function from outside of the form before, but I do it with modules all the time.  The first case works in that instance.

Cheers,
-WWC

Body:
Just to cover this.  Empty workbook, one button.
The button calls to a private function in the form that does nothing but open a message box.  Testing concept here.
This is all there is:

Doesn't work:

UserForm1.you_made_it

Error at compile, method or data member not found
Same if this:

With ThisWorkbook
    UserForm1.you_made_it
  End With

Then try this:

Application.Run "UserForm1.you_made_it"

Error: Cannot run macro . . . .

Try this from first comment:

ActiveWorkbook.UserForm("UserForm1").you_made_it

Error: Object doesn't support this property or method

So this is the winner from above. Not sure I wanted to go Public but it works.
Doesn't solve how to use a private member in the form but it gets the coding going forward.

Public Sub you_made_it()

    MsgBox ("you made it")

End Sub

So far:
1) Move the private to a module and then call it
2) make the function Public and it works

Thank you,
-WWC


问:
Instances in Application variable
Is it correct to instantiate classes and save them in Application variables to then use them and not have to instantiate them in each request?

For example: Instanciate a DbContext and use it directly from de Application variable every time I need.

And this means a real improvement in performance?

In the global asa:

```<code>

    protected void Application_Start()
    {
    Application["db"] = new Models.dbContext();
    }

</code>```

Using then:

```<code>

    db = (dbContext)HttpContext.Current.Application["db"];

</code>```

答: DbContexts should almost always be instantiated and discarded as needed. Connection-pooling and various other behind-the-scenes optimizations mean that this is quite efficient. Otoh, if you're using HttpClient, you should probably aim to create a single one for all calls (as it can't perform connection keep-alive otherwise). It's up to you whether you store in an "Application" variable or just as a global static. But HttpClient is the exception - unless you need to maintain state for the lifetime of your application, or there's some very implementation-specific reason, there are good reasons to avoid having variables with global scope and/or lifetime.

Title: Instances in Application variable

Body:
Is it correct to instantiate classes and save them in Application variables to then use them and not have to instantiate them in each request?

For example: Instanciate a DbContext and use it directly from de Application variable every time I need.

And this means a real improvement in performance?

In the global asa:

    protected void Application_Start()
    {
    Application["db"] = new Models.dbContext();
    }

Using then:

    db = (dbContext)HttpContext.Current.Application["db"];


问:
How do I use pseudo-elements to display content after the main item?
I am trying to achieve the following look:

I want to place the heart on the top right of the price box.   And I've managed to create it but the placement of the heart is hardwired.  And if I change $89k to something bigger, the price box increases in width and the heart is misplaced.

Is there a way that :before or :after pseudo-element can know (or inherit) the width of the price box and place itself accordingly?

Or am I going about this in a wrong manner?

body {
  background-color: lightsalmon;
  transform: scale(3.0);
  transform-origin: 0 0;
}

.home-price {
  color: white;
  border-width: 1px;
  border-style: solid;
  /* width: 50px; */
  text-align: center;
  border-radius: 2px;
  font-family: Helvetica, Arial;
  font-size: 14px;
  font-weight: 300;
  display: inline-block;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}

/* Favorite Marker */
.home-price:before {
  content: "♥";
  color: red;
  display: inline-block;
  position: absolute;
  left: 39px;
  top: -8px;
  text-shadow:  white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px;
}

.home-hot {
  background-color: #C81845;
  border-color: #F5F2F3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div style="height: 25px;margin-top: 30px;">
    <div class="home-price home-hot">
      $89K
    </div>
  </div>
</div></code>```

答:
In this case you can just use right: 0; instead of using hardcoded pixels for left, since you always want the icon to be displayed in the right corner anyway. There is no need to know the exact width of the element.

body {
  background-color: lightsalmon;
  transform: scale(3.0);
  transform-origin: 0 0;
}

.home-price {
  color: white;
  border-width: 1px;
  border-style: solid;
  /* width: 50px; */
  text-align: center;
  border-radius: 2px;
  font-family: Helvetica, Arial;
  font-size: 14px;
  font-weight: 300;
  display: inline-block;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}

/* Favorite Marker */
.home-price:before {
  content: "♥";
  color: red;
  display: inline-block;
  position: absolute;
  right: 0px;
  top: -8px;
  text-shadow:  white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px;
}

.home-hot {
  background-color: #C81845;
  border-color: #F5F2F3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="home-price home-hot">
  $80009K
</div>
<div class="home-price home-hot">
  $89K
</div>
<div class="home-price home-hot">
  $80009,99K
</div></code>```

Body:
I am trying to achieve the following look:

I want to place the heart on the top right of the price box.   And I've managed to create it but the placement of the heart is hardwired.  And if I change $89k to something bigger, the price box increases in width and the heart is misplaced.

Is there a way that :before or :after pseudo-element can know (or inherit) the width of the price box and place itself accordingly?

Or am I going about this in a wrong manner?

body {
  background-color: lightsalmon;
  transform: scale(3.0);
  transform-origin: 0 0;
}

.home-price {
  color: white;
  border-width: 1px;
  border-style: solid;
  /* width: 50px; */
  text-align: center;
  border-radius: 2px;
  font-family: Helvetica, Arial;
  font-size: 14px;
  font-weight: 300;
  display: inline-block;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}

/* Favorite Marker */
.home-price:before {
  content: "♥";
  color: red;
  display: inline-block;
  position: absolute;
  left: 39px;
  top: -8px;
  text-shadow:  white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px;
}

.home-hot {
  background-color: #C81845;
  border-color: #F5F2F3;
}

      $89K

Body:
In this case you can just use right: 0; instead of using hardcoded pixels for left, since you always want the icon to be displayed in the right corner anyway. There is no need to know the exact width of the element.

body {
  background-color: lightsalmon;
  transform: scale(3.0);
  transform-origin: 0 0;
}

.home-price {
  color: white;
  border-width: 1px;
  border-style: solid;
  /* width: 50px; */
  text-align: center;
  border-radius: 2px;
  font-family: Helvetica, Arial;
  font-size: 14px;
  font-weight: 300;
  display: inline-block;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}

/* Favorite Marker */
.home-price:before {
  content: "♥";
  color: red;
  display: inline-block;
  position: absolute;
  right: 0px;
  top: -8px;
  text-shadow:  white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px,
    white 0px 0px 1px;
}

.home-hot {
  background-color: #C81845;
  border-color: #F5F2F3;
}

<div class="home-price home-hot">
  $80009K
</div>
<div class="home-price home-hot">
  $89K
</div>
<div class="home-price home-hot">
  $80009,99K
</div>


问:
bash. break file into lines and then break by first equal sign. handle unescaped characters
I have an environment file that I normally use to set environment variables, but we are switching gears a bit and now want to use that env file to create multiple files from it.

My env file has lines that look like this:

```<code>MAIL_SETTINGS={"service": "service", "auth": { "user": "example.com", "pass": "pass=something"}}
</code>```

I want to spit each line by the first equal sign and have two variables.
MAIL_SETTINGS and {"service": "service", "auth": { "user": "example.com", "pass": "pass=something"}}

I've tried a few things, but keep coming up empty.

```<code>for line in $(cat .env | grep -v ^#); do
  start=$(echo "$line" |cut -d"=" -f1)
  end=$(echo "$line" |cut -d"=" -f2)
  echo "$start = $end"
done
</code>```

A couple issues.

If there are multiple equal signs, it seems to break on each of them

Unescaped characters like { just separates into multiple lines.

How do handle the special characters and only split on first equal sign?

Thanks!

答:
for line in $(cat .env | grep -v ^#) will split each line in the input on spaces, so it's not going to work at all.
You need to read lines using a while loop with read.

Don't use cut to split the line.
You can extract the left and right parts of the first = sign using parameter expansion:

Get the name by chopping off everything after the first =

Get the value by chopping off everything until the first =

Like this:

```<code>while read -r line; do
  name=${line%%=*}
  value=${line#*=}
  echo "$value" > "$name"
done < <(grep -v '^#' .env)
</code>```

Body:
I have an environment file that I normally use to set environment variables, but we are switching gears a bit and now want to use that env file to create multiple files from it.

My env file has lines that look like this:

MAIL_SETTINGS={"service": "service", "auth": { "user": "example.com", "pass": "pass=something"}}

I want to spit each line by the first equal sign and have two variables.
MAIL_SETTINGS and {"service": "service", "auth": { "user": "example.com", "pass": "pass=something"}}

I've tried a few things, but keep coming up empty.

for line in $(cat .env | grep -v ^#); do
  start=$(echo "$line" |cut -d"=" -f1)
  end=$(echo "$line" |cut -d"=" -f2)
  echo "$start = $end"
done

A couple issues.

If there are multiple equal signs, it seems to break on each of them

Unescaped characters like { just separates into multiple lines.

How do handle the special characters and only split on first equal sign?

Thanks!

Body:
for line in $(cat .env | grep -v ^#) will split each line in the input on spaces, so it's not going to work at all.
You need to read lines using a while loop with read.

Don't use cut to split the line.
You can extract the left and right parts of the first = sign using parameter expansion:

Get the name by chopping off everything after the first =

Get the value by chopping off everything until the first =

Like this:

while read -r line; do
  name=${line%%=*}
  value=${line#*=}
  echo "$value" > "$name"
done < <(grep -v '^#' .env)


问:
What are the advantages of installing programs in AppData like Google Chrome?
I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?</p>

答:
As far as I can tell, the only reason why Chrome installs into the Application Data folder is so that non-admin users can install it.

The Chrome installer currently does not allow the user to pick where the application is to be installed. Don't do that – instead, give the user a choice between a per-user (somewhere like App Data) and computer-wide (Program Files) installation.

OwnerDisplayName: Ravi Chhabra

LastEditorDisplayName: charlesroper

OwnerDisplayName: vt


问:
DLL plugin that creates a parented window doesn't handle messages correctly
I'm creating a plugin framework, where my application loads a series of plugin DLL's, then creates a new window and pass this new window's handle to the plugin. The plugin can, then, use this handle to create their own GUI.

Everything seems to be working very well. The only problem is that when I press TAB on a plugin widget (An editbox, for example), it doen't jump to another widget. I figured out that some Windows messages are passed, and some others aren't. The WM_KEYDOWN is passed for other keys, because I can type on the editbox, but this message doesn't handle TAB key.

Hope somebody has a hint.

I'm using Borland VCL with CBuilder, but I think I could use any framework under WIN32 to create these plugins, since they never know how their parent windows were created.

答:
A DLL has its own TApplication object.

to provide  uniform key handling. when the DLL Loads.
assign the DLL::TApplication to the EXE::TApplication
Be sure to do the reverse on exit.

--

Michael

OwnerDisplayName: Alex

LastEditorDisplayName: CodingTheWheel

OwnerDisplayName: Michael


问:
How to prevent package from reloading?
Consider the following

```<code>Needs["Combinatorica`"];
$ContextPath = DeleteCases[$ContextPath, "Combinatorica`"];
</code>```

When I execute it the second time, it's 10 times faster and it doesn't print the compatibility warning.

How does Mathematica know this package has been loaded already?

What's a good way to avoid reloading the package when it's been loaded and removed from $ContextPath?

I'm relying on Combinatorica for some graph algorithms, but I need to redefine Element every time it is loaded, so I'm trying to keep reloading to minimum

答:
From the usage message for Needs:

Needs["context`"] loads an appropriate
  file if the specified context is not
  already in $Packages.

Are you sharing your code with anyone else, or could you just edit your copy of Combinatorica to not add the problematic definition for Element?  (Should probably verify that Combinatorica isn't using it internally in a way that would cause problems.)

Title: How to prevent package from reloading?

Body:
Consider the following

Needs["Combinatorica`"];
$ContextPath = DeleteCases[$ContextPath, "Combinatorica`"];

When I execute it the second time, it's 10 times faster and it doesn't print the compatibility warning.

How does Mathematica know this package has been loaded already?

What's a good way to avoid reloading the package when it's been loaded and removed from $ContextPath?

I'm relying on Combinatorica for some graph algorithms, but I need to redefine Element every time it is loaded, so I'm trying to keep reloading to minimum