问:
Android Beacon library(AltBeacon) support in Oreo
I have integrated AltBeacon library in my app and it's working perfectly in all android versions except Oreo.

When I checked the code I found that the code for becaon scanning is in a service so we need to handle service restrictions from Oreo. Even after making the changes scanning is not happening in the specified time intervals, when the app is in background. Because Altbeacon library is using service for scanning.

Please let me know is there any way to fix this issue or please suggest any other libraries for beacon scanning.

Thanks

答:
Library version 2.12 introduced a new scanning mechanism compatible with Android 8 power saving restrictions. Apps that use the library will need to upgrade to version 2.12+ in order to detect in the background on Android 8 devices.  Version 2.13+ adds further enhancements for Android 8.1 restrictions of scanning with the screen off.

You can read more about the Android 8 restrictions here: Beacon Detection With Android 8

If you use the latest version, the library will use a JobScheduler instead of a long-running service to process scans on apps installed on Android 8+.


来源: stackexchange

问:
DriveApp root Computers folder
Does anyone know how to easily access the Google Drive "Computers" folder that contains entries for each of a user's computers that was synced using the Google "Backup and Sync" application?

I've created a simple app script (more out of interest than anything else) which creates a Google Sheets document listing the contents of the current user's G-Drive.   It starts with a call to DriveApp.getRootFolder(), and then lists and navigates the file tree from there.  This all works fine, but it does not contain anything that is not a child of "My Drive", such as the Backup and Sync files stored under the "Computers" pseudo-root folder.

I've tried using DriveApp.getFoldersByName("Computers"), but that returned an iterator with zero items.

答: Not possible. You can only touch your regular "My Drive" (or team drive) files. No mention of that in Files: list.</p>

ContentLicense: CC BY-SA 3.0

Title: DriveApp root Computers folder


问:
Javascript compare two strings of date in specfic format
I want to compare two strings of date. The format is: day month year. (example: 5 april 2017)
I want to see if it's superior or not to the current date. (6 december 2017) Is it possible without being too difficult? </p>

```<code>d1 = "5 april 2017"
d2 = "5 december 2017"

if (d1<d2){
//do this
}
</code>```

答:
You need to create date objects from your date strings first.

d1 = "5 april 2017"
d2 = "5 december 2017"
d3 = "05/04/2017";
d4 = "05/12/2017"

compareDates(d1, d2);
compareDates(d2, d1);
compareDates(d3, d4);
compareDates(d4, d3);

function compareDates( date1, date2 )
{
  if( (new Date(date1) > new Date(date2)) )
    console.log('Is ' + date1 + ' greater than ' + date2 + '? '+ '= ' + true);
  else
    console.log('Is ' + date1 + ' greater than ' + date2 + '? '+ '= ' + false);
}```

Body:
I want to compare two strings of date. The format is: day month year. (example: 5 april 2017)
I want to see if it's superior or not to the current date. (6 december 2017) Is it possible without being too difficult?

d1 = "5 april 2017"
d2 = "5 december 2017"

if (d1<d2){
//do this
}


答:
For date comparisons, it's usually best to get them in milliseconds or seconds. With JavaScript this can be done by passing the date to a new Date object, then calling the getTime function to get the milliseconds.

```<code>var d1 = new Date("5 april 2017").getTime();
var d2 = new Date("5 december 2017").getTime();

if (d1 < d2) {
    //do this
}
</code>```

Title: Javascript compare two strings of date in specfic format

Body:
For date comparisons, it's usually best to get them in milliseconds or seconds. With JavaScript this can be done by passing the date to a new Date object, then calling the getTime function to get the milliseconds.

var d1 = new Date("5 april 2017").getTime();
var d2 = new Date("5 december 2017").getTime();

if (d1 < d2) {
    //do this
}


问:
Is there a way to clear session data to ensure a clean session is initiated each time?
For IE you would use capabilities like this:

```<code>DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
</code>```

and possibly in combination with

```<code> driver.manage().deleteAllCookies();
</code>```

How could this be achieved using Chrome and ChromeDriver?

答:
While we work with Internet Explorer Driver we use the field IE_ENSURE_CLEAN_SESSION

IE_ENSURE_CLEAN_SESSION

As per the JavaDocs IE_ENSURE_CLEAN_SESSION is the Capability that defines whether to clean or not browser cache before launching Internet Explorer by IEDriverServer and is configured as follows :

```<code>DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
</code>```

Now let us have a look at GeckoDriver which follows the WebDriver Spec.

GeckoDriver / moz:profile / rust_mozprofile

If you have a closer look at the geckodriver logs closely you will observe that each time geckodriver is called a new moz:profile is scopped out and the details of rust_mozprofile occurs in the following line:

```<code>Marionette  CONFIG  Matched capabilities: {"browserName":"firefox","browserVersion":"56.0","platformName":"windows_nt","platformVersion":"6.2","pageLoadStrategy":"normal","acceptInsecureCerts":false,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000},"rotatable":false,"specificationLevel":0,"moz:processID":5848,"moz:profile":"C:\\Users\\AtechM_03\\AppData\\Local\\Temp\\rust_mozprofile.OfFuR9ogm33d","moz:accessibilityChecks":false,"moz:headless":false}
</code>```

This log clearly indicates that Marionette scoops out a new "moz:profile":"C:\\Users\\AtechM_03\\AppData\\Local\\Temp\\rust_mozprofile.OfFuR9ogm33d" and this configuration is handled by the WebDriver instance i.e. the GeckoDriver.

You can find a more detailed discussion on moz:profile in Is it Firefox or Geckodriver, which creates “rust_mozprofile” directory discussion.

ChromeDriver

ChromeDriver which is following the same WebDriver Spec does abides (will be abiding) by the same suite.

Incase you are using any stored FirefoxProfile or ChromeProfile, WebDriver will pick up the existing profile where the Stored Browser Configurations are picked up for reuse.

driver.manage().deleteAllCookies();

Irespective of New/Existing FirefoxProfile or ChromeProfile if you add the line :

```<code>driver.manage().deleteAllCookies();
</code>```

Only the cookies gets deleted only to be get restored back to support the Active Browser Session

Body:
For IE you would use capabilities like this:

DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);

and possibly in combination with

 driver.manage().deleteAllCookies();

How could this be achieved using Chrome and ChromeDriver?

Body:
While we work with Internet Explorer Driver we use the field IE_ENSURE_CLEAN_SESSION

IE_ENSURE_CLEAN_SESSION

As per the JavaDocs IE_ENSURE_CLEAN_SESSION is the Capability that defines whether to clean or not browser cache before launching Internet Explorer by IEDriverServer and is configured as follows :

DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);

Now let us have a look at GeckoDriver which follows the WebDriver Spec.

GeckoDriver / moz:profile / rust_mozprofile

If you have a closer look at the geckodriver logs closely you will observe that each time geckodriver is called a new moz:profile is scopped out and the details of rust_mozprofile occurs in the following line:

Marionette  CONFIG  Matched capabilities: {"browserName":"firefox","browserVersion":"56.0","platformName":"windows_nt","platformVersion":"6.2","pageLoadStrategy":"normal","acceptInsecureCerts":false,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000},"rotatable":false,"specificationLevel":0,"moz:processID":5848,"moz:profile":"C:\\Users\\AtechM_03\\AppData\\Local\\Temp\\rust_mozprofile.OfFuR9ogm33d","moz:accessibilityChecks":false,"moz:headless":false}

This log clearly indicates that Marionette scoops out a new "moz:profile":"C:\\Users\\AtechM_03\\AppData\\Local\\Temp\\rust_mozprofile.OfFuR9ogm33d" and this configuration is handled by the WebDriver instance i.e. the GeckoDriver.

You can find a more detailed discussion on moz:profile in Is it Firefox or Geckodriver, which creates “rust_mozprofile” directory discussion.

ChromeDriver

ChromeDriver which is following the same WebDriver Spec does abides (will be abiding) by the same suite.

Incase you are using any stored FirefoxProfile or ChromeProfile, WebDriver will pick up the existing profile where the Stored Browser Configurations are picked up for reuse.

driver.manage().deleteAllCookies();

Irespective of New/Existing FirefoxProfile or ChromeProfile if you add the line :

driver.manage().deleteAllCookies();

Only the cookies gets deleted only to be get restored back to support the Active Browser Session


问:
How to read inline styling of an element?
I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element.  I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

```<code><div id="foo" style="width: 100px; height: 100px; background: green;"></div>
</code>```

How can I determine that width, height, and background have been explicitly declared, inline?

As far as I can tell, the solution can work two ways.  I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set.  Like so:

```<code>var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'
</code>```

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles.  One last thing, I have no control over the HTML source.

Thanks

答:
You may want to try doing something like:

```<code>var obj = document.getElementById("foo");
var obj_has_background = (obj.style.background != "");
var obj_has_width = (obj.style.width != "");
var obj_has_height = (obj.style.height != "");
</code>```

Seems a bit long, but this is the best (and shortest) solution I could come up with.

OwnerDisplayName: sam

Body:
I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element.  I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

How can I determine that width, height, and background have been explicitly declared, inline?

As far as I can tell, the solution can work two ways.  I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set.  Like so:

var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles.  One last thing, I have no control over the HTML source.

Thanks

Body:
You may want to try doing something like:

var obj = document.getElementById("foo");
var obj_has_background = (obj.style.background != "");
var obj_has_width = (obj.style.width != "");
var obj_has_height = (obj.style.height != "");

Seems a bit long, but this is the best (and shortest) solution I could come up with.

OwnerDisplayName: hydrapheetz

ContentLicense: CC BY-SA 2.5


问:
Debugging problem
I have made some changes to my project, when I debug, application seems to run the old .exe file, not the updated.  I know it happens when there are some errors but I do not get any error messages also I checked the error list, it does not show any errors.

I also re-started Visual Studio, but nothing has changed.

Please advise.
Thanks and best regards,
Furqan

答:
This sometimes happens. You can try two thing:

In the menu, under “Project” (I think), go to “Clean solution”

If that doesn’t help, go to the folder where your project is stored, go into the Debug folder and delete the exe file.

Title: Debugging problem


问:
XSLT transformation - set variable during iteration through set of nodes
My task is to create XSLT transformation.
In procedural language solution would look like this:

```<code>foreach( Book book in set)
{
   int importanceIndicator = 0;
   foreach( Page page in book )
   {
      if(page.name == "important_page")
      {
         importanceIndicator = 1;
         break;
      }
   }
   book.newField.importanceIndicator = importanceIndicator;
}
</code>```

How can I solve this problem in XSLT (which is very different from procedural languages)?

Sample XML files:

Input:

```<code><set>
    <book>
        <page name="important_page"></page>
        <page name="first_page"></page>
        <page name="important_page"></page>
        <page name="second_page"></page>
        <page name="important_page"></page>
    </book>
    <book>
        <page name="another_page"></page>
        <page name="first_page"></page>
        <page name="3_page"></page>
        <page name="second_page"></page>
        <page name="another_page"></page>
    </book>
    <book>
        <page name="important_page"></page>
        <page name="first_page"></page>
        <page name="important_page"></page>
        <page name="second_page"></page>
        <page name="another_page"></page>
    </book>
</set>
</code>```

Output:

```<code><set>
    <book>
        <newField importance_indicator="1"></newField>
    </book>
    <book>
        <newField importance_indicator="0"></newField>
    </book>
    <book>
        <newField importance_indicator="1"></newField>
    </book>
</set>
</code>```

答:
I found the answer, it can be done like this:</p>

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes" />
  <xsl:template match="/">

    <set>
        <xsl:for-each select="set">
          <xsl:for-each select="book">
            <book>
            <xsl:variable name="importanceIndicatorTmp">
              <xsl:choose>
                <xsl:when test= "page/@name = 'important_page'">1</xsl:when>
                <xsl:otherwise>0</xsl:otherwise>
              </xsl:choose>
            </xsl:variable>
            <newField importanceIndicator="{$importanceIndicatorTmp}"></newField>
            </book>
          </xsl:for-each>
        </xsl:for-each>
    </set>

  </xsl:template>
</xsl:stylesheet>
</code>```

Body:
My task is to create XSLT transformation.
In procedural language solution would look like this:

foreach( Book book in set)
{
   int importanceIndicator = 0;
   foreach( Page page in book )
   {
      if(page.name == "important_page")
      {
         importanceIndicator = 1;
         break;
      }
   }
   book.newField.importanceIndicator = importanceIndicator;
}

How can I solve this problem in XSLT (which is very different from procedural languages)?

Sample XML files:

Input:

<set>
    <book>
        <page name="important_page"></page>
        <page name="first_page"></page>
        <page name="important_page"></page>
        <page name="second_page"></page>
        <page name="important_page"></page>
    </book>
    <book>
        <page name="another_page"></page>
        <page name="first_page"></page>
        <page name="3_page"></page>
        <page name="second_page"></page>
        <page name="another_page"></page>
    </book>
    <book>
        <page name="important_page"></page>
        <page name="first_page"></page>
        <page name="important_page"></page>
        <page name="second_page"></page>
        <page name="another_page"></page>
    </book>
</set>

Output:

<set>
    <book>
        <newField importance_indicator="1"></newField>
    </book>
    <book>
        <newField importance_indicator="0"></newField>
    </book>
    <book>
        <newField importance_indicator="1"></newField>
    </book>
</set>

Body:
I found the answer, it can be done like this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes" />
  <xsl:template match="/">

    <set>
        <xsl:for-each select="set">
          <xsl:for-each select="book">
            <book>
            <xsl:variable name="importanceIndicatorTmp">
              <xsl:choose>
                <xsl:when test= "page/@name = 'important_page'">1</xsl:when>
                <xsl:otherwise>0</xsl:otherwise>
              </xsl:choose>
            </xsl:variable>
            <newField importanceIndicator="{$importanceIndicatorTmp}"></newField>
            </book>
          </xsl:for-each>
        </xsl:for-each>
    </set>

  </xsl:template>
</xsl:stylesheet>


问:
How can i get a signed xml using azure logic apps
i was searching for an idea how can i sign a XML using a self signed certificate on logic apps. maybe using a function app? is there any way to get a signed xml using logic apps?</p>

答:
There are no built in tools for signing Xml in Logic Apps, other than just .Net in general.

The reason is this is not a widely used function.  Do you have to use signed Xml?  Is AS2 an option?


问:
Mongoose lowercase flag is ignored while doing findOneAndUpdate()
I want to store some fields in my documents as lowercase characters. Thus, I created a schema like

```<code>let body = new Schema({
    id: { type: Number, unique: true },
    group_name: { type: String, lowercase: true },
    type_name: { type: String, lowercase: true },
    full_spectral_class: { type: String, lowercase: true },
    spectral_class: { type: String, lowercase: true },
    spectral_sub_class: { type: String, lowercase: true },
    luminosity_class: { type: String, lowercase: true },
    luminosity_sub_class: { type: String, lowercase: true }
})
</code>```

When I am using save() to insert values, all values are getting stored as lowercase strings. But when I tried to update using findOneAndUpdate(), the values are getting as is. I would rather not convert all the fields into lowercase manually as there are quite a number of fields and schemas following the same style.

答:
You have to set the runSettersOnQuery to true.

```<code>const options = { upsert: true, runSettersOnQuery : true };
await yourModel.findOneAndUpdate(searchCriteria, newSetOfValues, options);
</code>```

There are few samples on internet, but maybe you can find this one useful from mongoose docs.

Body:
I want to store some fields in my documents as lowercase characters. Thus, I created a schema like

let body = new Schema({
    id: { type: Number, unique: true },
    group_name: { type: String, lowercase: true },
    type_name: { type: String, lowercase: true },
    full_spectral_class: { type: String, lowercase: true },
    spectral_class: { type: String, lowercase: true },
    spectral_sub_class: { type: String, lowercase: true },
    luminosity_class: { type: String, lowercase: true },
    luminosity_sub_class: { type: String, lowercase: true }
})

When I am using save() to insert values, all values are getting stored as lowercase strings. But when I tried to update using findOneAndUpdate(), the values are getting as is. I would rather not convert all the fields into lowercase manually as there are quite a number of fields and schemas following the same style.

Body:
You have to set the runSettersOnQuery to true.

const options = { upsert: true, runSettersOnQuery : true };
await yourModel.findOneAndUpdate(searchCriteria, newSetOfValues, options);

There are few samples on internet, but maybe you can find this one useful from mongoose docs.


问:
How to send a browser notification when a specific time occurs?
I'm creating a to-do app with MEAN stack. Input will be to-do text and to-do time, which will be stored in database. This is my code to fetch client browser time and send notification with that time. But what I need is, notification should be send when the time stored in database occurs. How I can do that? Atleast how I can get the variable btime in server? </p>

```<code><script>
        Notification.requestPermission().then(function(result) {
        var time = new Date();
        var bhours = time.getHours();
        var bminutes = time.getMinutes();
        var btime = bhours + ':' + bminutes;
        var notification = new Notification(btime);
      });
</script>
</code>```

答:
```<code>  var notify = function() {
    Notification.requestPermission().then(function(result) {
         //function
        })
        .error(function(data) {
           //function
        });
  }).catch((err) => {
    //function
  });
};
</code>```


问:
Check if element is clicked before removal
I have the following jquery code:

```<code>$(document).on('focusout', '#element_a', function(e){
     $('#element_b').remove();
});
$(document).on('click', '#element_b', function(e){
     // do other stuff here
});
</code>```

So basically, I want to remove #element_b on focusout BUT if it's clicked, execute the click function before removal. The problem is that focusout executes before the click so by the time the click is registered, the element is already removed, so the click doesn't register and does nothing.

答:
The DEMO is here

You better use mouseleave instead of focus out.

JS

```<code>$(document).ready(function(){
  $('#click').click(function(){
    alert('im clicked');
  });
  $('#click').mouseleave(function(){
    alert('im focus out');
  });
});
</code>```

Body:
I have the following jquery code:

$(document).on('focusout', '#element_a', function(e){
     $('#element_b').remove();
});
$(document).on('click', '#element_b', function(e){
     // do other stuff here
});

So basically, I want to remove #element_b on focusout BUT if it's clicked, execute the click function before removal. The problem is that focusout executes before the click so by the time the click is registered, the element is already removed, so the click doesn't register and does nothing.

Body:
The DEMO is here

You better use mouseleave instead of focus out.

JS

$(document).ready(function(){
  $('#click').click(function(){
    alert('im clicked');
  });
  $('#click').mouseleave(function(){
    alert('im focus out');
  });
});


问:
IIS URL rewrite with optional parameters for page no

I need a help writing rewrite rule for the following url pattern

```<code>www.mydomain.com/list-of-(buyers|suppers|all)-in-(location-name)/page/10.html
</code>```

The first parameter will be 'buyers' or 'suppliers' or 'all'

The second parameter can be ANY location name

'/page/number' part is optional

url will always end with '.html'

UPDATE:

I have managed to write a rewrite rule which successfully matches the following url:

mysite.com/list-of-buyers-in-goa/page/5.html.

The same rule is not working for the below url

mysite.com/list-of-buyers-in-goa.html

i.e. when I remove the page/no part from the url, it doesn't work. I don't need page/no parameter for the first page.

Since all the other pages on website are .html pages, just to maintain the uniformity, I want the url to always end with .html

Here is my rewrite rule

```<code>    <rule name="Rewrite rule for listing members">
      <match url="^list-of-([a-z-A-z]+)-in-([a-zA-z-]+)?(\/page\/)?([\d+])?\.html$" />
      <action type="Rewrite" url="members.aspx?type={R:1}&location={R:2}&page={R:4}" />
    </rule>
</code>```

--

答:
Try like this;

```<code>.*.com\/list-of-(buyers|suppers|all)-in-.*html$
</code>```

I tested it with "mysite.com/list-of-buyers-in-goa.html" and mysite.com/list-of-buyers-in-goa/page/1234.html, it matched.

Body:
I need a help writing rewrite rule for the following url pattern

www.mydomain.com/list-of-(buyers|suppers|all)-in-(location-name)/page/10.html

The first parameter will be 'buyers' or 'suppliers' or 'all'

The second parameter can be ANY location name

'/page/number' part is optional

url will always end with '.html'

UPDATE:

I have managed to write a rewrite rule which successfully matches the following url:

mysite.com/list-of-buyers-in-goa/page/5.html.

The same rule is not working for the below url

mysite.com/list-of-buyers-in-goa.html

i.e. when I remove the page/no part from the url, it doesn't work. I don't need page/no parameter for the first page.

Since all the other pages on website are .html pages, just to maintain the uniformity, I want the url to always end with .html

Here is my rewrite rule

    <rule name="Rewrite rule for listing members">
      <match url="^list-of-([a-z-A-z]+)-in-([a-zA-z-]+)?(\/page\/)?([\d+])?\.html$" />
      <action type="Rewrite" url="members.aspx?type={R:1}&location={R:2}&page={R:4}" />
    </rule>

--

Body:
Try like this;

.*.com\/list-of-(buyers|suppers|all)-in-.*html$

I tested it with "mysite.com/list-of-buyers-in-goa.html" and mysite.com/list-of-buyers-in-goa/page/1234.html, it matched.


问:
Variable arguments inside a macro
I have two functions foo1(a,b) & foo2(a,b,c) and a macro

```<code>#define add(a,b) foo(a,b)
</code>```

I need to re-define macro to accomplish,

1.if add() is called with 2 parameters, then call foo1

if add() is called with 3 parameters then call foo2

Im new to the option VA_ARGS. How can I do that

答:
If you just want to distinguish between two functions, the following works:

```<code>#define ADD(_1, _2, _3, X, ...) X
#define add(...) ADD(__VA_ARGS__, add3, add2, 0)(__VA_ARGS__)
</code>```

The auxiliary macro ADD always picks the fourth argument:

```<code>add(a, b)    --> ADD(a, b, add3, add2, 0)    --> add2
add(a, b, c) --> ADD(a, b, c, add3, add2, 0) --> add3
</code>```

The drawback is that you get quite cryptic error messages when you don't supply two or three arguments to the function.

The advantage over variadic functions is that you get type safety. For example if your functions operate on doubles, you can still say add(1, 2) and the integer arguments will be converted to doubles. And variadic functions require some additional information on the number of actual arguments, so that's not a feasible solution here, unless you specify the number of summands in the function.

Addendum: I've changed the add macro so that it doesn't pass an empty variadic list to ADD. Some compilers allow empty lists, but it isn't standard C.

Title: Variable arguments inside a macro

Body:
I have two functions foo1(a,b) & foo2(a,b,c) and a macro

#define add(a,b) foo(a,b)

I need to re-define macro to accomplish,

1.if add() is called with 2 parameters, then call foo1

if add() is called with 3 parameters then call foo2

Im new to the option VA_ARGS. How can I do that

Body:
If you just want to distinguish between two functions, the following works:

#define ADD(_1, _2, _3, X, ...) X
#define add(...) ADD(__VA_ARGS__, add3, add2, 0)(__VA_ARGS__)

The auxiliary macro ADD always picks the fourth argument:

add(a, b)    --> ADD(a, b, add3, add2, 0)    --> add2
add(a, b, c) --> ADD(a, b, c, add3, add2, 0) --> add3

The drawback is that you get quite cryptic error messages when you don't supply two or three arguments to the function.

The advantage over variadic functions is that you get type safety. For example if your functions operate on doubles, you can still say add(1, 2) and the integer arguments will be converted to doubles. And variadic functions require some additional information on the number of actual arguments, so that's not a feasible solution here, unless you specify the number of summands in the function.

Addendum: I've changed the add macro so that it doesn't pass an empty variadic list to ADD. Some compilers allow empty lists, but it isn't standard C.


问:
Retrieving the IP geo location
I have two .CSV files, one including IP addresses :

76.83.179.64

76.83.179.64

187.42.62.209

89.142.219.5

and the other includes IP ranges and country names as follow:

```<code> ip_from|  ip_to|  country_name|

|16777216|16777471|Australia|
</code>```

What I have done so far is as follow:

load the data : ip_from, ip_to and country name

```<code>val rdd1 = sqlContext.read.format("csv").option("inferSchema",
"true").load("/FileStore/tables/locations.CSV")
val df2 = rdd1.toDF()
</code>```

load the data and converts from IP to Long

```<code>val rdd2 = sc.textFile("/FileStore/tables/ipaddress.csv")
def ipToLong(ipAddress: String): Long = {
ipAddress.split("\\.").reverse.zipWithIndex
.map(a=>a._1.toInt*math.pow(256,a._2).toLong).sum
}
val df1 = rdd2.map(x=>ipToLong(x)).toDF()
</code>```

Now, what user defined function should I write to join both DFs(or look up) and retrieve the country name according the ip address?

答:
for your case you simply use following logic</p>

```<code>df1.join(df2, df1("value") >= df2("ip_from") && df1("value") <= df2("ip_to"), "left")
</code>```

Title: Retrieving the IP geo location

Body:
I have two .CSV files, one including IP addresses :

76.83.179.64

76.83.179.64

187.42.62.209

89.142.219.5

and the other includes IP ranges and country names as follow:

 ip_from|  ip_to|  country_name|

|16777216|16777471|Australia|

What I have done so far is as follow:

load the data : ip_from, ip_to and country name

val rdd1 = sqlContext.read.format("csv").option("inferSchema",
"true").load("/FileStore/tables/locations.CSV")
val df2 = rdd1.toDF()

load the data and converts from IP to Long

val rdd2 = sc.textFile("/FileStore/tables/ipaddress.csv")
def ipToLong(ipAddress: String): Long = {
ipAddress.split("\\.").reverse.zipWithIndex
.map(a=>a._1.toInt*math.pow(256,a._2).toLong).sum
}
val df1 = rdd2.map(x=>ipToLong(x)).toDF()

Now, what user defined function should I write to join both DFs(or look up) and retrieve the country name according the ip address?

Body:
for your case you simply use following logic

df1.join(df2, df1("value") >= df2("ip_from") && df1("value") <= df2("ip_to"), "left")


问:
how to protect software with dongle usb and where can I buy it?
I worked on a project for 9 months and I am finally ready to start selling it to potential clients. Before I do this, I would like to know what security measures to take so that it doesn't get hacked or stolen by pirates.

i want to secure my soft with this two conditions:

1/ check if the dongle is exist on the user pc
2/ if the dongle exist, check if the user is connected to the internet

and i want to host all the software scripts in the server ( encrypted )

my question is :

i don't have any idea about the dongle protection
is i can to turn any usb flash disk to dongle ? or i must to buy it ?

答:
Verifying authenticity of the scripts.

It is not necessary to upload the whole script to the server just to verify it is un-changed, that is what hashes are for.

Create hashes of all the scripts and save them on the server.

Have the client create a hash of the script and upload that to the server.

On the server compare the client hash with the server hash.

Note: Just about any cryptographic hash can be used, SHA-256 is a good choice, is only 32-bytes and generally quite fast.

Alternatively you could compare the hash on the client. If you are concerned with a user changing the comparison hashes in the client it is more likely the user will just remove the scrypt check. This is essentially what Apple does, it has hashes of all code files as part of the application (with a few special things).

Flash drive as a dongle: No that will notwork because a user can just duplicate the flash drive.


问:
Clearing dropdown selection office-ui-fabric react component
Im having problem clearing selections in dropdown list. I sometime have to clear the selection of a dropdown since the options population changes. If a new options length is lesser than the previous one then the selection points outside the range giving error.

Simple example:
(See: [https://developer.microsoft.com/en-us/fabric#Variants][1])

<Dropdown
              selectedKey={ selectedItem && selectedItem.key }
              onChanged={ item => this.setState({selectedItem: item}) }
              options={
                [
                  { key: 'A', text: 'Option a' },
                  { key: 'B', text: 'Option b' },
                ]
              }
/>```

The only thing I can think of is that maybe controlling selectedKey, ie setting selectedItem.key to null/undefined to clear it but Im not getting any luck with that solution..

答:
The problem I had was that I did not change my options and the selected id at the same time. What I did was that I associate each dropdown with an object:

// ...async call .then( (newFruits) => ...
this.fruits = {
  selectedId: null,
  options: ['My','newly', 'fetched','fruits','array']
};```
</div>
</div>
</p>

<p>...where fruits would be your observable Array.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><Dropdown
    selectedKey={ fruits && fruits.selectedId }
    onChanged={ this.myFuncThatCallsApiWithNewId }
    options={fruits.options}
/></code>```

Body:
Im having problem clearing selections in dropdown list. I sometime have to clear the selection of a dropdown since the options population changes. If a new options length is lesser than the previous one then the selection points outside the range giving error.

Simple example:
(See: [https://developer.microsoft.com/en-us/fabric#Variants][1])

<Dropdown
              selectedKey={ selectedItem && selectedItem.key }
              onChanged={ item => this.setState({selectedItem: item}) }
              options={
                [
                  { key: 'A', text: 'Option a' },
                  { key: 'B', text: 'Option b' },
                ]
              }
/>

The only thing I can think of is that maybe controlling selectedKey, ie setting selectedItem.key to null/undefined to clear it but Im not getting any luck with that solution..

Body:
The problem I had was that I did not change my options and the selected id at the same time. What I did was that I associate each dropdown with an object:

// ...async call .then( (newFruits) => ...
this.fruits = {
  selectedId: null,
  options: ['My','newly', 'fetched','fruits','array']
};

...where fruits would be your observable Array.

<Dropdown
    selectedKey={ fruits && fruits.selectedId }
    onChanged={ this.myFuncThatCallsApiWithNewId }
    options={fruits.options}
/>


问:
How to use Vert.x event loop to schedule RxJava execution
Is it possible to use Vert.x event loop as scheduler for RxJava execution? Something like...

```<code>Observable.range(1, 10).flatMap(it ->
  Observable.just(it)
).subscribeOn(new VertxScheduler()).
  subscribe(System.out::println);
</code>```

...where VertxScheduler should be some kind of Vert.x event loop based scheduler.

答:
As described in Vert.x RxJava documentation you can create Vert.x based scheduler using io.vertx.reactivex.RxHelper:

```<code>Vertx vertx = Vertx.vertx();
Scheduler scheduler = RxHelper.scheduler(vertx);

Observable.range(1, 10).flatMap(it ->
  Observable.just(it)
).subscribeOn(scheduler).
  subscribe(System.out::println);
</code>```

There is also RxHelper.blockingScheduler(Vertx) method creating scheduler from Vert.x worker threads pool.

Body:
Is it possible to use Vert.x event loop as scheduler for RxJava execution? Something like...

Observable.range(1, 10).flatMap(it ->
  Observable.just(it)
).subscribeOn(new VertxScheduler()).
  subscribe(System.out::println);

...where VertxScheduler should be some kind of Vert.x event loop based scheduler.

Body:
As described in Vert.x RxJava documentation you can create Vert.x based scheduler using io.vertx.reactivex.RxHelper:

Vertx vertx = Vertx.vertx();
Scheduler scheduler = RxHelper.scheduler(vertx);

Observable.range(1, 10).flatMap(it ->
  Observable.just(it)
).subscribeOn(scheduler).
  subscribe(System.out::println);

There is also RxHelper.blockingScheduler(Vertx) method creating scheduler from Vert.x worker threads pool.


问:
How can I add double quotes to a string that is inside a variable?
I have a string variable such as this:

```<code>string title = string.empty;
</code>```

I have to display the content of whatever is passed to it inside a div within double quotes. I have written something like this:

```<code>...
...
<div>"+ title +@"</div>
...
...
</code>```

How can I add the double quotes here? So that it will display like:

```<code>"How to add double quotes"
</code>```

答:
"" is used with ternary operator with Eval() data binding:

```<code>Text = '<%# Eval("bqtStatus").ToString()=="Verified" ?
       Convert.ToString("<i class=\"fa fa-check-circle\"></i>") :
       Convert.ToString("<i class=\"fa fa-info-circle\"></i>"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a string variable such as this:

string title = string.empty;

I have to display the content of whatever is passed to it inside a div within double quotes. I have written something like this:

...
...

"+ title +@"

...
...

How can I add the double quotes here? So that it will display like:

"How to add double quotes"

Body:
"<i class=\"fa fa-check-circle\"></i>" is used with ternary operator with Eval() data binding:

Text = '<%# Eval("bqtStatus").ToString()=="Verified" ?
       Convert.ToString("<i class=\"fa fa-check-circle\"></i>") :
       Convert.ToString("<i class=\"fa fa-info-circle\"></i>"


问:
Get variables from one php script to another
I have three activities in android studio!The first holds the password and email EditTexts,the second holds a button 'pause'.The third activity holds a text.
How to get the values of email and password when I click the button pause on second screen using php script?I am using a MYSQL database and a table inside of this database with email,password and pause.</p>

答:
May be you are looking for passing data from one activity to another. You can do that like below

```<code>Intent foo = new Intent(currentActivity.this, secondActivity.class);
foo.putExtra("Email", mail);
startActivity(foo);
</code>```

If you want to save on a database you can use volley package for GET and POST data from and to a server.
I hope you are looking for the first one.

Body:
May be you are looking for passing data from one activity to another. You can do that like below

Intent foo = new Intent(currentActivity.this, secondActivity.class);
foo.putExtra("Email", mail);
startActivity(foo);

If you want to save on a database you can use volley package for GET and POST data from and to a server.
I hope you are looking for the first one.


问:
WebSocketsSharp custom events deserialize
I have to build a functionality where I can send custom event with websockets-sharp.

I made a function MakePacket that creates me a string like this ["draw:drawer:accept","{\"imei\":\"123\"}"] that I can send.

```<code>    public string MakePacket(string eventName, string data)
    {
        return JsonConvert.SerializeObject(new[] { eventName, data });
    }
</code>```

So I want to do the same in the other direction. When there is an incomming event I want to convert this back to eventName and PayLoad.

So I create a data model:

```<code>public class PacketModel
{
    public string EventName { get; set; }

    public string PayLoad { get; set; }
}
</code>```

And I tried to convert this with this function:

```<code>    public PacketModel OpenPacket(string data)
    {
        PacketModel packet = JsonConvert.DeserializeObject<PacketModel>(data);

        return packet;
    }
</code>```

But this isn't working...

Does someone has an idea how I can do this?

Thank you

答:
I create an example, how to work with WebSocket-Sharp and custom events like socket.io.

I post the example in my git repository:

Websocket-Sharp Custom Events

Thanks to @Evk for the help

Body:
I have to build a functionality where I can send custom event with websockets-sharp.

I made a function MakePacket that creates me a string like this ["draw:drawer:accept","{\"imei\":\"123\"}"] that I can send.

    public string MakePacket(string eventName, string data)
    {
        return JsonConvert.SerializeObject(new[] { eventName, data });
    }

So I want to do the same in the other direction. When there is an incomming event I want to convert this back to eventName and PayLoad.

So I create a data model:

public class PacketModel
{
    public string EventName { get; set; }

    public string PayLoad { get; set; }
}

And I tried to convert this with this function:

    public PacketModel OpenPacket(string data)
    {
        PacketModel packet = JsonConvert.DeserializeObject<PacketModel>(data);

        return packet;
    }

But this isn't working...

Does someone has an idea how I can do this?

Thank you


问:
Android HandlerThread update UI without UiHandler
this code works fine  and update my "TextView" and also show "Toast"
and that is my Headache as I have tried to to pass A Runnable obj Without including my UiHandler on it as it suppose to be the bridge to update my UI Thread but my activity got updated with no single Error ?????
This not suppose to be as CustomHandlerThread should be A different thread

why this happen ?

My Activity

public class TestActivity extends BaseActivity {

```<code>Runnable task;
@BindView(R.id.send_test_message)
Button send_test_message;
private Handler mUiHandler = new Handler();
private MyWorkerThread mWorkerThread;

@Override
public void initViews() {

}

@Override
public void attachViewsListeners() {

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_activity);
    ButterKnife.bind(this);

    task = new Runnable() { ///this is normally work I have no problem with
                            ///that
        @Override
        public void run() {

                mUiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        send_test_message.setText("Change--->1");
                    }
                });

            }

    };

}

@Override
protected void onStart() {
    super.onStart();
    mWorkerThread = new MyWorkerThread("myWorkerThread");
    mWorkerThread.start();
    mWorkerThread.prepareHandler();
    mWorkerThread.postTask(task);

    mWorkerThread.postTask(new Runnable() {  /// why this task work with no
                                            ///error  ?
        @Override
        public void run() {
            send_test_message.setText("Change--->2");
        }
    });
}

@Override
protected void onDestroy() {
    mWorkerThread.quit();
    super.onDestroy();
}
</code>```

my HandlerThread

```<code>//MyWorkerThread.java
public class MyWorkerThread extends HandlerThread {

    Handler mWorkerHandler;

    public MyWorkerThread(String name) {
        super(name);
    }

    public void postTask(Runnable task) {
        mWorkerHandler.post(task);
    }

    public void prepareHandler() {

    mWorkerHandler = new Handler(getLooper());

Log.e("MyWorkerThread--->",Looper.myLooper().getThread().getName()); //-->main
Log.e("MyWorkerThread--->",getLooper().getThread().getName());//-->//myWorkerThread
Log.e("MyWorkerThread--->",Thread.currentThread().getName()); //-->main

    }
}
</code>```

I followed this link as A Referance

is My thread running on the MainThread or getLooper() intialize my
 HandlerThread with MainThread Looper ,is those log message are true

  please illuminate me

答:
After fill day of debugging i Found out That if i post A Runnable to my
  mWorkerThread with sleep() as here i got " Only the original thread that created a view hierarchy can touch its views."
  as should be.. but until I know why it not works without it
  I wish it would help some one.

```<code>   try {
                        TimeUnit.SECONDS.sleep(2);
                        send_test_message.setText("Change--->");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
</code>```

Body:
this code works fine  and update my "TextView" and also show "Toast"
and that is my Headache as I have tried to to pass A Runnable obj Without including my UiHandler on it as it suppose to be the bridge to update my UI Thread but my activity got updated with no single Error ?????
This not suppose to be as CustomHandlerThread should be A different thread

why this happen ?

My Activity

public class TestActivity extends BaseActivity {

Runnable task;
@BindView(R.id.send_test_message)
Button send_test_message;
private Handler mUiHandler = new Handler();
private MyWorkerThread mWorkerThread;

@Override
public void initViews() {

}

@Override
public void attachViewsListeners() {

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_activity);
    ButterKnife.bind(this);

    task = new Runnable() { ///this is normally work I have no problem with
                            ///that
        @Override
        public void run() {

                mUiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        send_test_message.setText("Change--->1");
                    }
                });

            }

    };

}

@Override
protected void onStart() {
    super.onStart();
    mWorkerThread = new MyWorkerThread("myWorkerThread");
    mWorkerThread.start();
    mWorkerThread.prepareHandler();
    mWorkerThread.postTask(task);

    mWorkerThread.postTask(new Runnable() {  /// why this task work with no
                                            ///error  ?
        @Override
        public void run() {
            send_test_message.setText("Change--->2");
        }
    });
}

@Override
protected void onDestroy() {
    mWorkerThread.quit();
    super.onDestroy();
}

my HandlerThread

//MyWorkerThread.java
public class MyWorkerThread extends HandlerThread {

    Handler mWorkerHandler;

    public MyWorkerThread(String name) {
        super(name);
    }

    public void postTask(Runnable task) {
        mWorkerHandler.post(task);
    }

    public void prepareHandler() {

    mWorkerHandler = new Handler(getLooper());

Log.e("MyWorkerThread--->",Looper.myLooper().getThread().getName()); //-->main
Log.e("MyWorkerThread--->",getLooper().getThread().getName());//-->//myWorkerThread
Log.e("MyWorkerThread--->",Thread.currentThread().getName()); //-->main

    }
}

I followed this link as A Referance

is My thread running on the MainThread or getLooper() intialize my
 HandlerThread with MainThread Looper ,is those log message are true

  please illuminate me

Body:
After fill day of debugging i Found out That if i post A Runnable to my
  mWorkerThread with sleep() as here i got " Only the original thread that created a view hierarchy can touch its views."
  as should be.. but until I know why it not works without it
  I wish it would help some one.

   try {
                        TimeUnit.SECONDS.sleep(2);
                        send_test_message.setText("Change--->");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


问:
AMP FORM Error: Response must contain the AMP-Access-Control-Allow-Source-Origin header

Response must contain the AMP-Access-Control-Allow-Source-Origin
  header Form submission failed: Error: Response must contain the
  AMP-Access-Control-Allow-Source-Origin header

my from

```<code><form id="aa" name="aa" method="post" target="_top" action-xhr="/gonder.asp" enctype="multipart/form-data">
<div class="ampstart-input inline-block relative m0 p0 mb3">
<input class="block border-none p0 m0" type="text" name="adSoyad" placeholder="Ad Soyad" required>
<input class="block border-none p0 m0 telefonKontrol" type="tel" name="telefon" maxlength="10" placeholder="5XX1112233" pattern="[1-9]{1}[0-9]{9}" required>
</div>
<input value="GÖNDER" class="ampstart-btn caps user-valid valid" type="submit">
<div submit-success>
<template type="amp-mustache">
<p>Bilgileriniz bize ulaştı. Size en kısa sürede geri dönüş yapılacaktır.</p>
</template>
</div>
</form>
</code>```

this c# code

```<code>public virtual ActionResult AmpRedirect(string redirectUrl, string __amp_source_origin)
{
    if (redirectUrl != string.Empty)
    {
        HttpContext.Response.AddHeader("AMP-Redirect-To", redirectUrl);
        HttpContext.Response.AddHeader("AMP-Access-Control-Allow-Source-Origin", __amp_source_origin);
        HttpContext.Response.AddHeader("Access-Control-Expose-Headers", "AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin");
    }

    HttpContext.Response.AddHeader("Content-type", "text/json");
    return Json(new {Content = ""});
}
</code>```

I needed a code to work with classic asp

答:
Check this CORS Security in AMP github guide:

CORS Security in AMP

The AMP CORS security protocol consists of three components:

The CORS Origin header The AMP-Same-Origin custom header Source origin
  restrictions via __amp_source_origin Ensuring secure requests

Verify the CORS Origin header

CORS endpoints receive the requesting origin via the Origin HTTP
  header. Endpoints should restrict requests to allow only the following
  origins:

Google AMP Cache subdomain: https://.cdn.ampproject.org (for example,
  https://nytimes-com.cdn.ampproject.org) Google AMP Cache (legacy):
  https://cdn.ampproject.org Cloudflare AMP Cache: https://.amp.cloudflare.com The Publisher’s own origins

Body:
Response must contain the AMP-Access-Control-Allow-Source-Origin
  header Form submission failed: Error: Response must contain the
  AMP-Access-Control-Allow-Source-Origin header

my from

<form id="aa" name="aa" method="post" target="_top" action-xhr="/gonder.asp" enctype="multipart/form-data">

<input class="block border-none p0 m0" type="text" name="adSoyad" placeholder="Ad Soyad" required>
<input class="block border-none p0 m0 telefonKontrol" type="tel" name="telefon" maxlength="10" placeholder="5XX1112233" pattern="[1-9]{1}[0-9]{9}" required>

<input value="GÖNDER" class="ampstart-btn caps user-valid valid" type="submit">

<template type="amp-mustache">

Bilgileriniz bize ulaştı. Size en kısa sürede geri dönüş yapılacaktır.

</template>

</form>

this c# code

public virtual ActionResult AmpRedirect(string redirectUrl, string __amp_source_origin)
{
    if (redirectUrl != string.Empty)
    {
        HttpContext.Response.AddHeader("AMP-Redirect-To", redirectUrl);
        HttpContext.Response.AddHeader("AMP-Access-Control-Allow-Source-Origin", __amp_source_origin);
        HttpContext.Response.AddHeader("Access-Control-Expose-Headers", "AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin");
    }

    HttpContext.Response.AddHeader("Content-type", "text/json");
    return Json(new {Content = ""});
}

I needed a code to work with classic asp


问:
MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating
I created /data/db in root directory and ran ./mongod:

```<code>[initandlisten] exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating
[initandlisten] shutdown: going to close listening sockets...
[initandlisten] shutdown: going to flush diaglog...
[initandlisten] now exiting
[initandlisten] shutting down with code:100
</code>```

答:
On a Mac, I had to do the following:

```<code>sudo chown -R $USER /data/db
sudo chown -R $USER /tmp/
</code>```

because there was also a file inside /tmp which Mongo also needed access

Body:
I created /data/db in root directory and ran ./mongod:

[initandlisten] exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating
[initandlisten] shutdown: going to close listening sockets...
[initandlisten] shutdown: going to flush diaglog...
[initandlisten] now exiting
[initandlisten] shutting down with code:100

Body:
On a Mac, I had to do the following:

sudo chown -R $USER /data/db
sudo chown -R $USER /tmp/

because there was also a file inside /tmp which Mongo also needed access


问:
How to clean a form with stars in javascript after submitting?
There is simple form with stars which has 2 icons: star & star_border (star is for marked one and star_border is for an empty).

The form is very simple itself:

```<code><div class="star-input">
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
</div>
</code>```

When form being loaded stars constantly changing between marked and empty while visitor haven't pressed on it. As soon as he pressed on some star the status being frozen and some stars are filled while other are empty (depending on marks). So this way ranking being formed. It is clear for me.

However I try to make a solution to clear a form to initial state after it being submitted. If you open it after a submittion now with no reload a page there is still past value being stored.

Here is JavaScript's function code:

```<code>prepareThemes.prototype.initReviewDialog = function() {
  const dialog = document.querySelector("#dialog-add-review");
  this.dialogs.add_review = new mdc.dialog.MDCDialog(dialog);

  this.dialogs.add_review.listen("MDCDialog:accept", () => {
    let pathname = this.getCleanPath(document.location.pathname);
    let id = pathname.split("/")[2];

    if (
      !dialog.querySelector("#text").value ||
      !dialog.querySelector("#textwhoareyou").value
    ) {
      alert("No text");
      return;
    } else {
      this.addRating(id, {
        rating,
        text: dialog.querySelector("#text").value,
        userName: dialog.querySelector("#textwhoareyou").value,
        timestamp: new Date(),
        userId: firebase.auth().currentUser.uid
      }).then(() => {
        this.rerender();
      });
      dialog.querySelector("#text").value = "";
      dialog.querySelector("#textwhoareyou").value = "";
    }
  });

  let rating = 0;

  dialog.querySelectorAll(".star-input i").forEach(el => {
    const rate = () => {
      let after = false;
      rating = 0;

      [].slice.call(el.parentNode.children).forEach(child => {
        if (!after) {
          rating++;
          child.innerText = "star";
        } else {
          child.innerText = "star_border";
        }
        after = after || child.isSameNode(el);
      });
    };
    el.addEventListener("mouseover", rate);
  });
};
</code>```

Thanks for any advice. Good day to everyone.

答:
Easy solution is to rebuild your div again after your form is submitted so You can do something like this:

 function doRate() {
  document.querySelectorAll('.star-input i').forEach(el => {
const rate = () => {
  let after = false;
  rating = 0;

  [].slice.call(el.parentNode.children).forEach(child => {
    if (!after) {
      rating++;
      child.innerText = 'star';
    } else {
      child.innerText = 'star_border';
    }
    after = after || child.isSameNode(el);
  });
};

el.addEventListener('mouseover', rate);
});
};

doRate();

document.querySelector('#my-form')
  .addEventListener('submit', function(e) {
    e.preventDefault();

    // Do you logic here

    // And after that rebuild your div
    var myDiv = document.querySelector('.star-input');
    myDiv.innerHTML = `
    star_border
    star_border
    star_border
    star_border
    star_border`;

    doRate();
  })
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
<form id="my-form">
<div class="star-input">
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
</div>
<button id="my-button">Rate!</button>
</form></code>```

Body:
There is simple form with stars which has 2 icons: star & star_border (star is for marked one and star_border is for an empty).

The form is very simple itself:

    star_border
    star_border
    star_border
    star_border
    star_border

When form being loaded stars constantly changing between marked and empty while visitor haven't pressed on it. As soon as he pressed on some star the status being frozen and some stars are filled while other are empty (depending on marks). So this way ranking being formed. It is clear for me.

However I try to make a solution to clear a form to initial state after it being submitted. If you open it after a submittion now with no reload a page there is still past value being stored.

Here is JavaScript's function code:

prepareThemes.prototype.initReviewDialog = function() {
  const dialog = document.querySelector("#dialog-add-review");
  this.dialogs.add_review = new mdc.dialog.MDCDialog(dialog);

  this.dialogs.add_review.listen("MDCDialog:accept", () => {
    let pathname = this.getCleanPath(document.location.pathname);
    let id = pathname.split("/")[2];

    if (
      !dialog.querySelector("#text").value ||
      !dialog.querySelector("#textwhoareyou").value
    ) {
      alert("No text");
      return;
    } else {
      this.addRating(id, {
        rating,
        text: dialog.querySelector("#text").value,
        userName: dialog.querySelector("#textwhoareyou").value,
        timestamp: new Date(),
        userId: firebase.auth().currentUser.uid
      }).then(() => {
        this.rerender();
      });
      dialog.querySelector("#text").value = "";
      dialog.querySelector("#textwhoareyou").value = "";
    }
  });

  let rating = 0;

  dialog.querySelectorAll(".star-input i").forEach(el => {
    const rate = () => {
      let after = false;
      rating = 0;

      [].slice.call(el.parentNode.children).forEach(child => {
        if (!after) {
          rating++;
          child.innerText = "star";
        } else {
          child.innerText = "star_border";
        }
        after = after || child.isSameNode(el);
      });
    };
    el.addEventListener("mouseover", rate);
  });
};

Thanks for any advice. Good day to everyone.

Body:
Easy solution is to rebuild your div again after your form is submitted so You can do something like this:

 function doRate() {
  document.querySelectorAll('.star-input i').forEach(el => {
const rate = () => {
  let after = false;
  rating = 0;

  [].slice.call(el.parentNode.children).forEach(child => {
    if (!after) {
      rating++;
      child.innerText = 'star';
    } else {
      child.innerText = 'star_border';
    }
    after = after || child.isSameNode(el);
  });
};

el.addEventListener('mouseover', rate);
});
};

doRate();

document.querySelector('#my-form')
  .addEventListener('submit', function(e) {
    e.preventDefault();

    // Do you logic here

    // And after that rebuild your div
    var myDiv = document.querySelector('.star-input');
    myDiv.innerHTML = `
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>`;

    doRate();
  })

<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
<form id="my-form">
<div class="star-input">
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
    <i class="material-icons">star_border</i>
</div>
<button id="my-button">Rate!</button>
</form>


问:
Selenium: Set the node thats executing by ip (or something else)
I am using the Selenium Grid with a hub on the server.
To debug easier I want to execute the test on my specific pc and not on other nodes. (all Nodes are allways online)
is there something like an ip-capability? (All Nodes running same Browser and Platform, etc.)
Otherwise I have to do a Grid-Execution.java and a Local-Execution.java?
If you have another idea how to do that, let me know! Greetings Arno</p>

答:
In our framework, there is a system property "IsLocal" and it is always true. We set it to false and pass additional parameter like hub ip and port number if we want to execute on the grid.

Also, this value we can pass it from maven command line, if we execute from IDE then, the value is null, if it is null, the it will take default value, ie true. So it will always execute on local. if we need to test it on grid, we pass the IsLocal system value from maven or command line.

In our driver Factory launch browser method. we always check this property if it true, we launch  browser using local driver otherwise remote web driver. something like below code.

```<code>boolean IsLocal=true;
if(System.getProperty("IsLocal")!=null){
      IsLocal=System.getProperty("IsLocal");
}

if(IsLocal){
    driver=new FirefoxDriver();
}
else{
    driver= new RemoteWebDriver(HUBURL, DesiredCap);
}
</code>```

Body:
In our framework, there is a system property "IsLocal" and it is always true. We set it to false and pass additional parameter like hub ip and port number if we want to execute on the grid.

Also, this value we can pass it from maven command line, if we execute from IDE then, the value is null, if it is null, the it will take default value, ie true. So it will always execute on local. if we need to test it on grid, we pass the IsLocal system value from maven or command line.

In our driver Factory launch browser method. we always check this property if it true, we launch  browser using local driver otherwise remote web driver. something like below code.

boolean IsLocal=true;
if(System.getProperty("IsLocal")!=null){
      IsLocal=System.getProperty("IsLocal");
}

if(IsLocal){
    driver=new FirefoxDriver();
}
else{
    driver= new RemoteWebDriver(HUBURL, DesiredCap);
}


问:
PHP strpos not checking multiple items correctly
I am pulling in live prices via an api and am checking the CHANGEPCT24HOUR value.

If value is negative I want a down arrow, if it is positive would give a green up arrow.

The code below isnt working correctly.
The current values are BTC : 8.32 & ETH : -2.86

Code:

```<code>      $json_string =    file_get_contents("https://myapi.com/?fsyms=BTC,ETH,DASH,LTC,NEO,XRP&tsyms=USD");
      $parsed_json = json_decode($json_string, true);
      $btcp = $parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
      $ethp = $parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];
      if(strpos($btcp,'-') == FALSE){
         $btc = "<i class=\"fa fa-fw fa-arrow-up\" style=\"color:green\"></i>".$parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
         } else {
         $btc = "<i class=\"fa fa-fw fa-arrow-down\" style=\"color:red\"></i>".$parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
         }
      if(strpos($ethp,'-') == FALSE){
         $eth = "<i class=\"fa fa-fw fa-arrow-up\" style=\"color:green\"></i>".$parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];
         } else {
         $eth = "<i class=\"fa fa-fw fa-arrow-down\" style=\"color:red\"></i>".$parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];

         }
      $livechange = "BTC : ".$btc.'<br />';
      $livechange .= "ETH : ".$eth;
      echo $livechange;
</code>```

It's showing an up arrow for both. However if I change the $eth strpos check to this
     if(strpos($ethp,'-') == FALSE)
and then switch the order or the $eth around it works fine.

I don't know why the original strpos method won't work properly for the second check.

答:
You need to use === instead of == since strpos will return 0 if the character you looked for is in the first position of the string.

So in -50 :

strpos('-50', '-') == 0 == FALSE // This is true

strpos('-50', '-') === FALSE // This is false

Body:
I am pulling in live prices via an api and am checking the CHANGEPCT24HOUR value.

If value is negative I want a down arrow, if it is positive would give a green up arrow.

The code below isnt working correctly.
The current values are BTC : 8.32 & ETH : -2.86

Code:

      $json_string =    file_get_contents("https://myapi.com/?fsyms=BTC,ETH,DASH,LTC,NEO,XRP&tsyms=USD");
      $parsed_json = json_decode($json_string, true);
      $btcp = $parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
      $ethp = $parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];
      if(strpos($btcp,'-') == FALSE){
         $btc = "".$parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
         } else {
         $btc = "".$parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
         }
      if(strpos($ethp,'-') == FALSE){
         $eth = "".$parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];
         } else {
         $eth = "".$parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];

         }
      $livechange = "BTC : ".$btc.'
';
      $livechange .= "ETH : ".$eth;
      echo $livechange;

It's showing an up arrow for both. However if I change the $eth strpos check to this
     if(strpos($ethp,'-') == FALSE)
and then switch the order or the $eth around it works fine.

I don't know why the original strpos method won't work properly for the second check.


问:
How to display MYSQL table columns in a CSS block style?
I want to display table columns in a css display:block style.The end result i want should look like the table below.

I use MYSQL and PHP to display the columns of the table

This is how the data from the table currently looks like when it is rendered in the browser.

Source code

```<code><?php

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);
for ( $i = 0; $i < $numcolumn; $i++ ) {
 $columnnames = mysql_field_name($result, $i);

  echo "<table style ='width:100%'>";
  echo "<tr>";

  echo "<th>".$columnnames. "</th>";

  echo "</tr>";
  echo "</table>";

 }
 ?>
</code>```

答:
you need to remove table, tr open tag and closing tag from loop like below code. then you will expected ouput.<br>

```<code>error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);
   echo "<table style ='width:100%'>";
     echo "<tr>";
for ( $i = 0; $i < $numcolumn; $i++ ) {
     $columnnames = mysql_field_name($result, $i);
     echo "<th>".$columnnames. "</th>";
 }

 echo "</tr>";
 echo "</table>";
?>
</code>```

Body:
I want to display table columns in a css display:block style.The end result i want should look like the table below.

I use MYSQL and PHP to display the columns of the table

This is how the data from the table currently looks like when it is rendered in the browser.

Source code

<?php

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);
for ( $i = 0; $i < $numcolumn; $i++ ) {
 $columnnames = mysql_field_name($result, $i);

  echo "
";
  echo "
";

  echo "".$columnnames. "	";

  echo "
";
  echo "
";

 }
 ?>

Body:
you need to remove table, tr open tag and closing tag from loop like below code. then you will expected ouput.

error_reporting(E_ALL ^ E_DEPRECATED);

mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("automobile")or die("Connection Failed");
$query = "select * from amin";
$result = mysql_query($query);
$numcolumn = mysql_num_fields($result);
   echo "<table style ='width:100%'>";
     echo "<tr>";
for ( $i = 0; $i < $numcolumn; $i++ ) {
     $columnnames = mysql_field_name($result, $i);
     echo "<th>".$columnnames. "</th>";
 }

 echo "</tr>";
 echo "</table>";
?>


问:
Making columns to be dynamic by adding checkboxe in Shiny
I've been trying to add a row (basically a row of check boxes) on my data table, so that users will be able to decide which column they like to keep/delete. And here is what my Shiny App looks like so far. Anyone who knows any hints please help!

Any help would be appreciated!

```<code>ui <- dashboardPage(dashboardHeader(disable = T),
                dashboardSidebar(disable = T),
                dashboardBody(uiOutput("MainBody")))

server <- shinyServer(function(input, output){
  vals <- reactiveValues()
  vals$data <- data.table(vals$Data<-data.table(
           Brands=paste0("Brand",1:10),
           Forecasted_Growth=sample(1:20,10),
           Last_Year_Purchase=round(rnorm(10,1000,1000)^2),
           Contact=paste0("Brand",1:10,"@email.com")
 ))

      output$MainBody <- renderUI({
        fluidPage(
          box(width = 12,
          h3(strong("Template"), align = "center"),
          hr(),
          column(6, offset = 6,
                 actionButton(inputId = "Del_Col", label = "Delete Select Column"))),
      column(12, dataTableOutput("MainTable")),
      tags$script()
    )
  })
</code>```

答:
I agree with Pork Chop that you should rethink your layout. I couldn't get my head around it so I reworked it into a minimal fluidpage.

The code below should get you close. It renders buttons (you could make these checkboxes though) directly into the table using a helper function described here. The code below uses these buttons to subset and update the dataframe which I term reactiveTable. Here's the functionality:

Good luck!

```<code>library(data.table)
library(DT)

## Nice helper function to make the buttons from:
## https://github.com/rstudio/DT/issues/178
shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), ...))
  }
  inputs
}

## Basic UI with a reset button
ui <- fluidPage(
  mainPanel(
    h1('Table Subsetter'),
    actionButton('reset', 'Reset!'),
    DT::dataTableOutput('mytable')
  )
)

server <- function(input, output){

  #This is the table you provided in your question
  tableA <- data.table(
    Brands=paste0("Brand",1:10),
    Forecasted_Growth=sample(1:20,10),
    Last_Year_Purchase=round(rnorm(10,1000,1000)^2),
    Contact=paste0("Brand",1:10,"@email.com")
  )

  #make a reactive value for the table and columns to delete
  reactiveTable <- reactiveValues(tab=tableA)
  columnToDelete <- reactiveValues(col=NULL)

  #Logic to make the buttons, reruns everytime the table is updated
  tableOut <- reactive({
    buttons <- shinyInput(actionButton, length(reactiveTable$tab[1,]), 'button_', label = "Delete!", onclick = 'Shiny.onInputChange(\"select_button\",  this.id)' )
    buttons <- t(as.data.frame(buttons, stringsAsFactors = FALSE))
    colnames(buttons) = colnames(reactiveTable$tab)
    rbind(buttons, reactiveTable$tab)
  })

  #reset button replaces the table
  observeEvent(input$reset, {
    reactiveTable$tab <- tableA
  })

  #listener to for the delete button
  observeEvent(input$select_button, {
    columnToDelete$col <-as.numeric(strsplit(input$select_button, "_")[[1]][2])
      reactiveTable$tab <- subset( reactiveTable$tab, select = -columnToDelete$col )
  })

  #output the table with DT. use escape=F so it renders the html
  output$mytable <- DT::renderDataTable({
                      tableOut()
                      },server = FALSE, escape = FALSE, selection = 'none')

}
shinyApp(ui = ui, server = server)
</code>```

Body:
I've been trying to add a row (basically a row of check boxes) on my data table, so that users will be able to decide which column they like to keep/delete. And here is what my Shiny App looks like so far. Anyone who knows any hints please help!

Any help would be appreciated!

ui <- dashboardPage(dashboardHeader(disable = T),
                dashboardSidebar(disable = T),
                dashboardBody(uiOutput("MainBody")))

server <- shinyServer(function(input, output){
  vals <- reactiveValues()
  vals$data <- data.table(vals$Data<-data.table(
           Brands=paste0("Brand",1:10),
           Forecasted_Growth=sample(1:20,10),
           Last_Year_Purchase=round(rnorm(10,1000,1000)^2),
           Contact=paste0("Brand",1:10,"@email.com")
 ))

      output$MainBody <- renderUI({
        fluidPage(
          box(width = 12,
          h3(strong("Template"), align = "center"),
          hr(),
          column(6, offset = 6,
                 actionButton(inputId = "Del_Col", label = "Delete Select Column"))),
      column(12, dataTableOutput("MainTable")),
      tags$script()
    )
  })

Body:
I agree with Pork Chop that you should rethink your layout. I couldn't get my head around it so I reworked it into a minimal fluidpage.

The code below should get you close. It renders buttons (you could make these checkboxes though) directly into the table using a helper function described here. The code below uses these buttons to subset and update the dataframe which I term reactiveTable. Here's the functionality:

Good luck!

library(data.table)
library(DT)

## Nice helper function to make the buttons from:
## https://github.com/rstudio/DT/issues/178
shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), ...))
  }
  inputs
}

## Basic UI with a reset button
ui <- fluidPage(
  mainPanel(
    h1('Table Subsetter'),
    actionButton('reset', 'Reset!'),
    DT::dataTableOutput('mytable')
  )
)

server <- function(input, output){

  #This is the table you provided in your question
  tableA <- data.table(
    Brands=paste0("Brand",1:10),
    Forecasted_Growth=sample(1:20,10),
    Last_Year_Purchase=round(rnorm(10,1000,1000)^2),
    Contact=paste0("Brand",1:10,"@email.com")
  )

  #make a reactive value for the table and columns to delete
  reactiveTable <- reactiveValues(tab=tableA)
  columnToDelete <- reactiveValues(col=NULL)

  #Logic to make the buttons, reruns everytime the table is updated
  tableOut <- reactive({
    buttons <- shinyInput(actionButton, length(reactiveTable$tab[1,]), 'button_', label = "Delete!", onclick = 'Shiny.onInputChange(\"select_button\",  this.id)' )
    buttons <- t(as.data.frame(buttons, stringsAsFactors = FALSE))
    colnames(buttons) = colnames(reactiveTable$tab)
    rbind(buttons, reactiveTable$tab)
  })

  #reset button replaces the table
  observeEvent(input$reset, {
    reactiveTable$tab <- tableA
  })

  #listener to for the delete button
  observeEvent(input$select_button, {
    columnToDelete$col <-as.numeric(strsplit(input$select_button, "_")[[1]][2])
      reactiveTable$tab <- subset( reactiveTable$tab, select = -columnToDelete$col )
  })

  #output the table with DT. use escape=F so it renders the html
  output$mytable <- DT::renderDataTable({
                      tableOut()
                      },server = FALSE, escape = FALSE, selection = 'none')

}
shinyApp(ui = ui, server = server)


问:
Retrieve value from query string?
How can I retrieve the value of a Query String Parameter using Expression Language in a JSP?</p>

答:
```<code><c:out value = "${pageContext.request.queryString}" />
</code>```

update:

If you want certain value for example ?key1=val1&key2=val2

then

```<code><c:out value = "${param.key1}" />

<c:out value = "${param.key2}" />
</code>```

Title: Retrieve value from query string?

Body:
<c:out value = "${pageContext.request.queryString}" />

update:

If you want certain value for example ?key1=val1&key2=val2

then

<c:out value = "${param.key1}" />

<c:out value = "${param.key2}" />


问:
Google API to recover data
in google drive, there's a tab named "backups" that contains data from old android phones I have.
These backups are not downloadable.

Is there a way to download these backup files? is there a way to get the information inside the backup files?  ( API requests )

I know that for the Whatsapp backup-file there is a different API (because it's not downloadable like the others).

答: There's no mention of accessing the backup folder in Drive API. But, if you're referring to a special folder called App Folder which is only accessible by your application, then you can. Check the Get authorization to use the App Folder.</p>

Title: Google API to recover data


问:
How to Share cookies in differents ASP.NET aplications
We have two ASP aplications running at the same server (in different subdomains), the first one is a Web Forms aplications (I'll call that App A) and the new one a APS.NET MVC aplication (App B).

The App B need to login in the App A restrited area, I saw in the web about sharing cookies in differents applications, but, in my tests, the redirect works, however the cookies can't be found.

Here's how I send cookies in App B:

```<code>var log = auth.GetLogin(user, password, Request.ServerVariables["REMOTE_ADDR"], 1);

if (!log.isPasswordValid)
    throw new Exception("user or password incorrect!");

FormsAuthentication.SetAuthCookie(user, false);
</code>```

And, in the App A, here's how I try to get the cookie:

```<code>if(HttpContext.Current.Request.Cookies["ASPXAUTH"] != null)
{
    var user = httpContext.Current.Request.Cookies["ASPXAUTH"].Value;
    Session["LoginUser"] = user;
}
</code>```

the ASPXAUTH key is the authentication in Web.Config

```<code><authentication mode="Forms">
  <forms loginUrl="/Login/Acess" enableCrossAppRedirects="true" path="/" name=".ASPXAUTHX" domain="dev.com.br" protection="All" />
</authentication>
</code>```

The Wrost part is that I can't even debug the application to check values :(

Can someone help me ?

EDIT 1

I followed those instructions in this page and, sometime I've getting the redirect "correctly", but with no sessions at all.

Here's the code (in the App a here I recive the cookies):

```<code>if (HttpContext.Current.Request.IsAuthenticated)
{
    for (int i = 0; i < HttpContext.Current.User.Identity.Name.Length; i++)
    {
        userId += userId  = HttpContext.Current.User.Identity.Name[i].ToString();
    }
}
</code>```

Sometimes the userId doesn't came, and it throws a exception in the Length part (the HttpContext.Current.User.Identity.Name comes null).

My thoughts is that the ApplicationName App A is not the same as the App B, but I tried to change in this page and it didn't work.

Can somebody help me?

答:
The following example shows the Authentication section of a Web.config file. Unless otherwise noted, the name, protection, path, validationKey, validation, decryptionKey, and decryption attributes must be identical across all applications. Similarly, the encryption and validation keys and the encryption scheme and validation scheme used for cookie data must be exactly the same. If the settings do not match, cookies cannot be shared. </p>

```<code><configuration>
  <system.web>
    <authentication mode="Forms" >
      <!-- The name, protection, and path attributes must match
           exactly in each Web.config file. -->
      <forms loginUrl="login.aspx"
        name=".ASPXFORMSAUTH"
        protection="All"
        path="/"
        timeout="30"
        domain="MyWeb.com"
 />
    </authentication>

    <!-- Validation and decryption keys must exactly match and cannot
         be set to "AutoGenerate". The validation and decryption
         algorithms must also be the same. -->
    <machineKey
      validationKey="[your key here]"
      decryptionKey="[your key here]"
      validation="SHA1" />
  </system.web>
</configuration>
</code>```

Body:
We have two ASP aplications running at the same server (in different subdomains), the first one is a Web Forms aplications (I'll call that App A) and the new one a APS.NET MVC aplication (App B).

The App B need to login in the App A restrited area, I saw in the web about sharing cookies in differents applications, but, in my tests, the redirect works, however the cookies can't be found.

Here's how I send cookies in App B:

var log = auth.GetLogin(user, password, Request.ServerVariables["REMOTE_ADDR"], 1);

if (!log.isPasswordValid)
    throw new Exception("user or password incorrect!");

FormsAuthentication.SetAuthCookie(user, false);

And, in the App A, here's how I try to get the cookie:

if(HttpContext.Current.Request.Cookies["ASPXAUTH"] != null)
{
    var user = httpContext.Current.Request.Cookies["ASPXAUTH"].Value;
    Session["LoginUser"] = user;
}

the ASPXAUTH key is the authentication in Web.Config

<authentication mode="Forms">
  <forms loginUrl="/Login/Acess" enableCrossAppRedirects="true" path="/" name=".ASPXAUTHX" domain="dev.com.br" protection="All" />
</authentication>

The Wrost part is that I can't even debug the application to check values :(

Can someone help me ?

EDIT 1

I followed those instructions in this page and, sometime I've getting the redirect "correctly", but with no sessions at all.

Here's the code (in the App a here I recive the cookies):

if (HttpContext.Current.Request.IsAuthenticated)
{
    for (int i = 0; i < HttpContext.Current.User.Identity.Name.Length; i++)
    {
        userId += userId  = HttpContext.Current.User.Identity.Name[i].ToString();
    }
}

Sometimes the userId doesn't came, and it throws a exception in the Length part (the HttpContext.Current.User.Identity.Name comes null).

My thoughts is that the ApplicationName App A is not the same as the App B, but I tried to change in this page and it didn't work.

Can somebody help me?

Body:
The following example shows the Authentication section of a Web.config file. Unless otherwise noted, the name, protection, path, validationKey, validation, decryptionKey, and decryption attributes must be identical across all applications. Similarly, the encryption and validation keys and the encryption scheme and validation scheme used for cookie data must be exactly the same. If the settings do not match, cookies cannot be shared.

<configuration>
  <system.web>
    <authentication mode="Forms" >
      <!-- The name, protection, and path attributes must match
           exactly in each Web.config file. -->
      <forms loginUrl="login.aspx"
        name=".ASPXFORMSAUTH"
        protection="All"
        path="/"
        timeout="30"
        domain="MyWeb.com"
 />
    </authentication>

    <!-- Validation and decryption keys must exactly match and cannot
         be set to "AutoGenerate". The validation and decryption
         algorithms must also be the same. -->
    <machineKey
      validationKey="[your key here]"
      decryptionKey="[your key here]"
      validation="SHA1" />
  </system.web>
</configuration>


问:
Python Tkinter multiprocessing progress
For my work, I frequently have to collect reasonably large datasets from a MySQL database, e.g. several parameters for several locations, and store that data in a CSV file per location. For this, I've written a small GUI. Since, the data has to be stored per location, I thought I'd take advantages of my 8-thread CPU and use the multiprocessing package to query the database per location. This works just fine, but I also want to keep track of how far the data retrieval and file writing is.

The trick with using multiprocessing together with Tkinter was to put the function that is called in the multiprocessing outside of the GUI class, but how do I get information from that function back into the class?

My code so far:

```<code>from multiprocessing import Process
from tkinter import *
import os
import pandas
import pymysql

class App:

    def __init__(self, master):
        self.master = master
        self.stations = None
        self.variables = None
        self.startdtg = None
        self.enddtg = None
        self.outputlocation = "C:/Users/test"
        self.processes = []

        Label(master, text="Locations:").grid(row=0, column=0, sticky=W, columnspan=3)
        self.locationEntry = Entry(master)
        self.locationEntry.grid(row=0, column=1, sticky=EW, columnspan=3)

        Label(master, text="Enter variables:").grid(row=1, column=0, sticky=W)
        self.varEntry = Entry(master)
        self.varEntry.grid(row=1, column=1, sticky=EW, columnspan=3)

        Label(master, text="Start DTG:").grid(row=2, column=0, sticky=W)
        self.startEntry = Entry(master)
        self.startEntry.grid(row=2, column=1, sticky=EW)

        Label(master, text="End DTG:").grid(row=2, column=2, sticky=W)
        self.endEntry = Entry(master)
        self.endEntry.grid(row=2, column=3, sticky=EW)

        Label(master, text="Output location:").grid(row=3, column=0, sticky=W)
        self.outputEntry = Entry(master)
        self.outputEntry.grid(row=3, column=1, columnspan=2, sticky=EW)

        self.startButton = Button(master, text="Start", command=self.get_data)
        self.startButton.grid(row=5, column=1, sticky=EW)

    def get_data(self):
        self.update_variables()
        self.collect_data()

    def update_variables(self):
        self.stations = [station.strip() for station in self.locationEntry.get().split(",")]
        self.variables = [variable.strip() for variable in self.varEntry.get().split(",")]
        self.startdtg = self.startEntry.get()
        self.enddtg = self.endEntry.get()
        self.outputlocation = os.path.join(self.outputlocation, self.outputEntry.get())

    def collect_data(self):
        for station in self.stations:
            p = Process(target=query_database, args=(station, self.variables, self.startdtg, self.enddtg, self.outputlocation))
            self.processes.append(p)
            p.start()

def query_database(station, variables, startdtg, enddtg, outputlocation):
    """"Function that collects and writes data to local drive"""

if __name__ == "__main__":
    root = Tk()
    app = App(root)
    root.mainloop()
</code>```

To be clear: this code works fine. It produces this GUI:

What I want, is a GUI like this:

With the  part showing the progress of the query_database function, meaning it has to update when a step in that function has been completed.

How would I approach this? Also, feel free to give any comments about my coding, I'm still learning the basics of GUIs and setting up classes.

答:
Let's sum what was said in comments:

To get information from function, which executed in another process,
you should communicate with function's process with either a Queue or a Pipe.

While you have a channel to communicate with - keep checking
continiously for messages via self-scheduling
after.

Keep in mind that idea to pass a Label or anything tk-related to
that process isn't an option, since it isn't a thread/process-safe
practice.

After all of this you should come with something similar to this approach:

```<code>try:
    import Tkinter as tk              # Python 2
    import ttk
    import Queue as queue
except ImportError:
    import tkinter as tk              # Python 3
    import tkinter.ttk as ttk
    import queue

import multiprocessing as mp
import time

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.minsize(width=400, height=25)

        self.label = tk.Label(self, text='Waiting for "work"')
        self.label.pack(expand=True, fill='both')

        self.progressbar = ttk.Progressbar(self, orient='horizontal', value=0, maximum=3, mode='determinate')
        self.progressbar.pack(fill='x')

        self.button = tk.Button(self, text='Start', command=self.start_work)
        self.button.pack(fill='x')

        self.queue = mp.Queue()
        self.process = None

    def start_work(self):
        self.process = mp.Process(target=work, args=(self.queue,))
        self.button.configure(state='disabled')
        self.process.start()
        self.periodic_call()

    def periodic_call(self):
        #   check a queue once
        self.check_queue()

        #   if exit code is None - process is on the run and we should re-schedule check
        if self.process.exitcode is None:
            self.after(100, self.periodic_call)
        #   things are executed
        else:
            self.process.join()
            self.button.configure(state='normal')
            self.label.configure(text='Waiting for "work"')
            self.progressbar.configure(value=0)

    def check_queue(self):
        #   common check of the queue
        while self.queue.qsize():
            try:
                self.label.configure(text=self.queue.get(0))
                self.progressbar.configure(value=self.progressbar['value'] + 1)
            except queue.Empty:
                pass

def work(working_queue):
    for type_of_work in ['Combobulationg Discombobulator', 'Pointing towards space',
                         'Calculating Ultimate Answer']:
        working_queue.put(type_of_work)
        time.sleep(1.5)

if __name__ == '__main__':
    app = App()
    app.mainloop()
</code>```

Title: Python Tkinter multiprocessing progress

Body:
For my work, I frequently have to collect reasonably large datasets from a MySQL database, e.g. several parameters for several locations, and store that data in a CSV file per location. For this, I've written a small GUI. Since, the data has to be stored per location, I thought I'd take advantages of my 8-thread CPU and use the multiprocessing package to query the database per location. This works just fine, but I also want to keep track of how far the data retrieval and file writing is.

The trick with using multiprocessing together with Tkinter was to put the function that is called in the multiprocessing outside of the GUI class, but how do I get information from that function back into the class?

My code so far:

from multiprocessing import Process
from tkinter import *
import os
import pandas
import pymysql

class App:

    def __init__(self, master):
        self.master = master
        self.stations = None
        self.variables = None
        self.startdtg = None
        self.enddtg = None
        self.outputlocation = "C:/Users/test"
        self.processes = []

        Label(master, text="Locations:").grid(row=0, column=0, sticky=W, columnspan=3)
        self.locationEntry = Entry(master)
        self.locationEntry.grid(row=0, column=1, sticky=EW, columnspan=3)

        Label(master, text="Enter variables:").grid(row=1, column=0, sticky=W)
        self.varEntry = Entry(master)
        self.varEntry.grid(row=1, column=1, sticky=EW, columnspan=3)

        Label(master, text="Start DTG:").grid(row=2, column=0, sticky=W)
        self.startEntry = Entry(master)
        self.startEntry.grid(row=2, column=1, sticky=EW)

        Label(master, text="End DTG:").grid(row=2, column=2, sticky=W)
        self.endEntry = Entry(master)
        self.endEntry.grid(row=2, column=3, sticky=EW)

        Label(master, text="Output location:").grid(row=3, column=0, sticky=W)
        self.outputEntry = Entry(master)
        self.outputEntry.grid(row=3, column=1, columnspan=2, sticky=EW)

        self.startButton = Button(master, text="Start", command=self.get_data)
        self.startButton.grid(row=5, column=1, sticky=EW)

    def get_data(self):
        self.update_variables()
        self.collect_data()

    def update_variables(self):
        self.stations = [station.strip() for station in self.locationEntry.get().split(",")]
        self.variables = [variable.strip() for variable in self.varEntry.get().split(",")]
        self.startdtg = self.startEntry.get()
        self.enddtg = self.endEntry.get()
        self.outputlocation = os.path.join(self.outputlocation, self.outputEntry.get())

    def collect_data(self):
        for station in self.stations:
            p = Process(target=query_database, args=(station, self.variables, self.startdtg, self.enddtg, self.outputlocation))
            self.processes.append(p)
            p.start()

def query_database(station, variables, startdtg, enddtg, outputlocation):
    """"Function that collects and writes data to local drive"""

if __name__ == "__main__":
    root = Tk()
    app = App(root)
    root.mainloop()

To be clear: this code works fine. It produces this GUI:

What I want, is a GUI like this:

With the  part showing the progress of the query_database function, meaning it has to update when a step in that function has been completed.

How would I approach this? Also, feel free to give any comments about my coding, I'm still learning the basics of GUIs and setting up classes.

Body:
Let's sum what was said in comments:

To get information from function, which executed in another process,
you should communicate with function's process with either a Queue or a Pipe.

While you have a channel to communicate with - keep checking
continiously for messages via self-scheduling
after.

Keep in mind that idea to pass a Label or anything tk-related to
that process isn't an option, since it isn't a thread/process-safe
practice.

After all of this you should come with something similar to this approach:

try:
    import Tkinter as tk              # Python 2
    import ttk
    import Queue as queue
except ImportError:
    import tkinter as tk              # Python 3
    import tkinter.ttk as ttk
    import queue

import multiprocessing as mp
import time

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.minsize(width=400, height=25)

        self.label = tk.Label(self, text='Waiting for "work"')
        self.label.pack(expand=True, fill='both')

        self.progressbar = ttk.Progressbar(self, orient='horizontal', value=0, maximum=3, mode='determinate')
        self.progressbar.pack(fill='x')

        self.button = tk.Button(self, text='Start', command=self.start_work)
        self.button.pack(fill='x')

        self.queue = mp.Queue()
        self.process = None

    def start_work(self):
        self.process = mp.Process(target=work, args=(self.queue,))
        self.button.configure(state='disabled')
        self.process.start()
        self.periodic_call()

    def periodic_call(self):
        #   check a queue once
        self.check_queue()

        #   if exit code is None - process is on the run and we should re-schedule check
        if self.process.exitcode is None:
            self.after(100, self.periodic_call)
        #   things are executed
        else:
            self.process.join()
            self.button.configure(state='normal')
            self.label.configure(text='Waiting for "work"')
            self.progressbar.configure(value=0)

    def check_queue(self):
        #   common check of the queue
        while self.queue.qsize():
            try:
                self.label.configure(text=self.queue.get(0))
                self.progressbar.configure(value=self.progressbar['value'] + 1)
            except queue.Empty:
                pass

def work(working_queue):
    for type_of_work in ['Combobulationg Discombobulator', 'Pointing towards space',
                         'Calculating Ultimate Answer']:
        working_queue.put(type_of_work)
        time.sleep(1.5)

if __name__ == '__main__':
    app = App()
    app.mainloop()