问:
Magick++ in VS2010 - unresolved external symbol
I'm trying to use ImageMagick Magick++ for a C++ Project in VS2010.
I installed the Library from here: klick

Then in my Project, I added c:/program files/ImageMagick-6.6.6-Q16/include to the include folders. Then I tried to use Magick++ with this code:

```<code>#include <Magick++.h>
void main(int argc, char ** argv){
    InitializeMagick(*argv);
}
</code>```

But this does not work!
VS2010 returns the following errors:

```<code>error LNK2001: unresolved external symbol "__declspec(dllimport) void __cdecl    Magick::InitializeMagick(char const *)" (__imp_?InitializeMagick@Magick@@YAXPBD@Z)
error LNK1120: 1 unresolved externals
</code>```

What am I doing wrong?

Thanks very much for your help!

UPDATE:

Set Linker -> Input -> Additionnal Dependencies to:

```<code>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;CORE_RL_Magick++_.lib
</code>```

And Linker -> General -> Additionnal Library Directories to:

```<code>C:\Program Files\ImageMagick-6.6.6-Q16\lib
</code>```

It still results in the same error...

UPDATE 2

Opening the .lib files in C:\Program Files\ImageMagick-6.6.6-Q16\lib results in this error:

UPDATE 3

CORE_RL_Magick++_.lib does contain ?InitializeMagick@Magick@@YAXPEBD@Z, but not ?InitializeMagick@Magick@@YAXPBD@Z. Does this mean the .lib file is corrupted?

UPDATE 4

I solved my problem by manually compliling the .lib files.
Thanks to all!

答:
You should also indicate to Visual Studio the .lib to be used for linking

in Linker -> Input -> Additionnal Dependencies

EDIT: and put the path of the magick library

in Linker -> General -> Additionnal Library Directories

EDIT2: if it still doesnt work, then you are calling a fonction with a wrong exported signature.
Launch the msdev tool Dependency Walker. And check if the magick.lib really exports the function whose name is ?InitializeMagick@Magick@@YAXPBD@Z

I am wrong it's not a microsoft tool: Dependency Walker

I was wrong Dependency Walker doesnt open .lib, only Dlls and Exes.
However since you have found ?InitializeMagick@Magick@@YAXPBD@Z in the content of the .lib file, it means that it is reaaly exported this way.

EDIT3: Are you SURE the name and the folder of the additionnal library is correct. I really cannot think of another reason for Visual C++ being unable to link with your library. If your .lib DO contains the string ?InitializeMagick@Magick@@YAXPBD@Z I really think it should link.

EDIT4: could you paste from the file <Magick++.h> the prototype definition of InitializeMagick ?
there is something that makes it be compiled differently between visual c++ and your library supplier. ?InitializeMagick@Magick@@YAXPEBD@Z and ?InitializeMagick@Magick@@YAXPEBD@Z are two DIFFERENT signatures. When including <Magick++.h> Visual C++ understands its differently. (that's why I need to see the prototype of the function)

Body:
I'm trying to use ImageMagick Magick++ for a C++ Project in VS2010.
I installed the Library from here: klick

Then in my Project, I added c:/program files/ImageMagick-6.6.6-Q16/include to the include folders. Then I tried to use Magick++ with this code:

#include <Magick++.h>
void main(int argc, char ** argv){
    InitializeMagick(*argv);
}

But this does not work!
VS2010 returns the following errors:

error LNK2001: unresolved external symbol "__declspec(dllimport) void __cdecl    Magick::InitializeMagick(char const *)" (__imp_?InitializeMagick@Magick@@YAXPBD@Z)
error LNK1120: 1 unresolved externals

What am I doing wrong?

Thanks very much for your help!

UPDATE:

Set Linker -> Input -> Additionnal Dependencies to:

kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;CORE_RL_Magick++_.lib

And Linker -> General -> Additionnal Library Directories to:

C:\Program Files\ImageMagick-6.6.6-Q16\lib

It still results in the same error...

UPDATE 2

Opening the .lib files in C:\Program Files\ImageMagick-6.6.6-Q16\lib results in this error:

UPDATE 3

CORE_RL_Magick++_.lib does contain ?InitializeMagick@Magick@@YAXPEBD@Z, but not ?InitializeMagick@Magick@@YAXPBD@Z. Does this mean the .lib file is corrupted?

UPDATE 4

I solved my problem by manually compliling the .lib files.
Thanks to all!


来源: stackexchange

问:
String to enum in C++
Is there a way to associate a string from a text file with an enum value?

The problem is: I have a few enum values stored as string in a text file which I read on the fly on meeting some condition... Now I want to assign the read value to an enum.

What is the most effective way to do so?  It doesn't need to be the simplest approach.

答:
You can calculate the hash of the string and then use this:</p>

```<code>template <typename H, typename E>
E map_hash(H const key, std::initializer_list<std::pair<H, E>> const il)
{
  auto const i(
    std::find_if(il.begin(),
      il.end(),
      [key](auto& p)
      {
        return p.first == key;
      }
    )
  );

  assert(i != il.end());

  return i->second;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: String to enum in C++

Body:
You can calculate the hash of the string and then use this:

template <typename H, typename E>
E map_hash(H const key, std::initializer_list<std::pair<H, E>> const il)
{
  auto const i(
    std::find_if(il.begin(),
      il.end(),
      [key](auto& p)
      {
        return p.first == key;
      }
    )
  );

  assert(i != il.end());

  return i->second;
}


问:
Pass JS variable into meta tag http-equiv=refresh into url field
Suppose my url is http://example.com#example.org i want to redirect my current tab "example.com" after 5 sec to query parameter "example.org"</p>

```<code><head>
<title></title>

<script type="text/javascript">
var x = window.location.hash.substr(1);
</script>

<meta http-equiv="refresh" content="4;url=x"/>

</head>
<body>
</body>
</code>```

答:
Instead of using a meta tag to refresh, you should just use Javascript with a timeout to handle the redirect instead. A metatag cannot get a value passed in from Javascript using the approach you have.</p>

```<code><script type="text/javascript">
setTimeout(function() {
    window.location.href = window.location.hash.substr(1);
}, 5000);
</script>
</code>```

Body:
Suppose my url is http://example.com#example.org i want to redirect my current tab "example.com" after 5 sec to query parameter "example.org"

<title></title>

<meta http-equiv="refresh" content="4;url=x"/>

Body:
Instead of using a meta tag to refresh, you should just use Javascript with a timeout to handle the redirect instead. A metatag cannot get a value passed in from Javascript using the approach you have.

<script type="text/javascript">
setTimeout(function() {
    window.location.href = window.location.hash.substr(1);
}, 5000);
</script>


问:
Selenium Java - ElementNotInteractableException upon trying to click a link
Within the program I'm trying to make I need to click on links from a variety of websites by searching for links including the word "team". I'm getting an error on a few websites I try it on though, and not on others, any idea why and any fixes available?
My code segment is as follows:

```<code>if (driver.getPageSource().contains("Team"))
{
     driver.findElement(By.partialLinkText("Team")).click();
     return;
}
</code>```

This works on some websites, however on others I'm getting

```<code>Exception in thread "AWT-EventQueue-0" org.openqa.selenium.ElementNotInteractableException:
</code>```

I don't know the source of this problem however, as I need it to work on multiple pages, for example I get that response on https://www.calipercorp.com/about-us/

Any workarounds or help given would be greatly appreciated.

答:
Let's try this:

```<code>if (driver.getPageSource().contains("Team"))
{
     WebElement elem = driver.findElement(By.partialLinkText("Team"));
     //Check if the element's type is a link
     if (elem.getTagName().equals("a"){
          elem.click();
     }
     return;
}
</code>```

Or you can using the method getAttribute("href") to get the link url and then go to this link instead of click on it

```<code>if (driver.getPageSource().contains("Team"))
    {
         WebElement elem = driver.findElement(By.partialLinkText("Team"));
         //get the href attr
         String url = elem.getAttribute("href");
         //add code to go to the url above
    }
</code>```

Body:
Within the program I'm trying to make I need to click on links from a variety of websites by searching for links including the word "team". I'm getting an error on a few websites I try it on though, and not on others, any idea why and any fixes available?
My code segment is as follows:

if (driver.getPageSource().contains("Team"))
{
     driver.findElement(By.partialLinkText("Team")).click();
     return;
}

This works on some websites, however on others I'm getting

Exception in thread "AWT-EventQueue-0" org.openqa.selenium.ElementNotInteractableException:

I don't know the source of this problem however, as I need it to work on multiple pages, for example I get that response on https://www.calipercorp.com/about-us/

Any workarounds or help given would be greatly appreciated.

Body:
Let's try this:

if (driver.getPageSource().contains("Team"))
{
     WebElement elem = driver.findElement(By.partialLinkText("Team"));
     //Check if the element's type is a link
     if (elem.getTagName().equals("a"){
          elem.click();
     }
     return;
}

Or you can using the method getAttribute("href") to get the link url and then go to this link instead of click on it

if (driver.getPageSource().contains("Team"))
    {
         WebElement elem = driver.findElement(By.partialLinkText("Team"));
         //get the href attr
         String url = elem.getAttribute("href");
         //add code to go to the url above
    }


问:
Quartiles query in sql
I have code like this:

```<code>SELECT `pelamarmagisterrangkuman`.`major` AS `ProgramStudi`,
count(IPKS1) as N,
AVG(IPKS1) as Mean,
MIN(IPKS1) as Minimum,
MAX(IPKS1) as Maximum,
StdDev(IPKS1) as StDev,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(IPKS1 ORDER BY IPKS1 SEPARATOR ','),
',', 50/100 * COUNT(*) + 1), ',', -1) AS decimal) AS `Median`,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(IPKS1 ORDER BY IPKS1 SEPARATOR ','),
',', 25/100 * COUNT(*) + 1), ',', -1) AS decimal) AS `Q1`,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(IPKS1 ORDER BY IPKS1 SEPARATOR ','),
',', 75/100 * COUNT(*) + 1), ',', -1) AS decimal) AS `Q3`
FROM `pelamarmagisterrangkuman` where `pelamarmagisterrangkuman`.`IPKS1` != 0 and `pelamarmagisterrangkuman`.`TahunDaftar` = 2012 group by `pelamarmagisterrangkuman`.`major`
</code>```

COUNT, AVG, MIN, MAX, and MIN can work properly. But, quartiles cannot work properly. I mean, the result of the code above is integer values. But, the result that I expected is not just integer value, but also float value because my data is in float and integer value. What may I do to fix that? Thanks in advance

答:
Avoid integers in the arithmetic e.g.

50.0/100.0 *  cast(COUNT(*) as decimal) + 1.0

Title: Quartiles query in sql

Body:
I have code like this:

SELECT `pelamarmagisterrangkuman`.`major` AS `ProgramStudi`,
count(IPKS1) as N,
AVG(IPKS1) as Mean,
MIN(IPKS1) as Minimum,
MAX(IPKS1) as Maximum,
StdDev(IPKS1) as StDev,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(IPKS1 ORDER BY IPKS1 SEPARATOR ','),
',', 50/100 * COUNT(*) + 1), ',', -1) AS decimal) AS `Median`,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(IPKS1 ORDER BY IPKS1 SEPARATOR ','),
',', 25/100 * COUNT(*) + 1), ',', -1) AS decimal) AS `Q1`,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(
GROUP_CONCAT(IPKS1 ORDER BY IPKS1 SEPARATOR ','),
',', 75/100 * COUNT(*) + 1), ',', -1) AS decimal) AS `Q3`
FROM `pelamarmagisterrangkuman` where `pelamarmagisterrangkuman`.`IPKS1` != 0 and `pelamarmagisterrangkuman`.`TahunDaftar` = 2012 group by `pelamarmagisterrangkuman`.`major`

COUNT, AVG, MIN, MAX, and MIN can work properly. But, quartiles cannot work properly. I mean, the result of the code above is integer values. But, the result that I expected is not just integer value, but also float value because my data is in float and integer value. What may I do to fix that? Thanks in advance


问:
Can an SPA issue parallel async queries against a single GraphQL server?
GraphQL usually serves at a single endpoint.  Can I have, for example, an SPA page with a half dozen live status displays each making an independent promise-wrapped request to that same endpoint?  The query payloads take time to assemble and will not complete in the same order as requests were received.  Further, some status payloads may take seconds or longer to complete.  I don't want to batch the requests, I want the data for each display delivered as soon as its data is available.   </p>

答: Yes, you can, you will lose one of the benefits of GraphQL but other than the small amount of latency that the GraphQL server adds, you won't experience downsides until you run into needing to horizontally scale the GraphQL server.</p>


问:
jQuery selecting the top li of a menu
Sorry for the noobish question.

I've got a menu similar to this:

```<code><div id="navigation">
  <ul>
    <li><a href="url">menu item</a></li>
    <li><a href="url">menu item</a>
      <ul>
        <li><a href="url">sub menu item</a></li>
        <li><a href="url">sub menu item</a>
          <ul>
            <li><a href="url">sub sub menu item</a></li>
            <li><a href="url">sub sub menu item</a></li>
            <li><a href="url">sub sub menu item</a></li>
          </ul>
        </li>
        <li><a href="url">sub menu item</a></li>
        <li><a href="url">sub menu item</a></li>
      </ul>
    </li>
    <li><a href="url">menu item</a></li>
    <li><a href="url">menu item</a></li>
  </ul>
</div>
</code>```

I'm trying to change the class for the selected page. I'm part way there with this:

```<code>$(function(){
     var path = location.pathname.substring(1);
     if ( path ){
  $('#navigation a[href$="' + path + '"]').parent().attr('class', 'selected');
  }
  });
</code>```

Which changes the class on the parent li. Cool. But what I really want to do is change the class on top level li. In other words if a "sub sub menu item" is selected goes all the way up the tree and changes the very first li that contains that link.

Would appreciate any help at all.

Thanks,

Andy.

答:
You can use .parents() and :last (since they're returned in the order found...top parent is last) when looking for the
, like this:

```<code>$('#navigation a[href$="' + path + '"]').parents('li:last').addClass('selected');
</code>```

Also .addClass() is probably what you're after here :)

ContentLicense: CC BY-SA 2.5

Title: jQuery selecting the top li of a menu

Body:
Sorry for the noobish question.

I've got a menu similar to this:

menu item

menu item

sub menu item

sub menu item

sub sub menu item

sub sub menu item

sub sub menu item

sub menu item

sub menu item

menu item

menu item

I'm trying to change the class for the selected page. I'm part way there with this:

$(function(){
     var path = location.pathname.substring(1);
     if ( path ){
  $('#navigation a[href$="' + path + '"]').parent().attr('class', 'selected');
  }
  });

Which changes the class on the parent li. Cool. But what I really want to do is change the class on top level li. In other words if a "sub sub menu item" is selected goes all the way up the tree and changes the very first li that contains that link.

Would appreciate any help at all.

Thanks,

Andy.

Body:
You can use .parents() and :last (since they're returned in the order found...top parent is last) when looking for the <li>, like this:

$('#navigation a[href$="' + path + '"]').parents('li:last').addClass('selected');

Also .addClass() is probably what you're after here :)


问:
Facebook getLoginStatus was not getting any response
```<code><div id="fb-root"></div>
      <script>
        window.fbAsyncInit = function() {
          FB.init({
            appId      : '261852174300349',
            status     : true,
            cookie     : true,
            xfbml      : true,
            oauth      : true,
          });
        };
        (function(d){
           var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js";
           d.getElementsByTagName('head')[0].appendChild(js);
         }(document));

       //LOGIN FUNCTION
       function login() {
           FB.getLoginStatus(function(response) {
                console.log(response)
            });

     }
      </script>
      <div onclick="login();">Login with Facebook</div>
</code>```

As per facebook document to check user is already login or not we can use FB.getLoginStatus get the user is log in or not but in my cause i can"t able to get any response

答:
try this instead. It will call the login function right after being initialized. In your current code</p>

```<code><div id="fb-root"></div>
      <script>
        window.fbAsyncInit = function() {
          FB.init({
            appId      : '261852174300349',
            status     : true,
            cookie     : true,
            xfbml      : true,
            oauth      : true,
          });
//LOGIN FUNCTION
           function login() {
               FB.getLoginStatus(function(response) {
                    console.log(response)
                });

         }
        };
        (function(d){
           var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js";
           d.getElementsByTagName('head')[0].appendChild(js);
         }(document));

      </script>
      <div onclick="login();">Login with Facebook</div>
</code>```

Body:
Login with Facebook

As per facebook document to check user is already login or not we can use FB.getLoginStatus get the user is log in or not but in my cause i can"t able to get any response

Body:
try this instead. It will call the login function right after being initialized. In your current code

<div id="fb-root"></div>
      <script>
        window.fbAsyncInit = function() {
          FB.init({
            appId      : '261852174300349',
            status     : true,
            cookie     : true,
            xfbml      : true,
            oauth      : true,
          });
//LOGIN FUNCTION
           function login() {
               FB.getLoginStatus(function(response) {
                    console.log(response)
                });

         }
        };
        (function(d){
           var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js";
           d.getElementsByTagName('head')[0].appendChild(js);
         }(document));

      </script>
      <div onclick="login();">Login with Facebook</div>


问:
Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed
When trying to deploy my app to the Android device I am getting the following error:

```<code>Deployment failed because of an internal error: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]
</code>```

I am aware of this question but the app is not installed. It has been removed/partially removed by Visual Studio during the attempt to deploy.

In the past I solved this by downloading the app from the google play store and then removing it from settings->Application manager. However, now i am getting the error "incompatible update" when it is trying to install it.

I tried to remove it using Titanium Backup and few other things but no luck.

EDIT 1

I realised (from @Motz) that I haven't mentioned that the obvious solution doesn't work. Namely, the app doesn't appear in Settings->Apps

答:
In case this helps someone,
I deployed my app to google play, when I uninstalled it and tried to run a debug on my device (new version) I was getting this failed update message.

I couldn't see the app in my device (it was already uninstalled) so I:

Installed the first version again from google play

Opened Settings/App/App name

Cleared the Data

Cleared the Cache

Uninstalled the app

Now you can deploy the debug version again to the device :)

Body:
When trying to deploy my app to the Android device I am getting the following error:

Deployment failed because of an internal error: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]

I am aware of this question but the app is not installed. It has been removed/partially removed by Visual Studio during the attempt to deploy.

In the past I solved this by downloading the app from the google play store and then removing it from settings->Application manager. However, now i am getting the error "incompatible update" when it is trying to install it.

I tried to remove it using Titanium Backup and few other things but no luck.

EDIT 1

I realised (from @Motz) that I haven't mentioned that the obvious solution doesn't work. Namely, the app doesn't appear in Settings->Apps


问:
is db_column changing my mongodb field?
i'm new here. I'm having a problem with django where i have 'type' which is a reserved keyword as a column in mongodb. Based on answers in stackoverflow, I solved it by applying https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.db_column

My code currently looked like this

```<code>discountType = StringField(required=True, db_column='type')
</code>```

However, the problem is the field 'type' was changed to 'discountType'. Is there a way to prevent the model from changing the field name?

答:
For mongo db_field is used instead.

See: http://docs.mongoengine.org/guide/defining-documents.html#field-arguments

```<code>discountType = StringField(required=True, db_field ='type')
</code>```

Title: is db_column changing my mongodb field?

Body:
i'm new here. I'm having a problem with django where i have 'type' which is a reserved keyword as a column in mongodb. Based on answers in stackoverflow, I solved it by applying https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.db_column

My code currently looked like this

discountType = StringField(required=True, db_column='type')

However, the problem is the field 'type' was changed to 'discountType'. Is there a way to prevent the model from changing the field name?

Body:
For mongo db_field is used instead.

See: http://docs.mongoengine.org/guide/defining-documents.html#field-arguments

discountType = StringField(required=True, db_field ='type')


问:
Why is GOPATH not recognized by google-cloud-sdk go-app-stager?
When I try to update my appengine project, it gives me an error.

```<code>$ sudo gcloud app deploy
ERROR: (gcloud.app.deploy) Staging command [/usr/local/google-cloud-sdk/platform/google_appengine/goroot-1.6/bin/go-app-stager /Users/baz/app/app.yaml /tmp/tmpSZLK/tmpIQ4] failed with return code [1].

------------------------------------ STDOUT ------------------------------------
------------------------------------ STDERR ------------------------------------
2017/07/08 16:22:06 failed analyzing /Users/baz/app: cannot find package "bitbucket.org/foo/bar" in any of:
    ($GOROOT not set)
    ($GOPATH not set)
GOPATH:

$ echo $GOPATH
/Users/baz/go
$ go env GOPATH
/Users/baz/go
</code>```

Clearly GOPATH is set (I export it in my .bash_profile).

答:
TL;DR - Do not use sudo for deploying the app.

Longer version

You're running the gcloud app deploy command using sudo. sudo by the nature of the command will not retain the current set of environment variables when running the command as root user.

Try deploying your app engine app without sudo:

```<code>gcloud app deploy
</code>```

If you do need to run you command as sudo (which is a smell that your setup is broken somehow), you can look at this post. Although, I would recommend looking into the possibility of running your command without sudo.

Body:
When I try to update my appengine project, it gives me an error.

$ sudo gcloud app deploy
ERROR: (gcloud.app.deploy) Staging command [/usr/local/google-cloud-sdk/platform/google_appengine/goroot-1.6/bin/go-app-stager /Users/baz/app/app.yaml /tmp/tmpSZLK/tmpIQ4] failed with return code [1].

------------------------------------ STDOUT ------------------------------------
------------------------------------ STDERR ------------------------------------
2017/07/08 16:22:06 failed analyzing /Users/baz/app: cannot find package "bitbucket.org/foo/bar" in any of:
    ($GOROOT not set)
    ($GOPATH not set)
GOPATH:

$ echo $GOPATH
/Users/baz/go
$ go env GOPATH
/Users/baz/go

Clearly GOPATH is set (I export it in my .bash_profile).

Body:
TL;DR - Do not use sudo for deploying the app.

Longer version

You're running the gcloud app deploy command using sudo. sudo by the nature of the command will not retain the current set of environment variables when running the command as root user.

Try deploying your app engine app without sudo:

gcloud app deploy

If you do need to run you command as sudo (which is a smell that your setup is broken somehow), you can look at this post. Although, I would recommend looking into the possibility of running your command without sudo.


问:
How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?
I am trying to do a go get:

```<code>go get github.com/go-sql-driver/mysql
</code>```

and it fails with the following error:

```<code>package github.com/go-sql-driver/mysql: cannot download, $GOPATH not set. For more details see: go help gopath
</code>```

when I do a go env , a list of Go values is shown as below:

```<code>ubuntu@ip-xxx-x-xx-x:~$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH=""
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread"
CGO_ENABLED="1"
</code>```

clearly the GOPATH is not set, how and where do I set it?

I see many threads that mention this error but none that provide an answer to my question, which file needs to be edited to provide a value for this path?

答:
Edit your ~/.bash_profile to add the following line:

```<code>$ export GOPATH=$HOME/work
</code>```

Save and exit your editor. Then, source your ~/.bash_profile

```<code>$ source ~/.bash_profile
</code>```

Note: Set the GOBIN path to generate a binary file when go install is run

```<code>$ export GOBIN=$HOME/work/bin
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do a go get:

go get github.com/go-sql-driver/mysql

and it fails with the following error:

package github.com/go-sql-driver/mysql: cannot download, $GOPATH not set. For more details see: go help gopath

when I do a go env , a list of Go values is shown as below:

ubuntu@ip-xxx-x-xx-x:~$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH=""
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread"
CGO_ENABLED="1"

clearly the GOPATH is not set, how and where do I set it?

I see many threads that mention this error but none that provide an answer to my question, which file needs to be edited to provide a value for this path?

Body:
Edit your ~/.bash_profile to add the following line:

$ export GOPATH=$HOME/work

Save and exit your editor. Then, source your ~/.bash_profile

$ source ~/.bash_profile

Note: Set the GOBIN path to generate a binary file when go install is run

$ export GOBIN=$HOME/work/bin


问:
What is the connection between LocationRequest object and LocationChangeListener
I have been following this for my application that needs to get current location updates even if 10 steps are walked, or maybe every 2 minutes, but I think time based would be more demanding in terms of battery usage, in the begning documentation says:

your app specifies the required level of accuracy/power consumption and desired update interval, and the device automatically makes the appropriate changes to system settings. These settings are defined by the LocationRequest data object.

what does it mean? accuracy level, and update interval?

After that when its explaining these things they say

To store parameters for requests to the fused location provider, create a LocationRequest. The parameters determine the level of accuracy for location requests.

does it mean that we can get current location update like updated latlng with setInterval()? if so then why we have to use onlocationchangelistener? if requirement has been fulfilled by location request

Thanks

答:
There is exactly two main terms about location, these are

Getting last known location (old location)

Receiving location updates (fresh location)

Understanding the those terms will help in the relation between LocationRequest and it's listener.

Getting last known location

The location api can give the last obtained location for given provider, without location request. This location could be obtained at any time for example 3 - 5 hours ago and by an app(including yours). There is no need to say 'hey provider please give me fresh location', so we don't need LocationRequest object.

Receiving location updates

This is where we need to say 'hey provider please give me fresh location at every 30 seconds with high accuracy'

To define our above request, we need to create LocationRequest object.

To receive result of our request, we need to create listener(receiving process is asynchronous)

This is the relation between LocationRequest and listener.

LocationRequest object is used for two purposes

As mentioned above, to make location request for fused provider

To prompt a dialog to make adequate requirements of location request(for example level of accuracy)


问:
CSS Override background without changing or restoring background image
When I try in stylish(chrome)
*{
      background : black !important
}
all the background images are overridden,

I was wondering if there is a way to restore the background images or keep them intact.

Thanks

答:
Use background-color instead of background

```<code>*:not([background-image]) {
  background-color:black!important;
}
</code>```

div {
  width: 200px;
  height: 200px;
  background-color: red;
}

.bg {
  background-image: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTqy1uodNithL90ttojytSP2imO4RC1y3qlm_ebZdRmNWh_8juV9Q');
}

*:not([background-image]) {
  background-color:black!important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>I am Test</div>
<div class="bg">I am Test2</div></code>```

Body:
Use background-color instead of background

*:not([background-image]) {
  background-color:black!important;
}

div {
  width: 200px;
  height: 200px;
  background-color: red;
}

.bg {
  background-image: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTqy1uodNithL90ttojytSP2imO4RC1y3qlm_ebZdRmNWh_8juV9Q');
}

*:not([background-image]) {
  background-color:black!important;
}

<div>I am Test</div>
<div class="bg">I am Test2</div>


问:
Change Angular 2/4 Material default styles for "md-menu"
I'm trying to change default Angular Material styles of md-menu. The problem is the Angular Material generates elements dynamically and I can't get access to them from my HTML.

Here is my DOM:

And here is my component HTML (md-menu generates that DOM):

```<code><md-toolbar color="primary">
  <h1>Logo</h1>
  <span class="spacer"></span>
  <img src="../../../images/avatar-default.png" class="avatar" [mdMenuTriggerFor]="userMenu" />

  <md-menu #userMenu="mdMenu">
    <button md-menu-item>{{username}}</button>
    <button md-menu-item>Log Out</button>
  </md-menu>
</md-toolbar>
</code>```

I know that I can get access to that div (selected on the picture) from global styles using .mat-menu-content {...}, but it will affect other elements with such classes. And I'm unable to set styles to this div from component CSS, because the element is outside component scope. So I'm trying to find the way to change styles of this element from component CSS and without affecting other elements with such style.

If there is a way to implement it, please, let me know.

答: Described in the picture below,Maybe this doc would help

Body:
I'm trying to change default Angular Material styles of md-menu. The problem is the Angular Material generates elements dynamically and I can't get access to them from my HTML.

Here is my DOM:

And here is my component HTML (md-menu generates that DOM):

<md-toolbar color="primary">

Logo

  <md-menu #userMenu="mdMenu">
    <button md-menu-item>{{username}}</button>
    <button md-menu-item>Log Out</button>
  </md-menu>
</md-toolbar>

I know that I can get access to that div (selected on the picture) from global styles using .mat-menu-content {...}, but it will affect other elements with such classes. And I'm unable to set styles to this div from component CSS, because the element is outside component scope. So I'm trying to find the way to change styles of this element from component CSS and without affecting other elements with such style.

If there is a way to implement it, please, let me know.


问:
Ms Access multi-select listbox mover
I have two list boxes (lfmVocabulary and lfmVocabularyAssign). They are both unbound along with the form and I'm having trouble achieving certain aspects of the code design.

Thus far, I am able to populate the first list form with the values through a query recordset, but I'm unable to transfer the items from one box to the other.

In an attempt to achieve this, I placed the code in a module as follows

```<code>Option Compare Database

Public Sub MoveListBoxItems(lfmVocabularyAssign As ListBox, _
lfmVocabulary As ListBox)

Dim intListX As Integer

For intListX = lfmVocabulary.ListCount = -1 To 0
    If lfmVocabulary.Selected(intListX) Then
     lfmVocabularyAssign.AddItem lfmVocabulary.List(intListX)
     lfmVocabulary.RemoveItem intListX
    End If
Next
End Sub
</code>```

In the form, I have the following code:

```<code>Option Explicit

Dim db As Database
Dim rs As Recordset

Private Sub cmdAdd_Click()

MoveListBoxItems lfmVocabulary, lfmVocabularyAssign

End Sub

Private Sub cmdSelectAll1_Click()

    Dim n As Integer

    With Me.lfmVocabulary
        For n = 0 To .ListCount - 1
            .Selected(n) = True
        Next n
    End With

End Sub

Private Sub Form_Load()

    Set db = CurrentDb
    Set rs = db.OpenRecordset("qryVocabularyDefinitions")

    Me.lfmVocabulary.RowSource = ""
    Do Until rs.EOF
        Me.lfmVocabulary.AddItem rs!Vocabulary
        rs.MoveNext
    Loop

End Sub
</code>```

I am kinda new to Access and coding in general and I've been scouring the Internet looking for a solution.

I would offer a thousand thanks to anyone that can help me :D

答:
In MS Access forms (unlike Excel's userforms), you can directly assign a query to a ListBox.RowSource without needing to iterate through a recordset:

```<code>Me.lfmVocabulary.RowSource = "qryVocabularyDefinitions"
Me.lfmVocabulary.RowSourceType = "Table/Query"
Me.lfmVocabulary.Requery
</code>```

And to update the values, pass a dynamic query using the selected items of previous listbox:

```<code>Dim in_clause As String: in_clause = ""
Dim strSQL As String, i As Integer

' ITERATE TO BUILD COMMA-SEPARATED LIST FOR SQL IN() CLAUSE
With Me.lfmVocabulary
    For n = 0 To .ListCount - 1
       If .Selected(n) = True Then
           in_clause = in_clause & .ItemData(n) & ", "
       End If
    Next n
End With

' REMOVE LAST COMMA AND SPACE
in_clause = Left(in_clause, Len(in_clause)-2)

strSQL = "SELECT * FROM qryVocabularyDefinitions" _
           & " WHERE ID IN (" & in_clause & ")"

Me.lfmVocabularyAssign.RowSource = strSQL
Me.lfmVocabularyAssign.RowSourceType = "Table/Query"
Me.lfmVocabularyAssign.Requery
</code>```

Title: Ms Access multi-select listbox mover

Body:
I have two list boxes (lfmVocabulary and lfmVocabularyAssign). They are both unbound along with the form and I'm having trouble achieving certain aspects of the code design.

Thus far, I am able to populate the first list form with the values through a query recordset, but I'm unable to transfer the items from one box to the other.

In an attempt to achieve this, I placed the code in a module as follows

Option Compare Database

Public Sub MoveListBoxItems(lfmVocabularyAssign As ListBox, _
lfmVocabulary As ListBox)

Dim intListX As Integer

For intListX = lfmVocabulary.ListCount = -1 To 0
    If lfmVocabulary.Selected(intListX) Then
     lfmVocabularyAssign.AddItem lfmVocabulary.List(intListX)
     lfmVocabulary.RemoveItem intListX
    End If
Next
End Sub

In the form, I have the following code:

Option Explicit

Dim db As Database
Dim rs As Recordset

Private Sub cmdAdd_Click()

MoveListBoxItems lfmVocabulary, lfmVocabularyAssign

End Sub

Private Sub cmdSelectAll1_Click()

    Dim n As Integer

    With Me.lfmVocabulary
        For n = 0 To .ListCount - 1
            .Selected(n) = True
        Next n
    End With

End Sub

Private Sub Form_Load()

    Set db = CurrentDb
    Set rs = db.OpenRecordset("qryVocabularyDefinitions")

    Me.lfmVocabulary.RowSource = ""
    Do Until rs.EOF
        Me.lfmVocabulary.AddItem rs!Vocabulary
        rs.MoveNext
    Loop

End Sub

I am kinda new to Access and coding in general and I've been scouring the Internet looking for a solution.

I would offer a thousand thanks to anyone that can help me :D

Body:
In MS Access forms (unlike Excel's userforms), you can directly assign a query to a ListBox.RowSource without needing to iterate through a recordset:

Me.lfmVocabulary.RowSource = "qryVocabularyDefinitions"
Me.lfmVocabulary.RowSourceType = "Table/Query"
Me.lfmVocabulary.Requery

And to update the values, pass a dynamic query using the selected items of previous listbox:

Dim in_clause As String: in_clause = ""
Dim strSQL As String, i As Integer

' ITERATE TO BUILD COMMA-SEPARATED LIST FOR SQL IN() CLAUSE
With Me.lfmVocabulary
    For n = 0 To .ListCount - 1
       If .Selected(n) = True Then
           in_clause = in_clause & .ItemData(n) & ", "
       End If
    Next n
End With

' REMOVE LAST COMMA AND SPACE
in_clause = Left(in_clause, Len(in_clause)-2)

strSQL = "SELECT * FROM qryVocabularyDefinitions" _
           & " WHERE ID IN (" & in_clause & ")"

Me.lfmVocabularyAssign.RowSource = strSQL
Me.lfmVocabularyAssign.RowSourceType = "Table/Query"
Me.lfmVocabularyAssign.Requery


问:
Does node_modules’s size affect to ionic app’s size?
node_modules's size is 230MB and app's size is 34MB(with crosswalk).

Does reduce app's size if reduce node_modules's size?

Does node_modules's size affect to app's size?

答:
It depends on what you're doing with the dependencies. You can have client side dependencies, such as Angular, which will be in the final application packages. You can also have building dependencies, such as some parts of the Cordova platform, that will be used only during application packaging, but will not be merged in the file that will be uploaded to the app stores.

There's a lot of good material online on Ionic 2 improvements for production apps. I recommend starting with this one: https://blog.khophi.co/optimize-ionic-2-app-production/.


问:
blackberry reading a text file and updating after sort
I am successfully able to read and print the contents of a text file. My text file contains 5 data entries such as

```
Rashmi 120
Prema 900
```

It must sort only the integers in descending order and swap the respective names attached to them. the first column of serial number must remain the same. Each time a new entry is made that score must be compared to the existing 5 records and placed accordingly with new name and score.

Since this is blackberry programming and blackberry APIs don't support Collections.sort,please tell me how do I do this. I tried using SimpleSortingVector but I am unable to put it into coding form.

答:
i believe u need to start with your own logic like

1) sorting depends on comparison
2) before making any comparison u need to split each string by spaces
3) after splitting save the name and numbers in different arrays
4) compare the numbers and accordingly do sorting
5) after this merge the array contents using indexing

m just giving u a way may be its not the perfect but drilling down may refine logics and usage of the api

Body:
I am successfully able to read and print the contents of a text file. My text file contains 5 data entries such as

Rashmi 120
Prema 900

It must sort only the integers in descending order and swap the respective names attached to them. the first column of serial number must remain the same. Each time a new entry is made that score must be compared to the existing 5 records and placed accordingly with new name and score.

Since this is blackberry programming and blackberry APIs don't support Collections.sort,please tell me how do I do this. I tried using SimpleSortingVector but I am unable to put it into coding form.


问:
Display / Hide Advert Based on Role
I created a Web Control which is basically a div for holding a mobile banner but I wish to hide it if the user is an Admin

I have tried:

```<code><mob:MobileBanner runat="server" ID="MobileBanner" Visible='<%# Not HttpContext.Current.User.IsInRole("Admin") %>' />
</code>```

but it doesn't seem to work.

I was also thinking of surrounding the html but cannot seem to get that working so it checks if you're an admin and if not it writes the advert code to the client, which includes the css link.

There is a similar question (how to enable and disable button based on user role?) but that is an ASP.NET Server Side button not a basic Web Control which just holds html.

Those of you who want code, add a new Web Control to the project then paste in this code.

```<code><link href = "my_css_file_here.css" rel="stylesheet" type="text/css" />

<div Class="my_banner_container">
    <!--My banner code goes here -->
</div>
</code>```

I know I could create a container in the master document with runat="server" then use:

```<code>my_container.Visible = Not HttpContext.Current.User.IsInRole("Admin")
</code>```

but I also need to change the padding-top: 130px; to padding-top: 50px; and swap back if the admin logs out or the user is not an admin.

I know if could have a link like this for non Admins:

```<code><link href = "my_css_file_130_here.css" rel="stylesheet" type="text/css" runat="server" />
</code>```

which would then become for Admins:

```<code><link href = "my_css_file_50_here.css" rel="stylesheet" type="text/css" runat="server" />
</code>```

then from code behind have 2 different css for the padding-top and change the href based on if the user is an admin or not

```<code>body {
     padding-top: 130px;
}
</code>```

or

```<code>body {
     padding-top: 50px;
}
</code>```

Any ideas on how to achieve this or a better way than my complicated idea?

答:
What I did in the end was to add the link for the stylesheet and make it runat="server" with the href set to the 120px padding

In form_load (outside of PostBack checking so always checked) of the master doc:

```<code>If HttpContext.Current.User.IsInRole("Admin") Then
    my_container.Visible = False
    my_stylesheet.Href = "~/path_to_file50.css"
Else
    my_container.Visible = True
    my_stylesheet.Href = "~/path_to_file120.css"
End If
</code>```

In those css files I set the

```<code>padding-top: 50px;
</code>```

or

```<code>padding-top: 120px;
</code>```

then left the rest of css in another file and all seems to be working now and by setting:

```<code>my_container.Visible = False
</code>```

should stop Google complaining that I am creating impressions whilst on my own site.

Title: Display / Hide Advert Based on Role

Body:
I created a Web Control which is basically a div for holding a mobile banner but I wish to hide it if the user is an Admin

I have tried:

<mob:MobileBanner runat="server" ID="MobileBanner" Visible='<%# Not HttpContext.Current.User.IsInRole("Admin") %>' />

but it doesn't seem to work.

I was also thinking of surrounding the html but cannot seem to get that working so it checks if you're an admin and if not it writes the advert code to the client, which includes the css link.

There is a similar question (how to enable and disable button based on user role?) but that is an ASP.NET Server Side button not a basic Web Control which just holds html.

Those of you who want code, add a new Web Control to the project then paste in this code.

<link href = "my_css_file_here.css" rel="stylesheet" type="text/css" />

I know I could create a container in the master document with runat="server" then use:

my_container.Visible = Not HttpContext.Current.User.IsInRole("Admin")

but I also need to change the padding-top: 130px; to padding-top: 50px; and swap back if the admin logs out or the user is not an admin.

I know if could have a link like this for non Admins:

<link href = "my_css_file_130_here.css" rel="stylesheet" type="text/css" runat="server" />

which would then become for Admins:

<link href = "my_css_file_50_here.css" rel="stylesheet" type="text/css" runat="server" />

then from code behind have 2 different css for the padding-top and change the href based on if the user is an admin or not

body {
     padding-top: 130px;
}

or

body {
     padding-top: 50px;
}

Any ideas on how to achieve this or a better way than my complicated idea?

Body:
What I did in the end was to add the link for the stylesheet and make it runat="server" with the href set to the 120px padding

In form_load (outside of PostBack checking so always checked) of the master doc:

If HttpContext.Current.User.IsInRole("Admin") Then
    my_container.Visible = False
    my_stylesheet.Href = "~/path_to_file50.css"
Else
    my_container.Visible = True
    my_stylesheet.Href = "~/path_to_file120.css"
End If

In those css files I set the

padding-top: 50px;

or

padding-top: 120px;

then left the rest of css in another file and all seems to be working now and by setting:

my_container.Visible = False

should stop Google complaining that I am creating impressions whilst on my own site.


问:
What is the difference here?
I am learning python and here is a small code that instructions want me to write.

First, def a function called cube that takes an argument called
  number. Don't forget the parentheses and the colon! Make that function
  return the cube of that number (i.e. that number multiplied by itself
  and multiplied by itself once again). Define a second function called
  by_three that takes an argument called number.

if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.

What I did first was;

```<code>def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        cube(number)
        return number
    else:
        return False
</code>```

but apparently in this, by_three(number) returns number itself. so to my understandings, the cube(Number) and return number doesnt work by line order?

this works:

```<code>def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        return cube(number)
    else:
        return False
</code>```

I know why this works, but I dont get why the other one doesnt.

答:
Python passes pass variables by assignment. That means when you pass an argument to a function, the parameter that corresponds to the argument is assigned a reference to the argument object.

In your code, when you pass number to the cube() function, the number parameter of cube() is assigned a reference to that object. However, you never do anything with that reference. You simply return a new object. This number is never changed. But even if you did attempt to change number inside of cube(), that would fail as well because Python would treat the assignment as a new declaration of a variable named number inside of cube().

This behavior can be demonstrated with a simple example:

```<code>>>> def func(n):
    print(id(n))
    print(id(n ** 3))
    n = 2
    print(id(n))

>>> def func2(n):
    print(id(n))
    func(n)

>>> func2(3)
1612339504
1612339504
1612339888
1612339488
>>>
</code>```

The id() function returns a unique number for each object created in your program. As you can see above, the 3 passed into func2()is the same object passed into func(). However, when we use n in the expression n ** 3, a new object is created. The same thing applies to the assignment n = 2. When we do that, Python treats that as a variable declaration, and a new variable local to func() is created with a reference to the new object 2.

Title: What is the difference here?

Body:
I am learning python and here is a small code that instructions want me to write.

First, def a function called cube that takes an argument called
  number. Don't forget the parentheses and the colon! Make that function
  return the cube of that number (i.e. that number multiplied by itself
  and multiplied by itself once again). Define a second function called
  by_three that takes an argument called number.

if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.

What I did first was;

def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        cube(number)
        return number
    else:
        return False

but apparently in this, by_three(number) returns number itself. so to my understandings, the cube(Number) and return number doesnt work by line order?

this works:

def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        return cube(number)
    else:
        return False

I know why this works, but I dont get why the other one doesnt.

Body:
Python passes pass variables by assignment. That means when you pass an argument to a function, the parameter that corresponds to the argument is assigned a reference to the argument object.

In your code, when you pass number to the cube() function, the number parameter of cube() is assigned a reference to that object. However, you never do anything with that reference. You simply return a new object. This number is never changed. But even if you did attempt to change number inside of cube(), that would fail as well because Python would treat the assignment as a new declaration of a variable named number inside of cube().

This behavior can be demonstrated with a simple example:

>>> def func(n):
    print(id(n))
    print(id(n ** 3))
    n = 2
    print(id(n))

>>> def func2(n):
    print(id(n))
    func(n)

>>> func2(3)
1612339504
1612339504
1612339888
1612339488
>>>

The id() function returns a unique number for each object created in your program. As you can see above, the 3 passed into func2()is the same object passed into func(). However, when we use n in the expression n ** 3, a new object is created. The same thing applies to the assignment n = 2. When we do that, Python treats that as a variable declaration, and a new variable local to func() is created with a reference to the new object 2.


问:
How to convert a string containing an array to an array swift
If I have a string that looks similar to this (stored in firebase):

"[brown, black, blue, pink]"

How would I convert this to in swift [brown, black, blue, pink]

答:
You can use the let components = yourString.components(separatedBy: ", ") function to separate the individual elements of your array. Then you can remove the first character (the "[") from your first string with components[0].remove(at: components[0].startIndex), and the last characters of the last element using components[components.count - 1].substring(to: components[components.count - 1].index(before: components[components.count - 1].endIndex)).

If you're using Swift 4 you can just use components[0].dropFirst() and components[components.count - 1].dropLast().

But as rmaddy stated, you should think about storing your data in a better way (using JSON or something similar), as someone could just enter "hello, world" which would be split into two components using this method.


问:
How to create an edge list from pandas dataframe?
I have a pandas dataframe (df) of the form-

```<code>    Col1
A  [Green,Red,Purple]
B  [Red, Yellow, Blue]
C  [Brown, Green, Yellow, Blue]
</code>```

I need to convert this to an edge list i.e. a dataframe of the form:

```<code>Source    Target    Weight
  A         B         1
  A         C         1
  B         C         2
</code>```

EDIT
Note that the new dataframe has rows equal to the total number of possible pairwise combinations. Also, to compute the 'Weight' column, we simply find the intersection between the two lists. For instance, for B&C, the elements share two colors: Blue and Yellow. Therefore, the 'Weight' for the corresponding row is 2.

What is the fastest way to do this? The original dataframe contains about 28,000 elements.

答:
Try this. Not very neat but work. PS: The final out put you can adjust it , I did not drop columns and change the columns name

```<code>import pandas as pd
df=pd.DataFrame({"Col1":[['Green','Red','Purple'],['Red', 'Yellow', 'Blue'],['Brown', 'Green', 'Yellow', 'Blue']],"two":['A','B','C']})
df=df.set_index('two')
del df.index.name
from itertools import combinations
DF=pd.DataFrame()
dict1=df.T.to_dict('list')
DF=pd.DataFrame(data=[x for x in combinations(df.index, 2)])
DF['0_0']=DF[0].map(df['Col1'])
DF['1_1']=DF[1].map(df['Col1'])
DF['Weight']=DF.apply(lambda x : len(set(x['0_0']).intersection(x['1_1'])),axis=1)

DF
Out[174]:
   0  1                   0_0                           1_1  Weight
0  A  B  [Green, Red, Purple]           [Red, Yellow, Blue]       1
1  A  C  [Green, Red, Purple]  [Brown, Green, Yellow, Blue]       1
2  B  C   [Red, Yellow, Blue]  [Brown, Green, Yellow, Blue]       2
</code>```

Body:
I have a pandas dataframe (df) of the form-

    Col1
A  [Green,Red,Purple]
B  [Red, Yellow, Blue]
C  [Brown, Green, Yellow, Blue]

I need to convert this to an edge list i.e. a dataframe of the form:

Source    Target    Weight
  A         B         1
  A         C         1
  B         C         2

EDIT
Note that the new dataframe has rows equal to the total number of possible pairwise combinations. Also, to compute the 'Weight' column, we simply find the intersection between the two lists. For instance, for B&C, the elements share two colors: Blue and Yellow. Therefore, the 'Weight' for the corresponding row is 2.

What is the fastest way to do this? The original dataframe contains about 28,000 elements.

Body:
Try this. Not very neat but work. PS: The final out put you can adjust it , I did not drop columns and change the columns name

import pandas as pd
df=pd.DataFrame({"Col1":[['Green','Red','Purple'],['Red', 'Yellow', 'Blue'],['Brown', 'Green', 'Yellow', 'Blue']],"two":['A','B','C']})
df=df.set_index('two')
del df.index.name
from itertools import combinations
DF=pd.DataFrame()
dict1=df.T.to_dict('list')
DF=pd.DataFrame(data=[x for x in combinations(df.index, 2)])
DF['0_0']=DF[0].map(df['Col1'])
DF['1_1']=DF[1].map(df['Col1'])
DF['Weight']=DF.apply(lambda x : len(set(x['0_0']).intersection(x['1_1'])),axis=1)

DF
Out[174]:
   0  1                   0_0                           1_1  Weight
0  A  B  [Green, Red, Purple]           [Red, Yellow, Blue]       1
1  A  C  [Green, Red, Purple]  [Brown, Green, Yellow, Blue]       1
2  B  C   [Red, Yellow, Blue]  [Brown, Green, Yellow, Blue]       2


问:
ngSemantic with angular error - unexpected module NgSemanticModule
I have an error while building my angular app using ng build -–prod

ngSemanticModule error

He’s how I installed the module

```<code>npm install ng-semantic --save

npm install jquery --save
</code>```

my angular-cli.json file

```<code>  "styles": [
    "../semantic/dist/semantic.css",
    "styles.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../semantic/dist/semantic.js"
  ]
</code>```

my app.module.ts

```<code>import { NgSemanticModule } from "ng-semantic";

...

  imports: [
    NgSemanticModule
    ...
]
</code>```

And my package.json

```<code>{
  "name": "someproject",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/compiler-cli": "^2.4.10",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/platform-server": "^4.1.3",
    "@angular/router": "^3.4.0",
    "@types/jquery": "^2.0.45",
    "chart.js": "2.5.0",
    "core-js": "^2.4.1",
    "jquery": "^3.2.1",
    "ng-semantic": "^1.1.13",
    "ng2-charts": "^1.5.0",
    "rxjs": "^5.1.0",
    "semantic-ui": "^2.2.10",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0-beta.21",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.0.0"
  }
}
</code>```

My attempts at fixing the error

Added following lines to ng-semantic.d.ts

```<code>import { NgModule } from '@angular/core';

...

@NgModule({
        declarations: [
                NgSemanticModule
        ]
})
export declare class NgSemanticModule {
}
</code>```

Tried using this line in appmodule

```<code>import { NgSemanticModule } from "ng-semantic/ng-semantic";
</code>```

Also followed this post

https://github.com/vladotesanovic/ngSemantic/issues/105

答:
I fixed this issue using in ng-semantic.d.ts file:

```<code>@NgModule()
export declare class NgSemanticModule {
}
</code>```

Instead:

```<code>@NgModule({
        declarations: [
                NgSemanticModule
        ]
})
export declare class NgSemanticModule {
}
</code>```

Body:
I have an error while building my angular app using ng build -–prod

ngSemanticModule error

He’s how I installed the module

npm install ng-semantic --save

npm install jquery --save

my angular-cli.json file

  "styles": [
    "../semantic/dist/semantic.css",
    "styles.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../semantic/dist/semantic.js"
  ]

my app.module.ts

import { NgSemanticModule } from "ng-semantic";

...

  imports: [
    NgSemanticModule
    ...
]

And my package.json

{
  "name": "someproject",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/compiler-cli": "^2.4.10",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/platform-server": "^4.1.3",
    "@angular/router": "^3.4.0",
    "@types/jquery": "^2.0.45",
    "chart.js": "2.5.0",
    "core-js": "^2.4.1",
    "jquery": "^3.2.1",
    "ng-semantic": "^1.1.13",
    "ng2-charts": "^1.5.0",
    "rxjs": "^5.1.0",
    "semantic-ui": "^2.2.10",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0-beta.21",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.0.0"
  }
}

My attempts at fixing the error

Added following lines to ng-semantic.d.ts

import { NgModule } from '@angular/core';

...

@NgModule({
        declarations: [
                NgSemanticModule
        ]
})
export declare class NgSemanticModule {
}

Tried using this line in appmodule

import { NgSemanticModule } from "ng-semantic/ng-semantic";

Also followed this post

https://github.com/vladotesanovic/ngSemantic/issues/105

Body:
I fixed this issue using in ng-semantic.d.ts file:

@NgModule()
export declare class NgSemanticModule {
}

Instead:

@NgModule({
        declarations: [
                NgSemanticModule
        ]
})
export declare class NgSemanticModule {
}


问:
Mapbox GL - draw and animate several points/symbols
I'm trying to add real-time, web-socket event-based data to my map.

Everytime I get a point, I must add it/update it on map.
What's the best option?

A) Create a FeatureCollection and add a source and respective layer. When updating, change the FeatureCollection and call setData();

B) For every point, create a different source and layer. When updating, just change the respective source and call setData();

I really don't believe B) is the best option, I'm just not sure about the perfomance of option A) (or I'm thinking about the former the wrong way).

答:
I'd say it somewhere between the two. For Mapbox Draw I use two layers, one for features that are being edited and one for features that aren't changing. In your case, you'd want to create a layer for every 100 features. This is because Mapbox GL has to recut the geojson into tiles every time you add a feature so limiting the number of features that have to be reviewed is wise. That said, lots of layers will be a problem too.

While I said 100 features above, you'll want to play around with this number a bunch. It will be about finding the right balance between number of layers and number of features in a source.


问:
How can I make this javascript stop when the last slide is shown
I want to make this javascript stop when the last slide is shown, so that the next button won't work, but same with the previous button when the first slide is shown. For the previous button, when I press it and the slider is at the first slide I want it to stay to the current slide.

Javascript code:

```<code>var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
    showDivs(slideIndex += n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName('slide');
    if (n < 1) {slideIndex = 1;}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = 'none';
    }
    x[slideIndex-1].style.display = 'block';
    }
</code>```

HTML code:

```<code><div class="links-to-wbp">
                    <div class="slide">
                        <a href="/physics/index.html"><img class="wbp" alt="thumb1" src="img/thumb1.png"/></a><a href="/francais/index.html"><img class="wbp" alt="thumb2" src="img/thumb2.png"/></a><a href="/strict/index.html"><img class="wbp" alt="thumb3" src="img/thumb3.png"/></a></div>
                <div class="slide">
                        <img class="wbp" alt="thumb4" src="img/thumb4.png"/><img class="wbp" alt="thumb5" src="img/thumb5.png"/><img class="wbp" alt="thumb6" src="img/thumb6.png"/></div>
                <div class="slide">
                        <img class="wbp" alt="thumb7" src="img/thumb7.png"/><img class="wbp" alt="thumb8" src="img/thumb8.png"/><img class="wbp" alt="thumb9" src="img/thumb9.png"/></div>
                     <div onclick="plusDivs(-1)" class="button previous_button"><</div>
                    <div onclick="plusDivs(+1)" class="button next_button">></div>
                </div>
</code>```

答:
To achieve expected result, add below line to the showDivs function

```<code>//add this line to stop after last slide
  if(n > x.length){
      n= slideIndex =x.length;
   }
</code>```

Codepen- https://codepen.io/nagasai/pen/vZVeZV

Solution:

Above mentioned solution, will check whether the next value is more than the count of slide class(i.e., 3 in this case)

If it is more than the count of slide class, reset n and slideIndex back to the length of slide class.

For previous slide at first slide, there is already if condition which works

```<code>if (n < 1) {slideIndex = 1;}
</code>```

Body:
I want to make this javascript stop when the last slide is shown, so that the next button won't work, but same with the previous button when the first slide is shown. For the previous button, when I press it and the slider is at the first slide I want it to stay to the current slide.

Javascript code:

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
    showDivs(slideIndex += n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName('slide');
    if (n < 1) {slideIndex = 1;}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = 'none';
    }
    x[slideIndex-1].style.display = 'block';
    }

HTML code:

<

>

Body:
To achieve expected result, add below line to the showDivs function

//add this line to stop after last slide
  if(n > x.length){
      n= slideIndex =x.length;
   }

Codepen- https://codepen.io/nagasai/pen/vZVeZV

Solution:

Above mentioned solution, will check whether the next value is more than the count of slide class(i.e., 3 in this case)

If it is more than the count of slide class, reset n and slideIndex back to the length of slide class.

For previous slide at first slide, there is already if condition which works

if (n < 1) {slideIndex = 1;}


答:
That's because you are not storing the result of cube anywhere and you are just returning the number itself.

I think what confused you is, inside cube() function you are returning number. Now you think, it is the same number variable inside the other function. But it is not. You need to reassign the value to some variable so as to use it.

```<code>...
cube_num = cube(number)
return cube_num
</code>```

Now this would work. Hope this helps! :)

Title: What is the difference here?

Body:
That's because you are not storing the result of cube anywhere and you are just returning the number itself.

I think what confused you is, inside cube() function you are returning number. Now you think, it is the same number variable inside the other function. But it is not. You need to reassign the value to some variable so as to use it.

...
cube_num = cube(number)
return cube_num

Now this would work. Hope this helps! :)


问:
C# type inference ("var") assignment from '??' null-coalescing operator
I've read many of the  SO questions on the null coalescing ?? operator but none of them seem to address the following specific issue, which concerns neither nullability (here), operator precedence (here and here) nor especially implicit conversion (here, here, here and here). I've also read the .NET docs (more here) and tried to read the offical spec, but sadly all to no avail.

So here goes. The only difference between the following two lines is the use of var for type inference in the second, versus explicit type Random in the first, yet the second line gives the error as shown, whereas the first is just fine.

```<code>Random x = new Random() ?? (x = new Random());        // ok

var    y = new Random() ?? (y = new Random());        // CS0841
                        //  ^-------- error here
</code>```

CS0841: Cannot use local variable 'y' before it is declared

What is it precisely about the second line that makes the outcome uncertain?

From the hubub I cited above, I learned that the possibility of the left-side of the ?? operator being null introduces a dependency on the runtime determination of the actual instantiated type of its right-side. Hmm, ok, I guess,... whatever that means? Maybe the amount of alarm generally wafting about the ?? operator on this site should have been some kind of dire warning...

Zeroing-in now, I thought that the whole point of the var keyword (as very specifically opposed to dynamic) was that it was not suscceptible to runtime considerations like that, by definition.

In other words, even if we adopt the conservative but perfectly defensible rule of "never peering beyond any assignment = operator", such that we therefore get no helpful information whatsoever from the right-side of the ??, then based on the left-side alone, the overall result must be "compatible with" Random. That is, the result must be Random or a more specific (derived) type; it cannot be more general. By definition, therefore, shouldn't Random be the inferred type, for this compile-time use of var?

As far as I can understand, corrupting var with runtime considerations summarily defeats its purpose. Isn't that precisely what dynamic is for? So I guess the questions are:

Is the null-coalescing operator a lone and/or rare exception to my understanding of C# static (i.e., compile-time) typing philosophy?

If yes, then what are the benefits or tradeoffs between this design vs. what seems to be going on here, namely, deliberately introducing non-determinism to a system of static type inference, and which it did not previously exhibit? Couldn't dynamic have been implemented without corrupting the purity of static typing?

Isn't one of the main points of strong-typing to enable compile-time design rigor via actionable feedback to the developer? Why can't var just maintain a policy of strict conservatism--always inferring the most-specific type that can be statically inferred--at the same time as the null-coalescing operator is doing whatever it wants to do based on information from the future?

答:
When you use var, the type is figured out at compile time. Therefore, when you write this:

```<code>var    y = new Random() ?? (y = new Random());
</code>```

the compiler cannot determine what y's type is at compile time and thus starts yelling-the decision whether the left side of ?? is null or not, will be determined at runtime.

A better example would be:

```<code>public interface IA { void Do(); }
public class A : IA { ... }
public class B : IA { ... }

A a = null;
var something = a ?? new B();
</code>```

What should be the type of something: IA, A or B?

Body:
I've read many of the  SO questions on the null coalescing ?? operator but none of them seem to address the following specific issue, which concerns neither nullability (here), operator precedence (here and here) nor especially implicit conversion (here, here, here and here). I've also read the .NET docs (more here) and tried to read the offical spec, but sadly all to no avail.

So here goes. The only difference between the following two lines is the use of var for type inference in the second, versus explicit type Random in the first, yet the second line gives the error as shown, whereas the first is just fine.

Random x = new Random() ?? (x = new Random());        // ok

var    y = new Random() ?? (y = new Random());        // CS0841
                        //  ^-------- error here

CS0841: Cannot use local variable 'y' before it is declared

What is it precisely about the second line that makes the outcome uncertain?

From the hubub I cited above, I learned that the possibility of the left-side of the ?? operator being null introduces a dependency on the runtime determination of the actual instantiated type of its right-side. Hmm, ok, I guess,... whatever that means? Maybe the amount of alarm generally wafting about the ?? operator on this site should have been some kind of dire warning...

Zeroing-in now, I thought that the whole point of the var keyword (as very specifically opposed to dynamic) was that it was not suscceptible to runtime considerations like that, by definition.

In other words, even if we adopt the conservative but perfectly defensible rule of "never peering beyond any assignment = operator", such that we therefore get no helpful information whatsoever from the right-side of the ??, then based on the left-side alone, the overall result must be "compatible with" Random. That is, the result must be Random or a more specific (derived) type; it cannot be more general. By definition, therefore, shouldn't Random be the inferred type, for this compile-time use of var?

As far as I can understand, corrupting var with runtime considerations summarily defeats its purpose. Isn't that precisely what dynamic is for? So I guess the questions are:

Is the null-coalescing operator a lone and/or rare exception to my understanding of C# static (i.e., compile-time) typing philosophy?

If yes, then what are the benefits or tradeoffs between this design vs. what seems to be going on here, namely, deliberately introducing non-determinism to a system of static type inference, and which it did not previously exhibit? Couldn't dynamic have been implemented without corrupting the purity of static typing?

Isn't one of the main points of strong-typing to enable compile-time design rigor via actionable feedback to the developer? Why can't var just maintain a policy of strict conservatism--always inferring the most-specific type that can be statically inferred--at the same time as the null-coalescing operator is doing whatever it wants to do based on information from the future?

Body:
When you use var, the type is figured out at compile time. Therefore, when you write this:

var    y = new Random() ?? (y = new Random());

the compiler cannot determine what y's type is at compile time and thus starts yelling-the decision whether the left side of ?? is null or not, will be determined at runtime.

A better example would be:

public interface IA { void Do(); }
public class A : IA { ... }
public class B : IA { ... }

A a = null;
var something = a ?? new B();

What should be the type of something: IA, A or B?


答:
Parse it as a JSON array</p>

```<code>let data = stringArray.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String]

    let first= json?[0] as? String
    dump(first)
}catch let error{

}
</code>```

Title: How to convert a string containing an array to an array swift

Body:
If I have a string that looks similar to this (stored in firebase):

"[brown, black, blue, pink]"

How would I convert this to in swift [brown, black, blue, pink]

Body:
Parse it as a JSON array

let data = stringArray.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String]

    let first= json?[0] as? String
    dump(first)
}catch let error{

}


问:
Python's re module - saving state?
One of the biggest annoyances I find in Python is the inability of the re module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:

```<code>if re.match('foo (\w+) bar (\d+)', line):
  # do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
  # do stuff with .group(1)
# etc.
</code>```

But unfortunately it's impossible to get to the matched object of the previous call to re.match, so this is written like this:

```<code>m = re.match('foo (\w+) bar (\d+)', line)
if m:
  # do stuff with m.group(1) and m.group(2)
else:
  m = re.match('baz whoo_(\d+)', line)
  if m:
    # do stuff with m.group(1)
</code>```

Which is rather less convenient and gets really unwieldy as the list of elifs grows longer.

A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?

What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?

Thanks in advance

答:
Based on the great answers to this question, I've concocted the following mechanism. It appears like a general way to solve the "no assignment in conditions" limitation of Python. The focus is transparency, implemented by silent delegation:

```<code>class Var(object):
    def __init__(self, val=None):
        self._val = val

    def __getattr__(self, attr):
        return getattr(self._val, attr)

    def __call__(self, arg):
        self._val = arg
        return self._val

if __name__ == "__main__":
    import re

    var = Var()

    line = 'foo kwa bar 12'

    if var(re.match('foo (\w+) bar (\d+)', line)):
        print var.group(1), var.group(2)
    elif var(re.match('baz whoo_(\d+)', line)):
        print var.group(1)
</code>```

In the general case, this is a thread-safe solution, because you can create your own instances of Var. For more ease-of-use when threading is not an issue, a default Var object can be imported and used. Here's a module holding the Var class:

```<code>class Var(object):
    def __init__(self, val=None):
        self._val = val

    def __getattr__(self, attr):
        return getattr(self._val, attr)

    def __call__(self, arg):
        self._val = arg
        return self._val

var = Var()
</code>```

And here's the user's code:

```<code>from var import Var, var
import re

line = 'foo kwa bar 12'

if var(re.match('foo (\w+) bar (\d+)', line)):
    print var.group(1), var.group(2)
elif var(re.match('baz whoo_(\d+)', line)):
    print var.group(1)
</code>```

While not thread-safe, for a lot of simple scripts this provides a useful shortcut.

OwnerDisplayName: eliben

Title: Python's re module - saving state?

Body:
One of the biggest annoyances I find in Python is the inability of the re module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:

if re.match('foo (\w+) bar (\d+)', line):
  # do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
  # do stuff with .group(1)
# etc.

But unfortunately it's impossible to get to the matched object of the previous call to re.match, so this is written like this:

m = re.match('foo (\w+) bar (\d+)', line)
if m:
  # do stuff with m.group(1) and m.group(2)
else:
  m = re.match('baz whoo_(\d+)', line)
  if m:
    # do stuff with m.group(1)

Which is rather less convenient and gets really unwieldy as the list of elifs grows longer.

A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?

What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?

Thanks in advance

LastEditorDisplayName: eliben

Body:
Based on the great answers to this question, I've concocted the following mechanism. It appears like a general way to solve the "no assignment in conditions" limitation of Python. The focus is transparency, implemented by silent delegation:

class Var(object):
    def __init__(self, val=None):
        self._val = val

    def __getattr__(self, attr):
        return getattr(self._val, attr)

    def __call__(self, arg):
        self._val = arg
        return self._val

if __name__ == "__main__":
    import re

    var = Var()

    line = 'foo kwa bar 12'

    if var(re.match('foo (\w+) bar (\d+)', line)):
        print var.group(1), var.group(2)
    elif var(re.match('baz whoo_(\d+)', line)):
        print var.group(1)

In the general case, this is a thread-safe solution, because you can create your own instances of Var. For more ease-of-use when threading is not an issue, a default Var object can be imported and used. Here's a module holding the Var class:

class Var(object):
    def __init__(self, val=None):
        self._val = val

    def __getattr__(self, attr):
        return getattr(self._val, attr)

    def __call__(self, arg):
        self._val = arg
        return self._val

var = Var()

And here's the user's code:

from var import Var, var
import re

line = 'foo kwa bar 12'

if var(re.match('foo (\w+) bar (\d+)', line)):
    print var.group(1), var.group(2)
elif var(re.match('baz whoo_(\d+)', line)):
    print var.group(1)

While not thread-safe, for a lot of simple scripts this provides a useful shortcut.


问:
Message Queue Where Messages Can Be Filtered By Tags
I'm in need of a message queue where I can associate messages with tags and receive only the messages that are associated with a certain tag.

For example let's say that {id:1, tags: "tag1", "tag2"} is a message with id 1 and associated with tags "tag1" and "tag2". So I would like the receive 1 when I ask for "tag1" or "tag2" from the queue but not for "tag3".

I also need this feature to support one-time delivery, which means when I receive the message above it won't be served again when asked for tag1 or tag2 (at least within the visibility timeout)

An MQ which enables filtering messages with a user-defined property would also work; but it should guarantee a one-time delivery of the message. So routing in AMQP (such as in RabbitMQ) would not work for me, since I believe it creates a copy of the message in each queue.

I've investigated several MQ implementations (RabbitMQ, ActiveMQ, SQS, MSMQ etc.) but failed to find an implementation of this feature. Is there an MQ which supports this type message filtering?

答:
Since you were looking at RabbitMQ, ActiveMQ, SQS, MSMQ you may be also interested to check out ZeroMQ, nanomsg or YAMI4.

They have PUB/SUB mechanism with the filtering capabilities on the client side.
The client could receive messages with a particular tag.

Listening to many tags could be arranged by using dedicated threads or multiple connections.

PUB/SUB in ZeroMQ

PUB/SUB in nanomsg

PUB/SUB in YAMI4

I use nanomsg in the production in C/C++ application and in Java app with Java bindings.


问:
PHP short-ternary ("Elvis") operator vs null coalescing operator
Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

When do they behave differently and when in the same way (if that even happens)?

```<code>$a ?: $b
</code>```

VS.

```<code>$a ?? $b
</code>```

答:
It seems there are pros and cons to using either ?? or ?:. The pro to using ?: is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ?? the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else.

The following is an example of the difference of using the ?? operator using both null and false:

```<code>$false = null;
$var = $false ?? "true";
echo $var . "---<br>";//returns: true---

$false = false;
$var = $false ?? "true";
echo $var . "---<br>"; //returns: ---
</code>```

By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:

```<code>$false = null;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = false;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = "";
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = true;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: 1---
</code>```

Personally, I think it would be really nice if a future rev of PHP included another new operator: :? that replaced the above syntax. ie:
// $var = $false :? "true"; That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...

Body:
Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

When do they behave differently and when in the same way (if that even happens)?

$a ?: $b

VS.

$a ?? $b

Body:
It seems there are pros and cons to using either ?? or ?:. The pro to using ?: is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ?? the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else.

The following is an example of the difference of using the ?? operator using both null and false:

$false = null;
$var = $false ?? "true";
echo $var . "---<br>";//returns: true---

$false = false;
$var = $false ?? "true";
echo $var . "---<br>"; //returns: ---

By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:

$false = null;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = false;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = "";
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---

$false = true;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: 1---

Personally, I think it would be really nice if a future rev of PHP included another new operator: :? that replaced the above syntax. ie:
// $var = $false :? "true"; That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...


问:
Accessing parent window variable with Office.context.ui.displayDialogAsync?
I'm opening and closing a Dialog Async with Office.context.ui.displayDialogAsync(),
When the page in the dialog pops up, I want to access a variable or DOM element defined in the parent window, that I would normally do using:

window.opener.VariableName

or

window.opener.$("#ElementName")

Is there a similar method for displayDialogAsync()?

PS: This variable string length is too long to be passed through GET variables in URL

答: There is no API to do that. You would need to save the variable value in Local Storage with script on the parent page and read it from script in the dialog. You could use the messageParent function in the dialog to tell the parent when to save the variable.</p>


问:
Use dollar sign in PHP sprintf function with a %s string
This involves Wordpress syntax but I figured it was mainly a PHP problem.

I'm using this function:

```<code>$subject = sprintf( '%s New Customer Order %s for %s on %s', $blogname, $order->id, $order->get_total, $order->order_date );
</code>```

to produce something like:
"SiteName New Customer Order #3715 for $40.00 on July 5th"

The problem is the $order_total outputs as a plain integer without dollar sign. Using $%s or \$%s doesn't work.. how can I append a dollar sign to the second %s variable?

答:
I would do :

```<code>$currency = '$';
$subject = sprintf( '%s New Customer Order %s for %s%01.2f on %s',
      $blogname,
      $order->id,
      $currency,
      $order->get_total,
      $order->order_date );
</code>```

Thus being able to change for different currencies, and format the amount to dollars and cents (or euros and cents, pounds and pennies etc)

Body:
This involves Wordpress syntax but I figured it was mainly a PHP problem.

I'm using this function:

$subject = sprintf( '%s New Customer Order %s for %s on %s', $blogname, $order->id, $order->get_total, $order->order_date );

to produce something like:
"SiteName New Customer Order #3715 for $40.00 on July 5th"

The problem is the $order_total outputs as a plain integer without dollar sign. Using $%s or \$%s doesn't work.. how can I append a dollar sign to the second %s variable?

Body:
I would do :

$currency = '$';
$subject = sprintf( '%s New Customer Order %s for %s%01.2f on %s',
      $blogname,
      $order->id,
      $currency,
      $order->get_total,
      $order->order_date );

Thus being able to change for different currencies, and format the amount to dollars and cents (or euros and cents, pounds and pennies etc)