问:
How to communicate between two process and two hosts using UDP datagrams on Android
My distributed application, with various hosts need to find local servers within the same LAN.

I had limited success detecting local servers using NsdManager, which is the way to go, but often, servers remain undetected. I am looking for a better solution, something more reliable.

Then I attempted to multicast UDP packets, which I have no problem detecting from within the same process. (My unit test uses both client and servers instances). That works fine. The same classes will not allow my clients to detect my servers running on the same device (client and servers are separate process applications).

Then I varied my approach using broadcast addresses, again, within the same process, unit tests are fine, but in two distinct process, no server found.

As I said, the code works fine within the same process, but they do not work when running in two distinct processes, or on two distinct client / server hosts within the same LAN.

Note: my LAN is a high end WiFi rooter, no special settings.

Anyone has any clue what might be the problem?

Note that my manifest includes these settings for both client and server applications:

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

Note that for my client to detect the server running on the same Host, I am already using TCP sockets, but I need to detect whatever server is in my LAN.

答:
@Onik was quite right,

Making a Minimal, Complete, and Verifiable example allowed me to find the problem.

Here is the code for whoever may be interested:

```<code>package com.example;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;

import android.util.Log;

/**
 * Minimal, Complete, and Verifiable example for broadcasting UDP sockets, send thread.
 *
 * Loosely based on:
 *
 * https://jackiexie.com/2015/07/15/network-discovery-using-udp-broadcast-java/
 */
public class BroadcastSender extends Thread {

public static final String TAG = "BroadcastSender";

public static final int TEST_PORT_NUMBER            = 1234;
public static final int TEST_COUNT                  = 10;
public static final int DELAY_BETWEEN_PACKETS_MS    = 500;

public static final int TEST_TIME_MS    =   TEST_COUNT * DELAY_BETWEEN_PACKETS_MS;

private DatagramSocket mSocket;

public BroadcastSender() {

    super( TAG );
}

public static InetAddress getBroadcastAddress() {

    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

        while( interfaces.hasMoreElements() ) {

            NetworkInterface current = interfaces.nextElement();

            try {

                if( !current.isUp()  )
                    continue;

                if( current.isLoopback() )
                    continue;

                List<InterfaceAddress> addresses = current.getInterfaceAddresses();

                if( addresses == null ) {

                    log("getBroadcastAddress can not get addresses from "+current);
                    continue;
                }

                for( InterfaceAddress oneInterfaceAddress : addresses ) {

                    InetAddress bcast = oneInterfaceAddress.getBroadcast();

                    if( bcast != null )
                        return bcast;
                }
            }
            catch( Exception ex) {

                log( "getBroadcastAddress exception "+ex+" stack "+Log.getStackTraceString(ex) );
            }
        }
    }
    catch( Exception ex) {

        log( "getBroadcastAddress exception "+ex+" stack "+Log.getStackTraceString(ex) );
    }

    return null;
}

@Override
public void run() {

    try {

        mSocket = new DatagramSocket();
        mSocket.setBroadcast(true);

        InetAddress interfaceBroadcast = getBroadcastAddress();

        InetAddress broadcastAddr = InetAddress.getByName("255.255.255.255");

        String payloadStr   = "payload pid="+android.os.Process.myPid();
        byte payloadBytes[] = payloadStr.getBytes();

        for( int packet = 0; packet < TEST_COUNT; packet++) {

            // First send to 255.255.255.255
            DatagramPacket dp = new DatagramPacket(payloadBytes, payloadBytes.length, broadcastAddr, TEST_PORT_NUMBER);
            mSocket.send(dp);

            // Then send to whatever address we have for interfaceBroadcast
            if( interfaceBroadcast != null ) {

                dp = new DatagramPacket(payloadBytes, payloadBytes.length, interfaceBroadcast, TEST_PORT_NUMBER);
                mSocket.send(dp);
            }

            log("sent #"+packet+" with "+payloadBytes.length+" bytes \""+payloadStr+"\"");

            synchronized (this) {

                try {

                    wait(DELAY_BETWEEN_PACKETS_MS);
                }
                catch( InterruptedException ex) {

                    log("run exeption "+ex.toString());
                }
            }
        }

        mSocket.close();
        mSocket = null;
    }
    catch( Exception ex) {

        log("run exception "+ex.toString()+" stack "+Log.getStackTraceString(ex));
    }
}

private static void log( String message) {

    Log.d(TAG, message);
}

/**
 * Minimal, Complete, and Verifiable example for broadcasting UDP sockets, receive thread.
 * Loosely based on:
 *
 * https://jackiexie.com/2015/07/15/network-discovery-using-udp-broadcast-java/
 */
public static class BroadcastReceiver extends Thread {

    public static final String TAG = "BroadcastReceiver";

    public int totalReceived = 0;

    public BroadcastReceiver() {

        super( TAG );
    }

    @Override
    public void run() {

        final String methodName = "run";

        try {

            byte messageBytes[] = new byte[1500];

            DatagramPacket dp = new DatagramPacket(messageBytes, messageBytes.length);

            DatagramSocket mSocket = new DatagramSocket(TEST_PORT_NUMBER);
            mSocket.setSoTimeout(DELAY_BETWEEN_PACKETS_MS);
            mSocket.setBroadcast(true);

            while( totalReceived < TEST_COUNT ) {

                try {
                    // Get one UDP packet
                    mSocket.receive(dp);

                    if( dp.getLength() > 0 ) {

                        totalReceived++;

                        String payloadStr = new String(dp.getData());
                        log( "received #"+totalReceived+" : \""+payloadStr+"\"");
                    }
                }
                catch( Exception ex) {

                    log("receive exception "+ex.toString());
                }
            }

            mSocket.close();
            mSocket = null;
            log(methodName+" socket closed.");
        }
        catch( Exception ex) {

            log(methodName+" exception "+ex.toString());
        }
    }

    private static void log( String message) {

        Log.d(TAG, message);
    }
}

public static boolean unit_test() {

    try {

        BroadcastSender     sender = new BroadcastSender();
        sender.start();

        BroadcastReceiver   receiver = new BroadcastReceiver();
        receiver.start();
        log( "joining "+sender.getName());
        sender.join(TEST_TIME_MS);

        log( "joining "+receiver.getName());
        receiver.join(TEST_TIME_MS);

        boolean success = receiver.totalReceived >= TEST_COUNT;
        log( "unit test results="+success);
        return success;

    }
    catch( Exception ex ) {

        log( "unit test exception "+ex);
        return false;
    }
}
/*
 * Log output:
 *
D 2017-11-17 19:10:56.809 6228 BroadcastSender sent #0 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:57.313 6228 BroadcastSender sent #1 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:57.314 6228 BroadcastReceiver received #1 : "payload pid=6228"
D 2017-11-17 19:10:57.315 6228 BroadcastReceiver received #2 : "payload pid=6228"
D 2017-11-17 19:10:57.816 6228 BroadcastSender sent #2 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:57.817 6228 BroadcastReceiver received #3 : "payload pid=6228"
D 2017-11-17 19:10:57.818 6228 BroadcastReceiver received #4 : "payload pid=6228"
D 2017-11-17 19:10:58.319 6228 BroadcastReceiver received #5 : "payload pid=6228"
D 2017-11-17 19:10:58.319 6228 BroadcastSender sent #3 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:58.321 6228 BroadcastReceiver received #6 : "payload pid=6228"
D 2017-11-17 19:10:58.822 6228 BroadcastSender sent #4 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:58.822 6228 BroadcastReceiver received #7 : "payload pid=6228"
D 2017-11-17 19:10:58.823 6228 BroadcastReceiver received #8 : "payload pid=6228"
D 2017-11-17 19:10:59.325 6228 BroadcastReceiver receive exception java.net.SocketTimeoutException: Receive timed out
D 2017-11-17 19:10:59.326 6228 BroadcastReceiver received #9 : "payload pid=6228"
D 2017-11-17 19:10:59.327 6228 BroadcastReceiver received #10 : "payload pid=6228"
D 2017-11-17 19:10:59.325 6228 BroadcastSender sent #5 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:59.328 6228 BroadcastReceiver run socket closed.
D 2017-11-17 19:10:59.831 6228 BroadcastSender sent #6 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:00.333 6228 BroadcastSender sent #7 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:00.834 6228 BroadcastSender sent #8 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:01.336 6228 BroadcastSender sent #9 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:01.839 6228 BroadcastSender sent #10 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:02.341 6228 BroadcastSender sent #11 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:02.844 6228 BroadcastSender sent #12 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:03.346 6228 BroadcastSender sent #13 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:01.810 6228 BroadcastSender unit test results=true
 */
}
</code>```

Body:
My distributed application, with various hosts need to find local servers within the same LAN.

I had limited success detecting local servers using NsdManager, which is the way to go, but often, servers remain undetected. I am looking for a better solution, something more reliable.

Then I attempted to multicast UDP packets, which I have no problem detecting from within the same process. (My unit test uses both client and servers instances). That works fine. The same classes will not allow my clients to detect my servers running on the same device (client and servers are separate process applications).

Then I varied my approach using broadcast addresses, again, within the same process, unit tests are fine, but in two distinct process, no server found.

As I said, the code works fine within the same process, but they do not work when running in two distinct processes, or on two distinct client / server hosts within the same LAN.

Note: my LAN is a high end WiFi rooter, no special settings.

Anyone has any clue what might be the problem?

Note that my manifest includes these settings for both client and server applications:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Note that for my client to detect the server running on the same Host, I am already using TCP sockets, but I need to detect whatever server is in my LAN.

Body:
@Onik was quite right,

Making a Minimal, Complete, and Verifiable example allowed me to find the problem.

Here is the code for whoever may be interested:

package com.example;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;

import android.util.Log;

/**
 * Minimal, Complete, and Verifiable example for broadcasting UDP sockets, send thread.
 *
 * Loosely based on:
 *
 * https://jackiexie.com/2015/07/15/network-discovery-using-udp-broadcast-java/
 */
public class BroadcastSender extends Thread {

public static final String TAG = "BroadcastSender";

public static final int TEST_PORT_NUMBER            = 1234;
public static final int TEST_COUNT                  = 10;
public static final int DELAY_BETWEEN_PACKETS_MS    = 500;

public static final int TEST_TIME_MS    =   TEST_COUNT * DELAY_BETWEEN_PACKETS_MS;

private DatagramSocket mSocket;

public BroadcastSender() {

    super( TAG );
}

public static InetAddress getBroadcastAddress() {

    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

        while( interfaces.hasMoreElements() ) {

            NetworkInterface current = interfaces.nextElement();

            try {

                if( !current.isUp()  )
                    continue;

                if( current.isLoopback() )
                    continue;

                List<InterfaceAddress> addresses = current.getInterfaceAddresses();

                if( addresses == null ) {

                    log("getBroadcastAddress can not get addresses from "+current);
                    continue;
                }

                for( InterfaceAddress oneInterfaceAddress : addresses ) {

                    InetAddress bcast = oneInterfaceAddress.getBroadcast();

                    if( bcast != null )
                        return bcast;
                }
            }
            catch( Exception ex) {

                log( "getBroadcastAddress exception "+ex+" stack "+Log.getStackTraceString(ex) );
            }
        }
    }
    catch( Exception ex) {

        log( "getBroadcastAddress exception "+ex+" stack "+Log.getStackTraceString(ex) );
    }

    return null;
}

@Override
public void run() {

    try {

        mSocket = new DatagramSocket();
        mSocket.setBroadcast(true);

        InetAddress interfaceBroadcast = getBroadcastAddress();

        InetAddress broadcastAddr = InetAddress.getByName("255.255.255.255");

        String payloadStr   = "payload pid="+android.os.Process.myPid();
        byte payloadBytes[] = payloadStr.getBytes();

        for( int packet = 0; packet < TEST_COUNT; packet++) {

            // First send to 255.255.255.255
            DatagramPacket dp = new DatagramPacket(payloadBytes, payloadBytes.length, broadcastAddr, TEST_PORT_NUMBER);
            mSocket.send(dp);

            // Then send to whatever address we have for interfaceBroadcast
            if( interfaceBroadcast != null ) {

                dp = new DatagramPacket(payloadBytes, payloadBytes.length, interfaceBroadcast, TEST_PORT_NUMBER);
                mSocket.send(dp);
            }

            log("sent #"+packet+" with "+payloadBytes.length+" bytes \""+payloadStr+"\"");

            synchronized (this) {

                try {

                    wait(DELAY_BETWEEN_PACKETS_MS);
                }
                catch( InterruptedException ex) {

                    log("run exeption "+ex.toString());
                }
            }
        }

        mSocket.close();
        mSocket = null;
    }
    catch( Exception ex) {

        log("run exception "+ex.toString()+" stack "+Log.getStackTraceString(ex));
    }
}

private static void log( String message) {

    Log.d(TAG, message);
}

/**
 * Minimal, Complete, and Verifiable example for broadcasting UDP sockets, receive thread.
 * Loosely based on:
 *
 * https://jackiexie.com/2015/07/15/network-discovery-using-udp-broadcast-java/
 */
public static class BroadcastReceiver extends Thread {

    public static final String TAG = "BroadcastReceiver";

    public int totalReceived = 0;

    public BroadcastReceiver() {

        super( TAG );
    }

    @Override
    public void run() {

        final String methodName = "run";

        try {

            byte messageBytes[] = new byte[1500];

            DatagramPacket dp = new DatagramPacket(messageBytes, messageBytes.length);

            DatagramSocket mSocket = new DatagramSocket(TEST_PORT_NUMBER);
            mSocket.setSoTimeout(DELAY_BETWEEN_PACKETS_MS);
            mSocket.setBroadcast(true);

            while( totalReceived < TEST_COUNT ) {

                try {
                    // Get one UDP packet
                    mSocket.receive(dp);

                    if( dp.getLength() > 0 ) {

                        totalReceived++;

                        String payloadStr = new String(dp.getData());
                        log( "received #"+totalReceived+" : \""+payloadStr+"\"");
                    }
                }
                catch( Exception ex) {

                    log("receive exception "+ex.toString());
                }
            }

            mSocket.close();
            mSocket = null;
            log(methodName+" socket closed.");
        }
        catch( Exception ex) {

            log(methodName+" exception "+ex.toString());
        }
    }

    private static void log( String message) {

        Log.d(TAG, message);
    }
}

public static boolean unit_test() {

    try {

        BroadcastSender     sender = new BroadcastSender();
        sender.start();

        BroadcastReceiver   receiver = new BroadcastReceiver();
        receiver.start();
        log( "joining "+sender.getName());
        sender.join(TEST_TIME_MS);

        log( "joining "+receiver.getName());
        receiver.join(TEST_TIME_MS);

        boolean success = receiver.totalReceived >= TEST_COUNT;
        log( "unit test results="+success);
        return success;

    }
    catch( Exception ex ) {

        log( "unit test exception "+ex);
        return false;
    }
}
/*
 * Log output:
 *
D 2017-11-17 19:10:56.809 6228 BroadcastSender sent #0 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:57.313 6228 BroadcastSender sent #1 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:57.314 6228 BroadcastReceiver received #1 : "payload pid=6228"
D 2017-11-17 19:10:57.315 6228 BroadcastReceiver received #2 : "payload pid=6228"
D 2017-11-17 19:10:57.816 6228 BroadcastSender sent #2 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:57.817 6228 BroadcastReceiver received #3 : "payload pid=6228"
D 2017-11-17 19:10:57.818 6228 BroadcastReceiver received #4 : "payload pid=6228"
D 2017-11-17 19:10:58.319 6228 BroadcastReceiver received #5 : "payload pid=6228"
D 2017-11-17 19:10:58.319 6228 BroadcastSender sent #3 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:58.321 6228 BroadcastReceiver received #6 : "payload pid=6228"
D 2017-11-17 19:10:58.822 6228 BroadcastSender sent #4 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:58.822 6228 BroadcastReceiver received #7 : "payload pid=6228"
D 2017-11-17 19:10:58.823 6228 BroadcastReceiver received #8 : "payload pid=6228"
D 2017-11-17 19:10:59.325 6228 BroadcastReceiver receive exception java.net.SocketTimeoutException: Receive timed out
D 2017-11-17 19:10:59.326 6228 BroadcastReceiver received #9 : "payload pid=6228"
D 2017-11-17 19:10:59.327 6228 BroadcastReceiver received #10 : "payload pid=6228"
D 2017-11-17 19:10:59.325 6228 BroadcastSender sent #5 with 16 bytes "payload pid=6228"
D 2017-11-17 19:10:59.328 6228 BroadcastReceiver run socket closed.
D 2017-11-17 19:10:59.831 6228 BroadcastSender sent #6 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:00.333 6228 BroadcastSender sent #7 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:00.834 6228 BroadcastSender sent #8 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:01.336 6228 BroadcastSender sent #9 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:01.839 6228 BroadcastSender sent #10 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:02.341 6228 BroadcastSender sent #11 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:02.844 6228 BroadcastSender sent #12 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:03.346 6228 BroadcastSender sent #13 with 16 bytes "payload pid=6228"
D 2017-11-17 19:11:01.810 6228 BroadcastSender unit test results=true
 */
}


来源: stackexchange

问:
neo4j cypher: how to change the type of a relationship
I can't find a way to change a relationship type in Cypher. Is this operation possible at all? If not: what's the best way achieve this result?</p>

答:
I use the following when modifying it.</p>

```<code>match (from:Label1 { prop: 1 })-[r:RELATIONSHIP]->(to:Label2 { prop: 2 })
with from, r, to
create (from)-[:NEW_RELATIONSHIP]->(to)
with r
delete r
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use the following when modifying it.

match (from:Label1 { prop: 1 })-[r:RELATIONSHIP]->(to:Label2 { prop: 2 })
with from, r, to
create (from)-[:NEW_RELATIONSHIP]->(to)
with r
delete r


问:
Get custom events in schedule function azure app insights
I have to get all custom events that contain certain string on the name, with a scheduled Azure function.
Ideally I would like to send an email if a specific custom event have some wrong data.</p>

答:
The built in alerting features don't let you do this (run an arbitrary query and alert if some specific condition)

However, a lot of people are using Microsoft Flow, and there's some example scenarios there.

Other people have created azure functions to do similar.


问:
wait for ui data filter in selenium
In a application many fields are there and all the fields are having filters ( text box) . so once user will enter the value in any one of filter immediately UI data (UI table) will start getting refreshed.

I wanted to wait for data to be loaded in UI and then apply the another filter.

Is there any way to wait until data gets loaded without using Thread.sleep

答:
Without further details provided by you, all I can recommend for now is FluentWait. For example:</p>

```<code>final WebDriver driver = ...
new FluentWait<>(driver).withTimeout(30, SECONDS)
    .pollingEvery(1, SECONDS)
    .ignoring(NoSuchElementException.class)
    .until(
        webDvr -> !webDvr.findElements(By.xpath("//tr")).isEmpty()
    );
</code>```

Title: wait for ui data filter in selenium

Body:
Without further details provided by you, all I can recommend for now is FluentWait. For example:

final WebDriver driver = ...
new FluentWait<>(driver).withTimeout(30, SECONDS)
    .pollingEvery(1, SECONDS)
    .ignoring(NoSuchElementException.class)
    .until(
        webDvr -> !webDvr.findElements(By.xpath("//tr")).isEmpty()
    );


问:
Selenium-C#: SendKeys timing out & JS Executor throwing error
Trying to paste the data(which is quiet big) in the "Textarea1" control, below are the two methods I tried using, but first method tries pasting the data but throws timeout error sometime, and second one throws JS error. please help

```<code>public StringBuilder PasteDataIn_Tarea1
{
    set
    {
        //Method1
        Textarea1.Clear();
        Textarea1.SendKeys(value.ToString());

        //Method2
        IWebDriver driver;
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

        StringBuilder javascript = new StringBuilder();
        javascript.Append(string.Format("$('#Textarea1').text('{0}')", value));//value has my data which is quiet big, "Textarea1" is where I need to paste my data
        js.ExecuteScript(javascript.ToString()); // Js exector which should paste my data
    }
}
</code>```

Method2 throws below exception:

An exception of type 'System.InvalidOperationException' occurred in
  WebDriver.dll but was not handled in user code

Additional information: JavaScript error (UnexpectedJavaScriptError)

I prefer going to Method2 as the first one takes time to paste the data in the textarea.

答:
Try resetting the browser timeout:

```<code> ChromeOptions options = new ChromeOptions();
 options.AddArgument("--disable-extensions");
 ChromeDriverService svc = ChromeDriverService.CreateDefaultService();
 IWebDriver driver = new ChromeDriver(svc, options,TimeSpan.FromMinutes(5));
</code>```

The example above takes the command timeout to 5 minutes. I had a similar problem and this is what worked for me.

Body:
Trying to paste the data(which is quiet big) in the "Textarea1" control, below are the two methods I tried using, but first method tries pasting the data but throws timeout error sometime, and second one throws JS error. please help

public StringBuilder PasteDataIn_Tarea1
{
    set
    {
        //Method1
        Textarea1.Clear();
        Textarea1.SendKeys(value.ToString());

        //Method2
        IWebDriver driver;
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

        StringBuilder javascript = new StringBuilder();
        javascript.Append(string.Format("$('#Textarea1').text('{0}')", value));//value has my data which is quiet big, "Textarea1" is where I need to paste my data
        js.ExecuteScript(javascript.ToString()); // Js exector which should paste my data
    }
}

Method2 throws below exception:

An exception of type 'System.InvalidOperationException' occurred in
  WebDriver.dll but was not handled in user code

Additional information: JavaScript error (UnexpectedJavaScriptError)

I prefer going to Method2 as the first one takes time to paste the data in the textarea.

Body:
Try resetting the browser timeout:

 ChromeOptions options = new ChromeOptions();
 options.AddArgument("--disable-extensions");
 ChromeDriverService svc = ChromeDriverService.CreateDefaultService();
 IWebDriver driver = new ChromeDriver(svc, options,TimeSpan.FromMinutes(5));

The example above takes the command timeout to 5 minutes. I had a similar problem and this is what worked for me.


问:
How to delete dynamic allocated array in c++?
I got stuck with deleting an dynamically allocated array of int.
I've got a destructor, where I'm trying to use a loop for to delete all elements of array and finally delete it.
I have code on http://rextester.com/OTPPRQ8349
Thanks!</p>

```<code>class MyClass
{
   public:
   int _a;
   int* c;
   int fRozmiar;
   static int fIlosc;
   MyClass() //default constructor
   {
       _a=0;
       c = new int [9];
       for(int i = 0; i<=9; i++)
       {
           c[i] = 1;
       }
       fIlosc++;
   }
   MyClass(int a1, int c1) // parametrized constructor
   {
       _a=a1;
       c = new int [c1];
       for(int i = 0; i<=c1; i++)
       {
           c[i] = rand();
       }
       fIlosc++;
   }
   MyClass(const MyClass &p2) // copy constructor
   {
    _a =p2._a;
    c = p2.c;
    fRozmiar = p2.fRozmiar;
    fIlosc = fIlosc;
    fIlosc++;
   }
    ~MyClass(); // destructor

    static int getCount() {
         return fIlosc;
      }
};

//Initialize static member of class
int MyClass::fIlosc = 0;
MyClass::~MyClass()
{
        for(int i = 0; i<sizeof(c); ++i)
        {
            delete[] c[i];
        }
        delete[] c;
       fIlosc--;
}
int main()
{
}
</code>```

答:
There are several problems in the code.

First, that loop in the destructor must go. If you didn’t new it, don’t delete it.

Second, a loop through an array of N elements should be for (int i = 0; i < N; ++i). Note that the test is i < N, not i <= N. The loops as currently written go off the end of the array. That’s not good.

Third, the copy constructor copies the pointer. When the first object goes out of scope its destructor deletes the array; when the copy goes out of scope its destructor also deletes the array. Again, not good. The copy constructor has to make a copy of the array. In order to do that the class needs to also store the number of elements the array.

Body:
I got stuck with deleting an dynamically allocated array of int.
I've got a destructor, where I'm trying to use a loop for to delete all elements of array and finally delete it.
I have code on http://rextester.com/OTPPRQ8349
Thanks!

class MyClass
{
   public:
   int _a;
   int* c;
   int fRozmiar;
   static int fIlosc;
   MyClass() //default constructor
   {
       _a=0;
       c = new int [9];
       for(int i = 0; i<=9; i++)
       {
           c[i] = 1;
       }
       fIlosc++;
   }
   MyClass(int a1, int c1) // parametrized constructor
   {
       _a=a1;
       c = new int [c1];
       for(int i = 0; i<=c1; i++)
       {
           c[i] = rand();
       }
       fIlosc++;
   }
   MyClass(const MyClass &p2) // copy constructor
   {
    _a =p2._a;
    c = p2.c;
    fRozmiar = p2.fRozmiar;
    fIlosc = fIlosc;
    fIlosc++;
   }
    ~MyClass(); // destructor

    static int getCount() {
         return fIlosc;
      }
};

//Initialize static member of class
int MyClass::fIlosc = 0;
MyClass::~MyClass()
{
        for(int i = 0; i<sizeof(c); ++i)
        {
            delete[] c[i];
        }
        delete[] c;
       fIlosc--;
}
int main()
{
}


问:
Have you ever obtained a significant speedup by using boost::pool?
I've played with boost::pool a few times in places where it seemed to me I was seriously hammering the heap with a lot of object "churn".  Generally I've used boost::object_pool, or boost::pool_alloc as an STL template parameter.  However the result is invariably that performance is virtually unchanged, or significantly worsened.

I'm curious to hear of any success stories with it.

What sort of things should I look for in profiling output which might indicate boost::pool is likely to help ?

Is it just actually pretty hard to improve on good old malloc ?

答:
Memory pools are most effective imo for transaction style processing where you can allocate to the pool and then when the transaction is done, just dump it into oblivion. The real speed up isn't that each allocation is going to be much faster its that you will have near zero memory fragmentation in an extremely long running application.

In sort, it sounds like your applications do not warrant using memory pools

OwnerDisplayName: timday

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Hippiehunter


问:
update precedents of excel formulas
Is there any way to ask excel to update the precedents of a formula if we provide all details like....

suppose in cell D1 = "=SUM(B1:B20)"

now after data got exported then we know that data is B5:B50

then how can we ask excel to update the formula in cell D1 like "=Sum(B5:B50)

or we will have to string replacements.

答:
You could assign a name to the B1:B20 range: highlight B1:B20, the click on the name box (to the left of the formula bar) and type a name. You can then use that name in your SUM formula. When the data moves, update the location of the range on the Excel 2003 Insert menu, at Range > Define.

Alternatively, if the top-left cell stayed in the same place after the export (i.e. in cell B1), you could create an Excel list to represent the data: highlight B1:B20 and right-click on it, then click Create List. If you add rows to the bottom of a list, Excel automatically updates any formulae that refer to it.

Title: update precedents of excel formulas


问:
How to start a new line of an array of squares with CSS
I'm trying to create a 'grid' of squares using CSS. So far I've tried:

.square {
  display: block;
  float: left;
  border: 1px solid black;
  width: 50px;
  height: 50px;
  margin: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>

<div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div></code>```

However, this simply display 6 squares in a row. I'd like to have two rows of 3 squares each, however. Why do the encompassing divs not have the 'normal' behavior that they are displayed beneath each other?

答:
You can place the blocks inside of a containing div that has a fixed width. This will force the blocks to stack given their display type. For example, placing the width of the container to 400px makes enough space for only three blocks in a row. Frameworks use a system that is very useful for creating grids that are evenly dispersed throughout the container.

<!DOCTYPE html>

```

Body:
I'm trying to create a 'grid' of squares using CSS. So far I've tried:

.square {
  display: block;
  float: left;
  border: 1px solid black;
  width: 50px;
  height: 50px;
  margin: 30px;
}

However, this simply display 6 squares in a row. I'd like to have two rows of 3 squares each, however. Why do the encompassing divs not have the 'normal' behavior that they are displayed beneath each other?

Body:
You can place the blocks inside of a containing div that has a fixed width. This will force the blocks to stack given their display type. For example, placing the width of the container to 400px makes enough space for only three blocks in a row. Frameworks use a system that is very useful for creating grids that are evenly dispersed throughout the container.

<!DOCTYPE html>
<html>
<head>
<style>
.square {
    display: block;
    float: left;
    border: 1px solid black;
    width: 50px;
    height: 50px;
    margin: 30px;
  }
.container {
    width:400px;
  }
</style>
</head>
<body>

<!-- Place all of your blocks in a single container -->

<div class="container">

<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<!-- The container is not large enough to display all of the blocks in one row -->
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

</body>
</html>


问:
Walk a chain of objects recursively in functional style
A common looping pattern in imperative coding styles is to follow a chain of objects to find the end, e.g.:

```<code>private ThreadGroup rootOf(ThreadGroup leaf) {
  ThreadGroup rootGroup = leaf;
  ThreadGroup parentGroup;
  while ((parentGroup = rootGroup.getParent()) != null) {
    rootGroup = parentGroup;
  }
  return rootGroup;
}
</code>```

(from this answer)

I feel like there must be a standard functional pattern that's logically equivalent to this, but I'm not sure what it is. I've come up with the recursive method below using Vavr's Option:

```<code>private ThreadGroup rootOf(ThreadGroup leaf) {
  return Option.of(leaf.getParent()) // returns None for null
    .map(this::rootOf)
    .getOrElse(leaf);
}
</code>```

But it seems as though there ought to be a way to do it without explicit recursion, especially in a language like Java without tail call optimization (I'm imagining something vaguely analogous to foldLeft() but on an iteratively computed value stream, if that makes any sense?)

What's the standard functional approach here?

答:
Stream.iterate + filtering should do it:</p>

```<code>Stream.iterate(leaf, ThreadGroup::getParent)
    .filter(g -> g.getParent() == null)
    .findFirst().get();
</code>```

Body:
A common looping pattern in imperative coding styles is to follow a chain of objects to find the end, e.g.:

private ThreadGroup rootOf(ThreadGroup leaf) {
  ThreadGroup rootGroup = leaf;
  ThreadGroup parentGroup;
  while ((parentGroup = rootGroup.getParent()) != null) {
    rootGroup = parentGroup;
  }
  return rootGroup;
}

(from this answer)

I feel like there must be a standard functional pattern that's logically equivalent to this, but I'm not sure what it is. I've come up with the recursive method below using Vavr's Option:

private ThreadGroup rootOf(ThreadGroup leaf) {
  return Option.of(leaf.getParent()) // returns None for null
    .map(this::rootOf)
    .getOrElse(leaf);
}

But it seems as though there ought to be a way to do it without explicit recursion, especially in a language like Java without tail call optimization (I'm imagining something vaguely analogous to foldLeft() but on an iteratively computed value stream, if that makes any sense?)

What's the standard functional approach here?

Body:
Stream.iterate + filtering should do it:

Stream.iterate(leaf, ThreadGroup::getParent)
    .filter(g -> g.getParent() == null)
    .findFirst().get();


问:
Spinnaker "Create Application" menu doesn't load
I'm quite new to the Spinnaker and have to ask for some help I guess. Does anyone knows why it could be that I can't create any Application and just keep seeing this screen.
My installation is through Halyard 1.5.0 and Ubuntu 14.04.
We don't use any cloud provider but I did configure Docker and Kubernetes part

And here is the error I see in the /var/log/spinnaker/echo/echo.log:

```<code>2017-11-16 13:52:29.901  INFO 13877 --- [ofit-/pipelines] c.n.s.echo.services.Front50Service       : java.net.SocketTimeoutException: timeout
at okio.Okio$3.newTimeoutException(Okio.java:207)
at okio.AsyncTimeout.exit(AsyncTimeout.java:261)
at okio.AsyncTimeout$2.read(AsyncTimeout.java:215)
at okio.RealBufferedSource.indexOf(RealBufferedSource.java:306)
at okio.RealBufferedSource.indexOf(RealBufferedSource.java:300)
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196)
at com.squareup.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
at com.squareup.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127)
at com.squareup.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:739)
at com.squareup.okhttp.internal.http.HttpEngine.access$200(HttpEngine.java:87)
at com.squareup.okhttp.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:724)
at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:578)
at com.squareup.okhttp.Call.getResponse(Call.java:287)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:243)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:205)
at com.squareup.okhttp.Call.execute(Call.java:80)
at retrofit.client.OkClient.execute(OkClient.java:53)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:326)
at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
at retrofit.RestAdapter$RestHandler$1.invoke(RestAdapter.java:265)
at retrofit.RxSupport$2.run(RxSupport.java:55)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at retrofit.Platform$Base$2$1.run(Platform.java:94)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: Socket closed
at java.net.SocketInputStream.read(SocketInputStream.java:204)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at okio.Okio$2.read(Okio.java:139)
at okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
... 24 more

2017-11-16 13:52:29.901  INFO 13877 --- [ofit-/pipelines] c.n.s.echo.services.Front50Service       : ---- END ERROR
</code>```

答:
@grizzthedj

thanks again for recommendations. It doesn't seem, however, solved the issue. I wonder if it has something to do with my Docker Registry or Kubernetes.
Here is what I have in my .hal/config:

```<code>dockerRegistry:
  enabled: true
  accounts:
  - name: <hidden-name>
    requiredGroupMembership: []
    address: https://docker-registry.<hidden-name>.net/
    cacheIntervalSeconds: 30
    repositories:
    - hellopod
    - demoapp
  primaryAccount: <hidden-name>

kubernetes:
  enabled: true
  accounts:
  - name: <username>
    requiredGroupMembership: []
    dockerRegistries:
    - accountName: <hidden-name>
      namespaces: []
    context: sre-os1-dev
    namespaces:
    - spinnaker
    omitNamespaces: []
    kubeconfigFile: /home/<username>/.kube/config
</code>```

Body:
I'm quite new to the Spinnaker and have to ask for some help I guess. Does anyone knows why it could be that I can't create any Application and just keep seeing this screen.
My installation is through Halyard 1.5.0 and Ubuntu 14.04.
We don't use any cloud provider but I did configure Docker and Kubernetes part

And here is the error I see in the /var/log/spinnaker/echo/echo.log:

2017-11-16 13:52:29.901  INFO 13877 --- [ofit-/pipelines] c.n.s.echo.services.Front50Service       : java.net.SocketTimeoutException: timeout
at okio.Okio$3.newTimeoutException(Okio.java:207)
at okio.AsyncTimeout.exit(AsyncTimeout.java:261)
at okio.AsyncTimeout$2.read(AsyncTimeout.java:215)
at okio.RealBufferedSource.indexOf(RealBufferedSource.java:306)
at okio.RealBufferedSource.indexOf(RealBufferedSource.java:300)
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196)
at com.squareup.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
at com.squareup.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127)
at com.squareup.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:739)
at com.squareup.okhttp.internal.http.HttpEngine.access$200(HttpEngine.java:87)
at com.squareup.okhttp.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:724)
at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:578)
at com.squareup.okhttp.Call.getResponse(Call.java:287)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:243)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:205)
at com.squareup.okhttp.Call.execute(Call.java:80)
at retrofit.client.OkClient.execute(OkClient.java:53)
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:326)
at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
at retrofit.RestAdapter$RestHandler$1.invoke(RestAdapter.java:265)
at retrofit.RxSupport$2.run(RxSupport.java:55)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at retrofit.Platform$Base$2$1.run(Platform.java:94)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: Socket closed
at java.net.SocketInputStream.read(SocketInputStream.java:204)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at okio.Okio$2.read(Okio.java:139)
at okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
... 24 more

2017-11-16 13:52:29.901  INFO 13877 --- [ofit-/pipelines] c.n.s.echo.services.Front50Service       : ---- END ERROR

Body:
@grizzthedj

thanks again for recommendations. It doesn't seem, however, solved the issue. I wonder if it has something to do with my Docker Registry or Kubernetes.
Here is what I have in my .hal/config:

dockerRegistry:
  enabled: true
  accounts:
  - name: <hidden-name>
    requiredGroupMembership: []
    address: https://docker-registry.<hidden-name>.net/
    cacheIntervalSeconds: 30
    repositories:
    - hellopod
    - demoapp
  primaryAccount: <hidden-name>

kubernetes:
  enabled: true
  accounts:
  - name: <username>
    requiredGroupMembership: []
    dockerRegistries:
    - accountName: <hidden-name>
      namespaces: []
    context: sre-os1-dev
    namespaces:
    - spinnaker
    omitNamespaces: []
    kubeconfigFile: /home/<username>/.kube/config


问:
How to get selected value in data-tagger attribute in Javascript?
I have a dropdown list field called "Bug category" which includes four options:
software, hardware, tools, documentation.
My HTML:

```<code><div class="form-field string  required  request_custom_fields_25376063" >
      <label for="request_custom_fields_25376063">Bug Category</label>
      <input type="hidden" name="request[custom_fields][25376063]" id="request_custom_fields_25376063" autocomplete="off" data-tagger="[{"label":"-","value":""},{"label":"Software","value":"software"},{"label":"Hardware","value":"hardware"},{"label":"Tools","value":"bug_tools"},{"label":"Documentation","value":"bug_documentation"}]" />

        <p>Which type of bugs do you want to report?</p>

    </div>
</code>```

The data-tagger attribute includes the selection values:

```<code>data-tagger="[{"label":"-","value":""},{"label":"Software","value":"software"},{"label":"Hardware","value":"hardware"},{"label":"Tools","value":"bug_tools"},{"label":"Documentation","value":"bug_documentation"}]"
</code>```

I want to change the form based on different selection of the bug category field. How can I get the value of selected option in the data-tagger attribute?

My Javascript code:

```<code>alert("value is:"+ $(this).attr('data-tagger').val()); // doesn't work
alert("value is:"+ $(this).attr('data-tagger')); //shows "Undefined" when I select option
</code>```

Edited:

```<code> var bug_category = $('input#request_custom_fields_25376063').parent();

 bug_category.on('change',function(){
    alert("value is:"+  $(this).find(':selected').data('tagger')); // return null
    });
</code>```

More script code:

25375983 - each kind of number represent a field in the form.

This code is generated from an app, which allows me show different fields based on different selection of "bug_category" field.

```<code><script>var cfaRules = [
{"fieldType":"tagger","field":25376063,"value":"bug_documentation","select":[25375983,24342549,24399485,25376023,25454706,25454746,25454766,25454806,25454826,25375963],"formId":240243,"requireds":[25375963,25454706,25454766]},{"fieldType":"tagger","field":25376063,"value":"bug_tools","select":[25454746,25454766,25454806,25454826,25454706,25376023,25375983,25375963,24399485,24342549],"formId":240243,"requireds":[25375983,25454706,25454746,25454766]},{"fieldType":"tagger","field":25376063,"value":"hardware","select":[24342549,24399485,25375963,25375983,25376023,25454706,25454746,25454766,25454806,25454826],"formId":240243,"requireds":[24342549,24399485,25454706,25454766]},{"fieldType":"tagger","field":25376063,"value":"software","select":[25454706,24342549,24399485,25375963,25375983,25376023,25454746,25454806,25454766,25454826],"formId":240243,"requireds":[24399485,25376023,25454706,25454766,25454826]}]</script>
</code>```

答:
Use .data() to get the value of data tags

```<code>alert($(this).data('tagger'));
</code>```

UPDATE

If I understand the real problem correctly, what you want should be something like this

// Get the categories on div's hidden input using .data()
var categories = $('div').find('input').data('tagger');

// Append each categories to the select tag
// e.g. <option value="value> label </option>
$.each(categories, function(key,value){
    $('#select_bug').append('<option value="' + value.value + '">' + value.label + '</option>');
});

// declare select tag to bug_category variable
var bug_category = $('#select_bug');

// Alert the value when selected option is changed
bug_category.on('change',function(){
    alert("value is : " +  $(this).find(':selected').val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-field string  required  request_custom_fields_25376063" >
    <label for="request_custom_fields_25376063">Bug Category</label>
    <input
        type="hidden"
        name="request[custom_fields][25376063]"
        id="request_custom_fields_25376063"
        autocomplete="off"
        data-tagger="[{"label":"-","value":""},{"label":"Software","value":"software"},{"label":"Hardware","value":"hardware"},{"label":"Tools","value":"bug_tools"},{"label":"Documentation","value":"bug_documentation"}]" />

    <p>Which type of bugs do you want to report?</p>

    <!-- Add select tags to insert dropdown options -->
    <select id="select_bug">
    </select>
    <!-- or if you already have this select tag, use yours -->

    <input type="submit" value="Submit">

</div>

<script src="//code.jquery.com/jquery-3.2.1.min.js"></script></code>```

Body:
I have a dropdown list field called "Bug category" which includes four options:
software, hardware, tools, documentation.
My HTML:

      Bug Category
      <input type="hidden" name="request[custom_fields][25376063]" id="request_custom_fields_25376063" autocomplete="off" data-tagger="[{"label":"-","value":""},{"label":"Software","value":"software"},{"label":"Hardware","value":"hardware"},{"label":"Tools","value":"bug_tools"},{"label":"Documentation","value":"bug_documentation"}]" />

Which type of bugs do you want to report?

The data-tagger attribute includes the selection values:

data-tagger="[{"label":"-","value":""},{"label":"Software","value":"software"},{"label":"Hardware","value":"hardware"},{"label":"Tools","value":"bug_tools"},{"label":"Documentation","value":"bug_documentation"}]"

I want to change the form based on different selection of the bug category field. How can I get the value of selected option in the data-tagger attribute?

My Javascript code:

alert("value is:"+ $(this).attr('data-tagger').val()); // doesn't work
alert("value is:"+ $(this).attr('data-tagger')); //shows "Undefined" when I select option

Edited:

 var bug_category = $('input#request_custom_fields_25376063').parent();

 bug_category.on('change',function(){
    alert("value is:"+  $(this).find(':selected').data('tagger')); // return null
    });

More script code:

25375983 - each kind of number represent a field in the form.

This code is generated from an app, which allows me show different fields based on different selection of "bug_category" field.

Body:
Use .data() to get the value of data tags

alert($(this).data('tagger'));

UPDATE

If I understand the real problem correctly, what you want should be something like this

// Get the categories on div's hidden input using .data()
var categories = $('div').find('input').data('tagger');

// Append each categories to the select tag
// e.g. <option value="value> label </option>
$.each(categories, function(key,value){
    $('#select_bug').append('<option value="' + value.value + '">' + value.label + '</option>');
});

// declare select tag to bug_category variable
var bug_category = $('#select_bug');

// Alert the value when selected option is changed
bug_category.on('change',function(){
    alert("value is : " +  $(this).find(':selected').val());
});

<div class="form-field string  required  request_custom_fields_25376063" >
    <label for="request_custom_fields_25376063">Bug Category</label>
    <input
        type="hidden"
        name="request[custom_fields][25376063]"
        id="request_custom_fields_25376063"
        autocomplete="off"
        data-tagger="[{&quot;label&quot;:&quot;-&quot;,&quot;value&quot;:&quot;&quot;},{&quot;label&quot;:&quot;Software&quot;,&quot;value&quot;:&quot;software&quot;},{&quot;label&quot;:&quot;Hardware&quot;,&quot;value&quot;:&quot;hardware&quot;},{&quot;label&quot;:&quot;Tools&quot;,&quot;value&quot;:&quot;bug_tools&quot;},{&quot;label&quot;:&quot;Documentation&quot;,&quot;value&quot;:&quot;bug_documentation&quot;}]" />

    <p>Which type of bugs do you want to report?</p>

    <!-- Add select tags to insert dropdown options -->
    <select id="select_bug">
    </select>
    <!-- or if you already have this select tag, use yours -->

    <input type="submit" value="Submit">

</div>

<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>


问:
Waze Deep Links
I'm developing an App using Xamarin Forms (cross platform), and im trying to open Waze app from my app, passing latitude and longitude.

It opens Waze very well, but Waze just open, it didn't try to find the address or the latitude/longitude that I passed.

```<code>string stringUri = @"waze://ul?ll=" + client.Latitude + ","  + client.Longitude + "&navigate=yes";
Intent intent = new Intent(Intent.ActionView);
intent.AddFlags(ActivityFlags.NewTask);
intent.SetData(Android.Net.Uri.Parse(stringUri));
Android.App.Application.Context.StartActivity(intent);
</code>```

Some Ideas on how I make it work?

---EDIT---

Finally, it WORKED, using the idea from @SushiHangover, i managed to achieve the desired result. The final code is here:

```<code>public static Task < bool > OpenWazeAndroid(decimal latitude, decimal longitude, string address) {
    var lat = latitude.ToString().Replace(",", ".");
    var longi = longitude.ToString().Replace(",", ".");
    const string wazePrefix = "waze://";
    Android.Content.Intent intent = new Android.Content.Intent(Android.Content.Intent.ActionView, Android.Net.Uri.Parse(wazePrefix));
    string wazeURL = ("https://waze.com/ul?q=" + address + "&ll=" + lat + "," + longi + "&z=8&navigate=yes");
    wazeURL = wazeURL.Replace(" ", "%20");
    var resolveInfo = Android.App.Application.Context.PackageManager.ResolveActivi ty(intent, 0);
    Android.Net.Uri wazeUri;
    if (resolveInfo != null) {
        wazeUri = Android.Net.Uri.Parse(wazeURL);
    } else {
        wazeUri = Android.Net.Uri.Parse("market://details?id=com.waze");
    }
    intent.AddFlags(Android.Content.ActivityFlags.NewTask);
    intent.SetData(wazeUri);
    Android.App.Application.Context.StartActivity(intent);

    return Task.FromResult(true);
}
</code>```

答:
The direct app link on Android does not respect the link properties/options (Waze iOS does), so use the web base url (https://waze.com) to properly open Waze with the deep link options.

Example:

```<code>const string wazeAppURL = "waze://";
var wazeURL = $"https://waze.com/ul?ll={loc[0]},{loc[1]}&navigate=yes";
var intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(wazeAppURL));
var resolveInfo = PackageManager.ResolveActivity(intent, 0);
var wazeUri = resolveInfo != null ? Android.Net.Uri.Parse(wazeURL) : Android.Net.Uri.Parse("market://details?id=com.waze");
intent.SetData(wazeUri);
StartActivity(intent);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Waze Deep Links

Body:
I'm developing an App using Xamarin Forms (cross platform), and im trying to open Waze app from my app, passing latitude and longitude.

It opens Waze very well, but Waze just open, it didn't try to find the address or the latitude/longitude that I passed.

string stringUri = @"waze://ul?ll=" + client.Latitude + ","  + client.Longitude + "&navigate=yes";
Intent intent = new Intent(Intent.ActionView);
intent.AddFlags(ActivityFlags.NewTask);
intent.SetData(Android.Net.Uri.Parse(stringUri));
Android.App.Application.Context.StartActivity(intent);

Some Ideas on how I make it work?

---EDIT---

Finally, it WORKED, using the idea from @SushiHangover, i managed to achieve the desired result. The final code is here:

public static Task < bool > OpenWazeAndroid(decimal latitude, decimal longitude, string address) {
    var lat = latitude.ToString().Replace(",", ".");
    var longi = longitude.ToString().Replace(",", ".");
    const string wazePrefix = "waze://";
    Android.Content.Intent intent = new Android.Content.Intent(Android.Content.Intent.ActionView, Android.Net.Uri.Parse(wazePrefix));
    string wazeURL = ("https://waze.com/ul?q=" + address + "&ll=" + lat + "," + longi + "&z=8&navigate=yes");
    wazeURL = wazeURL.Replace(" ", "%20");
    var resolveInfo = Android.App.Application.Context.PackageManager.ResolveActivi ty(intent, 0);
    Android.Net.Uri wazeUri;
    if (resolveInfo != null) {
        wazeUri = Android.Net.Uri.Parse(wazeURL);
    } else {
        wazeUri = Android.Net.Uri.Parse("market://details?id=com.waze");
    }
    intent.AddFlags(Android.Content.ActivityFlags.NewTask);
    intent.SetData(wazeUri);
    Android.App.Application.Context.StartActivity(intent);

    return Task.FromResult(true);
}

Body:
The direct app link on Android does not respect the link properties/options (Waze iOS does), so use the web base url (https://waze.com) to properly open Waze with the deep link options.

Example:

const string wazeAppURL = "waze://";
var wazeURL = $"https://waze.com/ul?ll={loc[0]},{loc[1]}&navigate=yes";
var intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(wazeAppURL));
var resolveInfo = PackageManager.ResolveActivity(intent, 0);
var wazeUri = resolveInfo != null ? Android.Net.Uri.Parse(wazeURL) : Android.Net.Uri.Parse("market://details?id=com.waze");
intent.SetData(wazeUri);
StartActivity(intent);


问:
Set a coupon description in WooCommerce
My site dynamically gives users coupons if they have been a member for a long enough time. When I am generating the coupon I want to assign a description to the coupon. However, I seem to be unable to assign a description by updating the post's metadata with the key description as the docs suggest I should be able to.

Currently I am trying to assign the description like so:

```<code>$percent = 25;//DISCOUNT PERCENTAGE
$coupon_code = 'testcoupon'; //Coupon Code
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product

//ASSIGN COUPON AND DISCOUNT PERCENTAGE

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );//SET DICOUNT TO BE PERCENTAGE BASED
update_post_meta( $new_coupon_id, 'coupon_amount', $percent );//SET DISCOUNT PERCENTAGE
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );//ONLY ONE CUPON BE USED AT A TIME
update_post_meta( $new_coupon_id, 'product_ids', '' ); //INCLUDE ALL PRODUCTS
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );//DO NOT EXCLUDE ANY PRODUCTS
update_post_meta( $new_coupon_id, 'usage_limit', '1' );//ONE TIME USE
update_post_meta( $new_coupon_id, 'expiry_date', strtotime("+6 months") );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );//DO NOT GIVE FREE SHIPPING

//ASSIGN DESCRIPTION TO COUPON
update_post_meta( $new_coupon_id, 'description', 'This is an example description used for the example coupon');
</code>```

How else should I go about adding a description?

答:
The coupon description has to be added in the post data as post_excerpt key (but not in post meta data)…

So your code should be instead:

```<code>$percent = 25;//DISCOUNT PERCENTAGE
$coupon_code = 'testcoupon'; //Coupon Code
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
$description = __('This is an example description used for the example coupon');

//ASSIGN COUPON AND DISCOUNT PERCENTAGE

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_excerpt' => $description, // <== HERE goes the description
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

## … / … and so on
</code>```

Or instead, since WooCommerce 3, you can use any related method on a WC_Coupon Object. In your case you will use setter methods to set the data (as getter methods are used to get the data on an existing coupon object):

```<code>// Get an instance of the WC_Coupon object
$wc_coupon = new WC_Coupon($coupon_code);

// Some data
$percent = 25; // DISCOUNT PERCENTAGE
$coupon_code = 'testcoupon'; // Coupon Code
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
$description = __('This is an example description used for the example coupon'); // Description

// Set the coupon data
$wc_coupon->set_code($coupon_code);
$wc_coupon->set_description($description);
$wc_coupon->set_discount_type($discount_type);
$wc_coupon->set_amount( floatval($percent) );
$wc_coupon->set_individual_use( true );
$wc_coupon->set_usage_limit( 1 );
$wc_coupon->set_date_expires( strtotime("+6 months") );
## $wc_coupon->apply_before_tax( true ); // ==> Deprecated in WC 3+ with no replacement alternatie
$wc_coupon->set_free_shipping( false );

// Test raw data output before save
var_dump($wc_coupon);

// SAVE the coupon
$wc_coupon->save();
</code>```

Title: Set a coupon description in WooCommerce

Body:
My site dynamically gives users coupons if they have been a member for a long enough time. When I am generating the coupon I want to assign a description to the coupon. However, I seem to be unable to assign a description by updating the post's metadata with the key description as the docs suggest I should be able to.

Currently I am trying to assign the description like so:

$percent = 25;//DISCOUNT PERCENTAGE
$coupon_code = 'testcoupon'; //Coupon Code
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product

//ASSIGN COUPON AND DISCOUNT PERCENTAGE

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );//SET DICOUNT TO BE PERCENTAGE BASED
update_post_meta( $new_coupon_id, 'coupon_amount', $percent );//SET DISCOUNT PERCENTAGE
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );//ONLY ONE CUPON BE USED AT A TIME
update_post_meta( $new_coupon_id, 'product_ids', '' ); //INCLUDE ALL PRODUCTS
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );//DO NOT EXCLUDE ANY PRODUCTS
update_post_meta( $new_coupon_id, 'usage_limit', '1' );//ONE TIME USE
update_post_meta( $new_coupon_id, 'expiry_date', strtotime("+6 months") );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );//DO NOT GIVE FREE SHIPPING

//ASSIGN DESCRIPTION TO COUPON
update_post_meta( $new_coupon_id, 'description', 'This is an example description used for the example coupon');

How else should I go about adding a description?

Body:
The coupon description has to be added in the post data as post_excerpt key (but not in post meta data)…

So your code should be instead:

$percent = 25;//DISCOUNT PERCENTAGE
$coupon_code = 'testcoupon'; //Coupon Code
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
$description = __('This is an example description used for the example coupon');

//ASSIGN COUPON AND DISCOUNT PERCENTAGE

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_excerpt' => $description, // <== HERE goes the description
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

## … / … and so on

Or instead, since WooCommerce 3, you can use any related method on a WC_Coupon Object. In your case you will use setter methods to set the data (as getter methods are used to get the data on an existing coupon object):

// Get an instance of the WC_Coupon object
$wc_coupon = new WC_Coupon($coupon_code);

// Some data
$percent = 25; // DISCOUNT PERCENTAGE
$coupon_code = 'testcoupon'; // Coupon Code
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
$description = __('This is an example description used for the example coupon'); // Description

// Set the coupon data
$wc_coupon->set_code($coupon_code);
$wc_coupon->set_description($description);
$wc_coupon->set_discount_type($discount_type);
$wc_coupon->set_amount( floatval($percent) );
$wc_coupon->set_individual_use( true );
$wc_coupon->set_usage_limit( 1 );
$wc_coupon->set_date_expires( strtotime("+6 months") );
## $wc_coupon->apply_before_tax( true ); // ==> Deprecated in WC 3+ with no replacement alternatie
$wc_coupon->set_free_shipping( false );

// Test raw data output before save
var_dump($wc_coupon);

// SAVE the coupon
$wc_coupon->save();


答:
Use jquery's .data() method because it will also auto-magically parse the value to the correct type.

var value = $('input').data('tagger');
console.log(typeof value);
console.log(value);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden"
   name="request[custom_fields][25376063]"
   id="request_custom_fields_25376063"
   autocomplete="off"
   data-tagger="[{"label":"-","value":""},{"label":"Software","value":"software"},{"label":"Hardware","value":"hardware"},{"label":"Tools","value":"bug_tools"},{"label":"Documentation","value":"bug_documentation"}]" /></code>```

Regarding your example code.

```<code>var bug_category = $('input#request_custom_fields_25376063').parent();
</code>```

Makes literally no sense because the .parent() of your input field, the div cannot have a change event on it, so it cannot fire.

```<code>$(this).find(':selected').data('tagger')
</code>```

If somehow this code was to fire, based on your example, find would return Zero elements because there are no elements that support :selected, thus .data() will always return undefined.

Title: How to get selected value in data-tagger attribute in Javascript?

Body:
Use jquery's .data() method because it will also auto-magically parse the value to the correct type.

var value = $('input').data('tagger');
console.log(typeof value);
console.log(value);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden"
   name="request[custom_fields][25376063]"
   id="request_custom_fields_25376063"
   autocomplete="off"
   data-tagger="[{&quot;label&quot;:&quot;-&quot;,&quot;value&quot;:&quot;&quot;},{&quot;label&quot;:&quot;Software&quot;,&quot;value&quot;:&quot;software&quot;},{&quot;label&quot;:&quot;Hardware&quot;,&quot;value&quot;:&quot;hardware&quot;},{&quot;label&quot;:&quot;Tools&quot;,&quot;value&quot;:&quot;bug_tools&quot;},{&quot;label&quot;:&quot;Documentation&quot;,&quot;value&quot;:&quot;bug_documentation&quot;}]" />

Regarding your example code.

var bug_category = $('input#request_custom_fields_25376063').parent();

Makes literally no sense because the .parent() of your input field, the div cannot have a change event on it, so it cannot fire.

$(this).find(':selected').data('tagger')

If somehow this code was to fire, based on your example, find would return Zero elements because there are no elements that support :selected, thus .data() will always return undefined.


问:
Android Notification bar buttons become not responsive
I am working on an app where I have a service that should always run in the background. This service is responsible for a Notification bar that should always be visible. The notification bar has 2 buttons, where the 1st one is for grabbing some data and storing it and the 2nd one should open an activity that will show all the data. I encountered a problem where when I close the application and then press the notification button that starts an activity after that activity starts, my notification buttons stop responding. Note that both buttons work fine before the point where the 2nd button click starts the activity.

Here is a template code for my notification service and for notification bar button handler

service that handles the Notification bar

```<code>   public class NotificationBarService extends Service {

        private int notificationID;

        @Override
        public IBinder onBind(Intent intent){
            return null;
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId){

            notificationID = new Random().nextInt();

            RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
            contentView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
            contentView.setTextViewText(R.id.title, "Custom notification");
            contentView.setTextViewText(R.id.text, "This is a custom layout");

            //Handle the button for showing bookmarks on custom notification
            Intent buttonsIntent2 = new Intent(this, NotificationBarButtonActivityHandler.class);
            buttonsIntent2.putExtra(PENDING_ACTION, SHOW_BOOKMARKS);
            contentView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton, PendingIntent.getActivity(this, 0, buttonsIntent2, 0));

            //Handle the button for adding bookmark on custom notification
            Intent buttonsIntent = new Intent(this, NotificationBarButtonActivityHandler.class);
            buttonsIntent.putExtra(PENDING_ACTION, REGISTER_BOOKMARK);
            contentView.setOnClickPendingIntent(R.id.notificationBarAddBookmarkFromChromeButton, PendingIntent.getActivity(this, 1, buttonsIntent, 0));

            RemoteViews notificationView = new RemoteViews(getPackageName(),
                    R.layout.custom_notification);

            Intent switchIntent = new Intent(this, NotificationBarService.class);
            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0,
                    switchIntent, 0);

            notificationView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton,
                    pendingSwitchIntent);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setContent(contentView)
                    .setSmallIcon(R.drawable.notification_small_icon)
                    .setOngoing(true);

            Notification notification = mBuilder.build();

            startForeground(notificationID, notification);

            return START_STICKY;
        }

        @Override
        public void onDestroy(){
            super.onDestroy();

            stopForeground(true);

        }
    }
</code>```

Class that handles the button press on Notification bar

```<code>public class NotificationBarButtonActivityHandler extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String action = (String) getIntent().getExtras().get(NotificationBarService.PENDING_ACTION);

        if (action != null) {
            if (action.equals(NotificationBarService.REGISTER_BOOKMARK)){
                CustomLogger.log("---------------- BUTTON FOR COLLECT DATA WAS PRESSED!!!");

                //Does something here
            }
            else if(action.equals(NotificationBarService.SHOW_BOOKMARKS)){
                CustomLogger.log("---------------- BUTTON FOR SHOW DATA WAS PRESSSED!!!");

                //Notification bar buttons start not responding right after
                //this is executed. Note that this problem only occurs if I close the app
                //and press the notification button to execute this code.
                //Otherwise this works just fine.
                Intent intent2;
                intent2 = new Intent(this, BookmarkDisplayActivity.class);
                startActivity(intent2);
            }
        }

        finish();
    }
}
</code>```

So basically if I close the application and remove the code that starts the activity, both buttons work as expected but as soon as I start the activity, both buttons stop working.

答:
Ok, I finally solved the issue that I was having with changing the way that I handle button presses. This is what I got now and it works as expected.

In NotificationBarService this is how I handle the listeners for the buttons

```<code>Intent addBookmarkIntent = new Intent(this, NotificationBarButtonListener.class);
            addBookmarkIntent.setAction(ADD_BOOKMARK_ACTION);
            PendingIntent pendingAddBookmarkIntent = PendingIntent.getBroadcast(this, 0, addBookmarkIntent, 0);
            contentView.setOnClickPendingIntent(R.id.notificationBarAddBookmarkFromChromeButton, pendingAddBookmarkIntent);

            Intent showBookmarkIntent = new Intent(this, NotificationBarButtonListener.class);
            showBookmarkIntent.setAction(SHOW_BOOKMARK_ACTION);
            PendingIntent pendingShowBookmarkIntent = PendingIntent.getBroadcast(this, 0, showBookmarkIntent, 0);
            contentView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton, pendingShowBookmarkIntent);
</code>```

and then I receive a broadcast even and handle it like this

```<code>public static class NotificationBarButtonListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            final String action = intent.getAction();
            if(action.equals(ADD_BOOKMARK_ACTION)){
                CustomLogger.log("---------------- BUTTON FOR REGISTER BOOKMARK WAS PRESSED!!! ");

            }
            else if(action.equals(SHOW_BOOKMARK_ACTION)){
                CustomLogger.log("---------------- BUTTON FOR SHOW BOOKMARK WAS PRESSSED!!!");

            }

        }
    }
</code>```

Note that this required me to add the following line to my manifest

```<code><receiver android:name=".NotificationBarService$NotificationBarButtonListener"/>
</code>```

Body:
I am working on an app where I have a service that should always run in the background. This service is responsible for a Notification bar that should always be visible. The notification bar has 2 buttons, where the 1st one is for grabbing some data and storing it and the 2nd one should open an activity that will show all the data. I encountered a problem where when I close the application and then press the notification button that starts an activity after that activity starts, my notification buttons stop responding. Note that both buttons work fine before the point where the 2nd button click starts the activity.

Here is a template code for my notification service and for notification bar button handler

service that handles the Notification bar

   public class NotificationBarService extends Service {

        private int notificationID;

        @Override
        public IBinder onBind(Intent intent){
            return null;
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId){

            notificationID = new Random().nextInt();

            RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
            contentView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
            contentView.setTextViewText(R.id.title, "Custom notification");
            contentView.setTextViewText(R.id.text, "This is a custom layout");

            //Handle the button for showing bookmarks on custom notification
            Intent buttonsIntent2 = new Intent(this, NotificationBarButtonActivityHandler.class);
            buttonsIntent2.putExtra(PENDING_ACTION, SHOW_BOOKMARKS);
            contentView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton, PendingIntent.getActivity(this, 0, buttonsIntent2, 0));

            //Handle the button for adding bookmark on custom notification
            Intent buttonsIntent = new Intent(this, NotificationBarButtonActivityHandler.class);
            buttonsIntent.putExtra(PENDING_ACTION, REGISTER_BOOKMARK);
            contentView.setOnClickPendingIntent(R.id.notificationBarAddBookmarkFromChromeButton, PendingIntent.getActivity(this, 1, buttonsIntent, 0));

            RemoteViews notificationView = new RemoteViews(getPackageName(),
                    R.layout.custom_notification);

            Intent switchIntent = new Intent(this, NotificationBarService.class);
            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0,
                    switchIntent, 0);

            notificationView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton,
                    pendingSwitchIntent);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setContent(contentView)
                    .setSmallIcon(R.drawable.notification_small_icon)
                    .setOngoing(true);

            Notification notification = mBuilder.build();

            startForeground(notificationID, notification);

            return START_STICKY;
        }

        @Override
        public void onDestroy(){
            super.onDestroy();

            stopForeground(true);

        }
    }

Class that handles the button press on Notification bar

public class NotificationBarButtonActivityHandler extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String action = (String) getIntent().getExtras().get(NotificationBarService.PENDING_ACTION);

        if (action != null) {
            if (action.equals(NotificationBarService.REGISTER_BOOKMARK)){
                CustomLogger.log("---------------- BUTTON FOR COLLECT DATA WAS PRESSED!!!");

                //Does something here
            }
            else if(action.equals(NotificationBarService.SHOW_BOOKMARKS)){
                CustomLogger.log("---------------- BUTTON FOR SHOW DATA WAS PRESSSED!!!");

                //Notification bar buttons start not responding right after
                //this is executed. Note that this problem only occurs if I close the app
                //and press the notification button to execute this code.
                //Otherwise this works just fine.
                Intent intent2;
                intent2 = new Intent(this, BookmarkDisplayActivity.class);
                startActivity(intent2);
            }
        }

        finish();
    }
}

So basically if I close the application and remove the code that starts the activity, both buttons work as expected but as soon as I start the activity, both buttons stop working.

Body:
Ok, I finally solved the issue that I was having with changing the way that I handle button presses. This is what I got now and it works as expected.

In NotificationBarService this is how I handle the listeners for the buttons

Intent addBookmarkIntent = new Intent(this, NotificationBarButtonListener.class);
            addBookmarkIntent.setAction(ADD_BOOKMARK_ACTION);
            PendingIntent pendingAddBookmarkIntent = PendingIntent.getBroadcast(this, 0, addBookmarkIntent, 0);
            contentView.setOnClickPendingIntent(R.id.notificationBarAddBookmarkFromChromeButton, pendingAddBookmarkIntent);

            Intent showBookmarkIntent = new Intent(this, NotificationBarButtonListener.class);
            showBookmarkIntent.setAction(SHOW_BOOKMARK_ACTION);
            PendingIntent pendingShowBookmarkIntent = PendingIntent.getBroadcast(this, 0, showBookmarkIntent, 0);
            contentView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton, pendingShowBookmarkIntent);

and then I receive a broadcast even and handle it like this

public static class NotificationBarButtonListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            final String action = intent.getAction();
            if(action.equals(ADD_BOOKMARK_ACTION)){
                CustomLogger.log("---------------- BUTTON FOR REGISTER BOOKMARK WAS PRESSED!!! ");

            }
            else if(action.equals(SHOW_BOOKMARK_ACTION)){
                CustomLogger.log("---------------- BUTTON FOR SHOW BOOKMARK WAS PRESSSED!!!");

            }

        }
    }

Note that this required me to add the following line to my manifest

<receiver android:name=".NotificationBarService$NotificationBarButtonListener"/>


问:
Why does my push notification keep repeating irregularly?
A push notification set up using alarm manager and pending intent is displaying unusual behavior. For some reason, the notification comes up a minute or less after I open up the app. Sometimes more than once a minute, then it doesn't show up for a while. My idea is to have the notification be given off once a day, assuming the user hasn't access my app in over 24hrs. I intend to cancel any previous timer, and start a new one for 1 day when the user next accesses my app. Below is my code.

```<code>public class Main_Menu extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);

    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    Button goToGame1;

    goToGame1 = (Button) findViewById(R.id.Game1);
    goToGame1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtGame1 = new Intent(Main_Menu.this, memory_modes.class);
            startActivity(beAtGame1);
        }
    });

Button goToGame2;

    goToGame2 = (Button) findViewById(R.id.Game2);
    goToGame2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtGame2 = new Intent(Main_Menu.this, computation_modes.class);
            startActivity(beAtGame2);
        }
    });

Button goToGame3;

    goToGame3 = (Button) findViewById(R.id.Game3);
    goToGame3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtGame3 = new Intent(Main_Menu.this, evaluation_modes.class);
            startActivity(beAtGame3);
        }
    });

    Button goToGame4;

    goToGame4 = (Button) findViewById(R.id.Game4);
    goToGame4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtGame4 = new Intent(Main_Menu.this, attention_modes.class);
            startActivity(beAtGame4);
        }
    });

    Button goToTrackers;

    goToTrackers = (Button) findViewById(R.id.Trackers);
    goToTrackers.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtTrackers = new Intent(Main_Menu.this,trackerMenu.class);
            startActivity(beAtTrackers);
        }
    });

    Intent intent = new Intent(Main_Menu.this, Receiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(Main_Menu.this, 1, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarm.cancel(pendingIntent);
    alarm.setRepeating(alarm.RTC_WAKEUP, System.currentTimeMillis(), alarm.INTERVAL_DAY, pendingIntent);

    }

public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

}
</code>```

and

```<code>public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    showNotification(context);
}

public void showNotification(Context context) {
    Intent intent = new Intent(context, Main_Menu.class);
    PendingIntent pi = PendingIntent.getActivity(context, 1, intent, 0);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.smalliconfinal)
            .setColor(Color.argb(000,255,177,17))
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon4))
            .setContentTitle("Title")
            .setContentText("Some text.");
    mBuilder.setLights(0xffffb111, 750, 750);
    mBuilder.setContentIntent(pi);
    mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    mBuilder.setAutoCancel(true);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());
}

}
</code>```

and from my Manifest:

```<code><receiver android:name=".Receiver"></receiver>
</code>```

Anyone know why this issue occurs?

Much appreciated,
thank you.

答:
The second parameter to the AlarmManager.setRepeating method is the time the alarm should first go off.

You're calling this method using these parameters:

```<code>alarm.setRepeating(alarm.RTC_WAKEUP, System.currentTimeMillis(), alarm.INTERVAL_DAY, pendingIntent);
</code>```

Which means that you're setting the repeating alarm to go off as soon as you call the method (when the Main_Menu activity is created).

From your description it seems like you're looking for something like this:

```<code>alarm.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + AlarmManager.INTERVAL_DAY), AlarmManager.INTERVAL_DAY, pendingIntent);
</code>```

Body:
A push notification set up using alarm manager and pending intent is displaying unusual behavior. For some reason, the notification comes up a minute or less after I open up the app. Sometimes more than once a minute, then it doesn't show up for a while. My idea is to have the notification be given off once a day, assuming the user hasn't access my app in over 24hrs. I intend to cancel any previous timer, and start a new one for 1 day when the user next accesses my app. Below is my code.

public class Main_Menu extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);

    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    Button goToGame1;

    goToGame1 = (Button) findViewById(R.id.Game1);
    goToGame1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtGame1 = new Intent(Main_Menu.this, memory_modes.class);
            startActivity(beAtGame1);
        }
    });

Button goToGame2;

    goToGame2 = (Button) findViewById(R.id.Game2);
    goToGame2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtGame2 = new Intent(Main_Menu.this, computation_modes.class);
            startActivity(beAtGame2);
        }
    });

Button goToGame3;

    goToGame3 = (Button) findViewById(R.id.Game3);
    goToGame3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtGame3 = new Intent(Main_Menu.this, evaluation_modes.class);
            startActivity(beAtGame3);
        }
    });

    Button goToGame4;

    goToGame4 = (Button) findViewById(R.id.Game4);
    goToGame4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtGame4 = new Intent(Main_Menu.this, attention_modes.class);
            startActivity(beAtGame4);
        }
    });

    Button goToTrackers;

    goToTrackers = (Button) findViewById(R.id.Trackers);
    goToTrackers.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent beAtTrackers = new Intent(Main_Menu.this,trackerMenu.class);
            startActivity(beAtTrackers);
        }
    });

    Intent intent = new Intent(Main_Menu.this, Receiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(Main_Menu.this, 1, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarm.cancel(pendingIntent);
    alarm.setRepeating(alarm.RTC_WAKEUP, System.currentTimeMillis(), alarm.INTERVAL_DAY, pendingIntent);

    }

public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

}

and

public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    showNotification(context);
}

public void showNotification(Context context) {
    Intent intent = new Intent(context, Main_Menu.class);
    PendingIntent pi = PendingIntent.getActivity(context, 1, intent, 0);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.smalliconfinal)
            .setColor(Color.argb(000,255,177,17))
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon4))
            .setContentTitle("Title")
            .setContentText("Some text.");
    mBuilder.setLights(0xffffb111, 750, 750);
    mBuilder.setContentIntent(pi);
    mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    mBuilder.setAutoCancel(true);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());
}

}

and from my Manifest:

<receiver android:name=".Receiver"></receiver>

Anyone know why this issue occurs?

Much appreciated,
thank you.

Body:
The second parameter to the AlarmManager.setRepeating method is the time the alarm should first go off.

You're calling this method using these parameters:

alarm.setRepeating(alarm.RTC_WAKEUP, System.currentTimeMillis(), alarm.INTERVAL_DAY, pendingIntent);

Which means that you're setting the repeating alarm to go off as soon as you call the method (when the Main_Menu activity is created).

From your description it seems like you're looking for something like this:

alarm.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + AlarmManager.INTERVAL_DAY), AlarmManager.INTERVAL_DAY, pendingIntent);


问:
Javascript: function not defined with button onclick event?
Learning JS, trying to get this little survey to work, but I get a "function not defined" error at HTML element onclick.  Can't figure out why, it seems like the function is defined and I can't find any syntax errors.  I also get an error saying that "soda is not defined," but it seems like that variable is defined as an object in the array.

```<code><html>
<body>

<h3>What cats are in the room?</h3>

Sophie: <input type="checkbox" id="sophieCheck">
<br></br>
Soda: <input type="checkbox" id="sodaCheck">
<br></br>
Mr.: <input type="checkbox" id="mrCheck">
<br></br>

<button onclick="catsInTheRoom()">Try it</button>
<br></br>

<p id="cats"></p>

<script>
function catsInTheRoom() {

    var myCats = [ soda, mr, sophie ];

    if (getElementById("sodaCheck").checked) {
        myCats[0] = 1;
    } else {
        myCats[0] = 0;
    }
    if (getElementById("sophieCheck").checked) {
        myCats[2] = 10;
    } else {
        myCats[2] = 0;
    }
    if (getElementById("mrCheck").checked) {
        myCats[1] = 20;
    } else {
        myCats[1] = 0;
    }

    getElementById("cats").innerHTML = myCats[0] + myCats[1]  + myCats[2];
}

</script>
</body>
</html>
</code>```

I created the array so I can use the numerical values for a switch statement to produce different text based on which checkboxes are checked.

This simpler version worked:

```<code>Sophie: <input type="checkbox" id="sohpieCheck">
<br></br>
Soda: <input type="checkbox" id="sodaCheck">
<br></br>
Mr.: <input type="checkbox" id="mrCheck">
<br></br>

<button onclick="myFunction()">Try it</button>

<p id="cats"></p>

<script>

function myFunction() {
    var soda = document.getElementById("sodaCheck").checked;

    if (soda) {
        catBehavior = "Cats are being rascals.";
    } else {
        catBehavior = "Cats are behaving nicely.";
    }

    document.getElementById("cats").innerHTML = catBehavior;
}

</script>
</code>```

Why does the second example work, but not the first one?

答:
script error: soda, mr, sophie are used as variables but are never defined before .. throws error and stops function execution.

```<code>var myCats = [ 0, 0, 0 ]; // will initialize myCats to 0,0,0
</code>```

or you can defined variables first:

```<code>var soda = 0, mr = 0, sophie = 0;
</code>```

bunt since you never use them after initial myCats definition, initializing to 0s should enough

Body:
Learning JS, trying to get this little survey to work, but I get a "function not defined" error at HTML element onclick.  Can't figure out why, it seems like the function is defined and I can't find any syntax errors.  I also get an error saying that "soda is not defined," but it seems like that variable is defined as an object in the array.

What cats are in the room?

Sophie: <input type="checkbox" id="sophieCheck">

Soda: <input type="checkbox" id="sodaCheck">

Mr.: <input type="checkbox" id="mrCheck">

<button onclick="catsInTheRoom()">Try it</button>

I created the array so I can use the numerical values for a switch statement to produce different text based on which checkboxes are checked.

This simpler version worked:

Sophie: <input type="checkbox" id="sohpieCheck">

Soda: <input type="checkbox" id="sodaCheck">

Mr.: <input type="checkbox" id="mrCheck">

<button onclick="myFunction()">Try it</button>

Why does the second example work, but not the first one?

Body:
script error: soda, mr, sophie are used as variables but are never defined before .. throws error and stops function execution.

var myCats = [ 0, 0, 0 ]; // will initialize myCats to 0,0,0

or you can defined variables first:

var soda = 0, mr = 0, sophie = 0;

bunt since you never use them after initial myCats definition, initializing to 0s should enough


问:
Claudia.js with multiple AWS lambda functions
I'm using claudia.js CLI to deploy functions and web API to AWS lambda and API gateway.
My project files structure is as follow:

```<code>functions
--function1
---- node_modules
---- package.json
---- index.js
---- claudia.json
--function2
---- node_modules
---- package.json
---- index.js
---- claudia.json
</code>```

The problem is that in order to update new version I have to run "claudia update" in every function folder...so I have to run it once for every function (in every folder). Is there a way to tell claudia.js to update all my functions at once?

答:
We have a lambda repo with multiple replate lambdas, each in its own subfolder. </p>

```<code>> lambdas
> |_lambda1
> |___main.js
> |___main.spec.js
> |___claudia.json
> |___package.json
> |_lambda2
> |___main.js
> |___main.spec.js
> |___claudia.json
> |___package.json
> |_helpers
> |_test.sh
> |_deploy.sh
</code>```

<p>We use npm and a bash script to iterate over each lambda and run a consistent set of npm/eslint commands on them. If that passes the build process we run a claudia command the same way on each lambda. There is some cut and paste  </p>

Body:
I'm using claudia.js CLI to deploy functions and web API to AWS lambda and API gateway.
My project files structure is as follow:

functions
--function1
---- node_modules
---- package.json
---- index.js
---- claudia.json
--function2
---- node_modules
---- package.json
---- index.js
---- claudia.json

The problem is that in order to update new version I have to run "claudia update" in every function folder...so I have to run it once for every function (in every folder). Is there a way to tell claudia.js to update all my functions at once?

Body:
We have a lambda repo with multiple replate lambdas, each in its own subfolder.

> lambdas
> |_lambda1
> |___main.js
> |___main.spec.js
> |___claudia.json
> |___package.json
> |_lambda2
> |___main.js
> |___main.spec.js
> |___claudia.json
> |___package.json
> |_helpers
> |_test.sh
> |_deploy.sh

We use npm and a bash script to iterate over each lambda and run a consistent set of npm/eslint commands on them. If that passes the build process we run a claudia command the same way on each lambda. There is some cut and paste


问:
Parallel.For with custom data type: Update variable outside of the loop
I am trying to write some code based on the answer provided in this question.
The thing is that in my case I have my own custom data type and I am not using an integer.

How can I do a Parallel.For with a custom data?

This is the answer provided in the linked question

```<code>Parallel.For<int>(0, 1000, () => 0, (res, loop, subtotal) =>
            {
                subtotal += 1;
                return subtotal;
            },
            (x) => Interlocked.Add(ref sum, x)
            );
</code>```

And this is how I am doing my loop without using Parallel.

```<code>int value1 = 0;
int value2 = 0;
List<MyData> myDataTypeList = ...
foreach (var myDataType in myDataTypeList)
{
         value1 = value1 + Function1(myDataType);
         value2 = value2 + Function2(myDataType);
}
</code>```

Is there a way I can transform my non-parallel loop into a Parallel.For similar to the response provided in the other question?

答:
You'll need to use an object instead of int for your TLocal variable.

```<code>        int value1 = 0;
        int value2 = 0;

        //Populate data
        List<MyDataType> list = new List<MyDataType>();
        for (int i = 1; i < 5; i++)
            list.Add(new MyDataType { SomeProp = i });

        Parallel.For(
            0, //Start of loop
            list.Count, //End of loop
            () => new SomeObject { Number1 = 0, Number2 = 0 }, //Initializer
            (i, loop, subtotal) =>
            {
                //
                subtotal.Number1 += Function1(list[i]);
                subtotal.Number2 += Function2(list[i]);
                return subtotal;
            }, //Logic
            (x) =>
            {
                Interlocked.Add(ref value1, x.Number1);
                Interlocked.Add(ref value2, x.Number2);
            }//Finally
        );
</code>```

I've created a dummy SomeObject class just for using multiple variables inside the Parallel.For.

```<code>public class SomeObject
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
}
</code>```

Body:
I am trying to write some code based on the answer provided in this question.
The thing is that in my case I have my own custom data type and I am not using an integer.

How can I do a Parallel.For with a custom data?

This is the answer provided in the linked question

Parallel.For<int>(0, 1000, () => 0, (res, loop, subtotal) =>
            {
                subtotal += 1;
                return subtotal;
            },
            (x) => Interlocked.Add(ref sum, x)
            );

And this is how I am doing my loop without using Parallel.

int value1 = 0;
int value2 = 0;
List<MyData> myDataTypeList = ...
foreach (var myDataType in myDataTypeList)
{
         value1 = value1 + Function1(myDataType);
         value2 = value2 + Function2(myDataType);
}

Is there a way I can transform my non-parallel loop into a Parallel.For similar to the response provided in the other question?

Body:
You'll need to use an object instead of int for your TLocal variable.

        int value1 = 0;
        int value2 = 0;

        //Populate data
        List<MyDataType> list = new List<MyDataType>();
        for (int i = 1; i < 5; i++)
            list.Add(new MyDataType { SomeProp = i });

        Parallel.For(
            0, //Start of loop
            list.Count, //End of loop
            () => new SomeObject { Number1 = 0, Number2 = 0 }, //Initializer
            (i, loop, subtotal) =>
            {
                //
                subtotal.Number1 += Function1(list[i]);
                subtotal.Number2 += Function2(list[i]);
                return subtotal;
            }, //Logic
            (x) =>
            {
                Interlocked.Add(ref value1, x.Number1);
                Interlocked.Add(ref value2, x.Number2);
            }//Finally
        );

I've created a dummy SomeObject class just for using multiple variables inside the Parallel.For.

public class SomeObject
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
}