问:
Java function signature accept single enum value
I have a Java class with multiple "type" values, and a class which can take one of those types.

I'm trying to change the implementation of the constructor depending the Type enum using Java's type system, but can't find any information on how to do it.

public enum Type {
    A,
    B,
    C
}

public class Action {
    public Action(Type.A type, String value) {}
    public Action(Type.B type, Float value) {}
    public Action(Type.C type, String value) {}
}
```

Is something to this effect possible in Java? Like it is in Typescript for example.

答:
No, what you wrote will not compile.

You can have named factory methods + a private constructor to achieve a similar result:

public class Action {
  private Action(Type discriminator, String s, Float f) {...}
  public static ofA(String value) { return new Action(Type.A, value, null); }
  public static ofB(Float value)  { return new Action(Type.B, null, value); }
  public static ofC(String value) { return new Action(Type.C, value, null); }
}
```

The constructor will likely have a number of if / else branches. (Sorry, algebraic types and pattern matching are not yet available in Java.)

Body:
I have a Java class with multiple "type" values, and a class which can take one of those types.

I'm trying to change the implementation of the constructor depending the Type enum using Java's type system, but can't find any information on how to do it.

public enum Type {
    A,
    B,
    C
}

public class Action {
    public Action(Type.A type, String value) {}
    public Action(Type.B type, Float value) {}
    public Action(Type.C type, String value) {}
}

Is something to this effect possible in Java? Like it is in Typescript for example.

Body:
No, what you wrote will not compile.

You can have named factory methods + a private constructor to achieve a similar result:

public class Action {
  private Action(Type discriminator, String s, Float f) {...}
  public static ofA(String value) { return new Action(Type.A, value, null); }
  public static ofB(Float value)  { return new Action(Type.B, null, value); }
  public static ofC(String value) { return new Action(Type.C, value, null); }
}

The constructor will likely have a number of if / else branches. (Sorry, algebraic types and pattern matching are not yet available in Java.)


来源: stackexchange

问:
.htaccess rewrite regex regular expressions
My url is:

```<code>http://www.domain.com/Seattle_WA_math
</code>```

It needs to point to:

```<code>http://www.domain.com/list.php?city=Seattle&state=WA&s=math
</code>```

Here's what I have so far, doesn't work...

```<code>RewriteRule ^[A-Za-z_\-]+_[A-Z]{2}_[A-Za-z0-9_\-\(\)]+\/$ list.php?city=$1&state=$2&$s=$3 [L]
</code>```

答:
This should do it:

```<code>RewriteRule ^([A-Za-z\-]+(?:_[A-Za-z\-]+)*)_([A-Z]{2})_([A-Za-z0-9_\-\(\)]+)\/?$ list.php?city=$1&state=$2&$s=$3 [L]
</code>```

Allows multiple worded citys and subjects and optional trailing / path.

ContentLicense: CC BY-SA 3.0

Body:
My url is:

http://www.domain.com/Seattle_WA_math

It needs to point to:

http://www.domain.com/list.php?city=Seattle&state=WA&s=math

Here's what I have so far, doesn't work...

RewriteRule ^[A-Za-z_\-]+_[A-Z]{2}_[A-Za-z0-9_\-\(\)]+\/$ list.php?city=$1&state=$2&$s=$3 [L]

Body:
This should do it:

RewriteRule ^([A-Za-z\-]+(?:_[A-Za-z\-]+)*)_([A-Z]{2})_([A-Za-z0-9_\-\(\)]+)\/?$ list.php?city=$1&state=$2&$s=$3 [L]

Allows multiple worded citys and subjects and optional trailing / path.


答:
It appears that what you are trying to model is three related types

A, with a string value,

B, with a float value, and

C, with a string value.

If so, Java pretty much wants you to make three subclasses, A, B, and C, of an abstract base class, because, well, Java doesn't really do disjoint sum types (a.k.a. disjoint union types, tagged union types) very well.

Information on how to have a single type with "tags" (that's where the name tagged union or tagged sum comes from) is discussed in this Stack Overflow question. It might be best to check out that question at some point, since many ideas are offered; most use generics.

IMHO, Java never really got a proper way to do sum types. Java 8 introduced optionals, but "only optionals," so proper sum types take some work.

So in the meantime, consider the usual Java workarounds:

subclasses (sigh)

static factory methods (since you cannot overload constructors with your enum: A, B, and C all belong to the same type).

EDIT: See the great answer by @9000 which shows exactly how to implement the static factory methods.

ContentLicense: CC BY-SA 4.0

Title: Java function signature accept single enum value


问:
How can I generate a pdf from web URL with Symfony 4?
I try to generate a pdf from webURL with the snappy bundle:

```<code>class PagesController extends AbstractController
{
 /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request)
  {
    $snappy = $this->get("knp_snappy.pdf");
    $snappy->setOption("encoding","UTF-8");

    $filename = "mypdf";
    $webSiteURL = "http://www.stackoverflow.com";
    return new Response(
      $snappy->getOutput($webSiteURL),
      200,
      array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$filname.'.pdf"'
      )
    );
  }
</code>```

But when I try to open the pdf I get the error message:

Service "knp_snappy.pdf" not found: even though it exists in the app's
  container, the container inside "App\Controller\PagesController" is a
  smaller service locator that only knows about the "doctrine",
  "form.factory", "http_kernel", "parameter_bag", "request_stack",
  "router", "security.authorization_checker",
  "security.csrf.token_manager", "security.token_storage", "serializer",
  "session" and "twig" services. Try using dependency injection instead

This is my config/packages/knp_snappy.yaml file:

```<code>knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf
        options:    []
    image:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltoimage
        options:    []
</code>```

One approach to solve this was, I tried to add use Knp\Component\Pager\PaginatorInterface; to my Controller, but then I get the error message:

Cannot determine controller argument for
  "App\Controller\PagesController::pdf()": the $paginator argument is
  type-hinted with the non-existent class or interface:
  "Knp\Component\Pager\PaginatorInterface".

Another approach to solve this was adding to my controller:

```<code>  public static function getSubscribedServices(): array
{
    $services = parent::getSubscribedServices();
    $services['fos_elastica.manager'] = RepositoryManagerInterface::class;
    $services['knp_paginator'] = PaginatorInterface::class;

    return $services;
}
</code>```

But then I get the error message:

The service "App\Controller\PagesController" has a dependency on a
  non-existent service "App\Controller\RepositoryManagerInterface".

答: When a Controller extends the AbstractController it doesn’t have access to container which is responsible to contains services. Try to extends the Controller (note that this class will be removed in Symfony 5) or inject the snappy services in the Controller in the services.yaml file

Body:
I try to generate a pdf from webURL with the snappy bundle:

class PagesController extends AbstractController
{
 /**
  * @Route("/pdf", name="pdf")
  */

  public function pdf(Request $request)
  {
    $snappy = $this->get("knp_snappy.pdf");
    $snappy->setOption("encoding","UTF-8");

    $filename = "mypdf";
    $webSiteURL = "http://www.stackoverflow.com";
    return new Response(
      $snappy->getOutput($webSiteURL),
      200,
      array(
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="'.$filname.'.pdf"'
      )
    );
  }

But when I try to open the pdf I get the error message:

Service "knp_snappy.pdf" not found: even though it exists in the app's
  container, the container inside "App\Controller\PagesController" is a
  smaller service locator that only knows about the "doctrine",
  "form.factory", "http_kernel", "parameter_bag", "request_stack",
  "router", "security.authorization_checker",
  "security.csrf.token_manager", "security.token_storage", "serializer",
  "session" and "twig" services. Try using dependency injection instead

This is my config/packages/knp_snappy.yaml file:

knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf
        options:    []
    image:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltoimage
        options:    []

One approach to solve this was, I tried to add use Knp\Component\Pager\PaginatorInterface; to my Controller, but then I get the error message:

Cannot determine controller argument for
  "App\Controller\PagesController::pdf()": the $paginator argument is
  type-hinted with the non-existent class or interface:
  "Knp\Component\Pager\PaginatorInterface".

Another approach to solve this was adding to my controller:

  public static function getSubscribedServices(): array
{
    $services = parent::getSubscribedServices();
    $services['fos_elastica.manager'] = RepositoryManagerInterface::class;
    $services['knp_paginator'] = PaginatorInterface::class;

    return $services;
}

But then I get the error message:

The service "App\Controller\PagesController" has a dependency on a
  non-existent service "App\Controller\RepositoryManagerInterface".


问:
Device Farm test upload status sits in "INITIALIZED" status forever
I'm using AWS CLI to upload my android app and the tests.zip file to device farm. My test project type is Appium + Java + TestNG.

I'm able to upload the android app successfully, but while trying to upload the "tests.zip" the upload status shows INITIALIZED for ever, even though the upload is completed successfully.(using curl command)

I'm not able to proceed with my automated tests because of this issue. Any clue/suggestions would be really appreciated.

Below is the code snippet that I've been trying with so far and its output.

```<code>TEST_UPLOAD_RESPONSE=$(aws devicefarm create-upload --project-arn $DEVICE_FARM_PROJECT_ARN --name "zip-with-dependencies.zip" --type "APPIUM_JAVA_TESTNG_TEST_PACKAGE" --region "us-west-2" --output "json")
ANDROID_TEST_ARN=$(echo $TEST_UPLOAD_RESPONSE | jq '.upload.arn' | tr -d \")
TEST_PRESIGNED_URL=$(echo $TEST_UPLOAD_RESPONSE | jq '.upload.url' | tr -d \")
echo "Test upload url is :$TEST_PRESIGNED_URL"
echo "Test upload arn is :$ANDROID_TEST_ARN"

curl -T ./target/zip-with-dependencies.zip $APP_PRESIGNED_URL
sleep 5s
TEST_UPLOAD_STATUS=""
while [ "$TEST_UPLOAD_STATUS" != "SUCCEEDED" ]
do
  TEST_UPLOAD_STATUS=$(aws devicefarm get-upload --arn $ANDROID_TEST_ARN --query upload.status)
  TEST_UPLOAD_STATUS=$(echo $TEST_UPLOAD_STATUS | tr -d \")
  echo "Test upload status : $TEST_UPLOAD_STATUS"
done
</code>```

App upload url is :https://prod-us-west-2-uploads.s3-us-west-2.amazonaws.com/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A949397191675%3Aproject%3Acd2fdd09-4c62-42f4-8e27-bde987554d70/uploads/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A949397191675%3Aupload%3Acd2fdd09-4c62-42f4-8e27-bde987554d70/22d28644-4c01-4b82-939c-8e39ee5a268e/zip-with-dependencies.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190525T230634Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIAJSORV74ENYFBITRQ%2F20190525%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=4ace7559023815966bbbd88af6357374bd511d021aeb9d222f9c08acdbb07ed5

  App upload arn is :arn:aws:devicefarm:us-west-2:949397191675:upload:cd2fdd09-4c62-42f4-8e27-bde987554d70/22d28644-4c01-4b82-939c-8e39ee5a268e

    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                   Dload  Upload   Total   Spent    Left  Speed

    0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0

    0 41.2M    0     0    0  400k      0   536k  0:01:18 --:--:--  0:01:18  536k

   62 41.2M    0     0   62 25.6M      0  14.6M  0:00:02  0:00:01  0:00:01 14.6M

  100 41.2M    0     0  100 41.2M      0  17.3M  0:00:02  0:00:02 --:--:-- 17.3M

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  .

  .

答:
Here is a document which shows the process you described

https://docs.aws.amazon.com/devicefarm/latest/developerguide/how-to-create-test-run.html#how-to-create-test-run-cli-step4

When you have the chance can you let me know if all these steps were followed?

The description suggests to me that the wrong upload url was used or that the upload failed during the curl command.

Please provide full output of the commands in the document and I should be able to help more.

Hth

-James

Body:
I'm using AWS CLI to upload my android app and the tests.zip file to device farm. My test project type is Appium + Java + TestNG.

I'm able to upload the android app successfully, but while trying to upload the "tests.zip" the upload status shows INITIALIZED for ever, even though the upload is completed successfully.(using curl command)

I'm not able to proceed with my automated tests because of this issue. Any clue/suggestions would be really appreciated.

Below is the code snippet that I've been trying with so far and its output.

TEST_UPLOAD_RESPONSE=$(aws devicefarm create-upload --project-arn $DEVICE_FARM_PROJECT_ARN --name "zip-with-dependencies.zip" --type "APPIUM_JAVA_TESTNG_TEST_PACKAGE" --region "us-west-2" --output "json")
ANDROID_TEST_ARN=$(echo $TEST_UPLOAD_RESPONSE | jq '.upload.arn' | tr -d \")
TEST_PRESIGNED_URL=$(echo $TEST_UPLOAD_RESPONSE | jq '.upload.url' | tr -d \")
echo "Test upload url is :$TEST_PRESIGNED_URL"
echo "Test upload arn is :$ANDROID_TEST_ARN"

curl -T ./target/zip-with-dependencies.zip $APP_PRESIGNED_URL
sleep 5s
TEST_UPLOAD_STATUS=""
while [ "$TEST_UPLOAD_STATUS" != "SUCCEEDED" ]
do
  TEST_UPLOAD_STATUS=$(aws devicefarm get-upload --arn $ANDROID_TEST_ARN --query upload.status)
  TEST_UPLOAD_STATUS=$(echo $TEST_UPLOAD_STATUS | tr -d \")
  echo "Test upload status : $TEST_UPLOAD_STATUS"
done

App upload url is :<a href="https://prod-us-west-2-uploads.s3-us-west-2.amazonaws.com/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A949397191675%3Aproject%3Acd2fdd09-4c62-42f4-8e27-bde987554d70/uploads/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A949397191675%3Aupload%3Acd2fdd09-4c62-42f4-8e27-bde987554d70/22d28644-4c01-4b82-939c-8e39ee5a268e/zip-with-dependencies.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190525T230634Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIAJSORV74ENYFBITRQ%2F20190525%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=4ace7559023815966bbbd88af6357374bd511d021aeb9d222f9c08acdbb07ed5" rel="nofollow noreferrer">https://prod-us-west-2-uploads.s3-us-west-2.amazonaws.com/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A949397191675%3Aproject%3Acd2fdd09-4c62-42f4-8e27-bde987554d70/uploads/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A949397191675%3Aupload%3Acd2fdd09-4c62-42f4-8e27-bde987554d70/22d28644-4c01-4b82-939c-8e39ee5a268e/zip-with-dependencies.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190525T230634Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIAJSORV74ENYFBITRQ%2F20190525%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=4ace7559023815966bbbd88af6357374bd511d021aeb9d222f9c08acdbb07ed5

  App upload arn is :arn:aws:devicefarm:us-west-2:949397191675:upload:cd2fdd09-4c62-42f4-8e27-bde987554d70/22d28644-4c01-4b82-939c-8e39ee5a268e

    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                   Dload  Upload   Total   Spent    Left  Speed

    0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0

    0 41.2M    0     0    0  400k      0   536k  0:01:18 --:--:--  0:01:18  536k

   62 41.2M    0     0   62 25.6M      0  14.6M  0:00:02  0:00:01  0:00:01 14.6M

  100 41.2M    0     0  100 41.2M      0  17.3M  0:00:02  0:00:02 --:--:-- 17.3M

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  Test upload status : INITIALIZED

  .

  .


问:
How would I use javascript to make an image "jiggle" or "shiver"?
So my question is simple, I'm building a webpage in HTML and I want to incorporate a little JavaScript into it so as to make an image "vibrate" or "jiggle" Basically move back and forth in a relatively tight space/pattern.

I did some research and I found this:

```<code>Copy the below code and paste it into the <HEAD> section of your page
Example:<head>Code Here</head>
<style>
.jc{
position:relative;
}
</style>

<script language="JavaScript1.2">

var ns6=document.getElementById&&!document.all
var ie=document.all

var customcollect=new Array()
var i=0

function jiggleit(num){
if ((!document.all&&!document.getElementById)) return;
customcollect[num].style.left=(parseInt(customcollect[num].style.left)==-1)? customcollect[num].style.left=1 : customcollect[num].style.left=-1
}

function init(){
if (ie){
while (eval("document.all.jiggle"+i)!=null){
customcollect[i]= eval("document.all.jiggle"+i)
i++
}
}
else if (ns6){
while (document.getElementById("jiggle"+i)!=null){
customcollect[i]= document.getElementById("jiggle"+i)
i++
}
}

if (customcollect.length==1)
setInterval("jiggleit(0)",80)
else if (customcollect.length>1)
for (y=0;y<customcollect.length;y++){
var tempvariable='setInterval("jiggleit('+y+')",'+'100 )'
eval(tempvariable)
}
}

window.onload=init

</script>

NOW PASTE THIS ANYWHERE YOU WISH YOUR IMAGE TO APPEAR

<span id="jiggle0" class="jc"><b>YOUR IMAGE URL HERE</b></span>
</code>```

They called it a "shivering pic" and gave an example... its exactly what I want. I did it exactly as they described it. I added the code where they said it was needed, I copied all the right parts (none of the directions), and I made sure everything is in the right place.

I tested it out an there was no image! There was nothing! I realized that this was because I was using a black background, and if there was any text, it would also be black, so what actually was happening was that it was merely showing the URL of the image I want to add in (I could see it once I highlighted it). Regardless, still no image (just the text), and still no vibrating/jittering/shivering/jiggling. I did note that there were bold tags right where it suggests to add the image URL... so to me that would make it seem like I would be putting in text.

PLEASE HELP! How do I make this code work, or how do I make an image "shiver"?

答:
This is what you want :

Dynamic Drive : Shake Image script

Body:
So my question is simple, I'm building a webpage in HTML and I want to incorporate a little JavaScript into it so as to make an image "vibrate" or "jiggle" Basically move back and forth in a relatively tight space/pattern.

I did some research and I found this:

Copy the below code and paste it into the  section of your page
Example:Code Here

NOW PASTE THIS ANYWHERE YOU WISH YOUR IMAGE TO APPEAR

YOUR IMAGE URL HERE

They called it a "shivering pic" and gave an example... its exactly what I want. I did it exactly as they described it. I added the code where they said it was needed, I copied all the right parts (none of the directions), and I made sure everything is in the right place.

I tested it out an there was no image! There was nothing! I realized that this was because I was using a black background, and if there was any text, it would also be black, so what actually was happening was that it was merely showing the URL of the image I want to add in (I could see it once I highlighted it). Regardless, still no image (just the text), and still no vibrating/jittering/shivering/jiggling. I did note that there were bold tags right where it suggests to add the image URL... so to me that would make it seem like I would be putting in text.

PLEASE HELP! How do I make this code work, or how do I make an image "shiver"?


问:
How could I implement image channel drop with the python lib of pillow
I need to randomly zero out 0, 1 or 2 channel of a pillow image. That means I need to randomly set 0, 1 or 2 channels of an image to 0.

How could I do that with pil?

答:
Have you tried using Numpy?
It's quite simple.</p>

```<code>import numpy as np
import PIL.Image as Image
img = np.array(Image.open("image1.jpg")) # My Image
c = np.random.randint(3, size=1)[0] # Selecting a random channel c
img[:,:,c] = img[:,:,c] * 0 # channel c times 0.
</code>```

Body:
Have you tried using Numpy?
It's quite simple.

import numpy as np
import PIL.Image as Image
img = np.array(Image.open("image1.jpg")) # My Image
c = np.random.randint(3, size=1)[0] # Selecting a random channel c
img[:,:,c] = img[:,:,c] * 0 # channel c times 0.


问:
Graceful shutdown while actor is waiting for a reply
I have an Akka cluster with 2 nodes and deploy using a rolling update strategy.

Actor A sends a message to Actor B and becomes a behaviour which waits for a reply.

Example Actor A implementation:

```<code>class ActorA extends AbstractActor {
    private ActorRef sender;

    static Props props () {
        return Props.create(ActorA.class);
    }

    @Override
    public Receive createReceive() {
        return ReceiveBuilder.create()
                .matchAny(msg -> {
                    sender = getSender();
                    getContext().become(waiting());
                })
                .build();
    }

    private Receive waiting() {
        return ReceiveBuilder.create()
                .matchAny(msg -> sender.tell("COMPLETE", getSelf()))
                .build();
    }
}
</code>```

A deployment happens at the same time, so the node containing Actor A receives a SIGTERM and starts a graceful shutdown. From what I've understood from the Akka docs, a graceful shutdown involves sending a PoisonPill to all actors on the node.

So what happens to Actor A? It was waiting for a response from Actor B but has now received a PoisonPill. What happens when Actor B replies to its sender?

In my case Actor A will never receive the response.

答:
Just to make a complete answer out of /u/jrudolph 's comment, Actor A will not get a response. Which it needs to be prepared to deal with anyway, since message delivery is "at-most-once". There are lots of potential reasons that Actor B might not send a response, graceful shutdown being a relatively obscure reason.

Any actor that requires a response has to have some mechanism to deal with situations where it doesn't get that response. That can be a simple retry, Akka's built in guaranteed message delivery (where it will automatically retry), or any method.

Body:
I have an Akka cluster with 2 nodes and deploy using a rolling update strategy.

Actor A sends a message to Actor B and becomes a behaviour which waits for a reply.

Example Actor A implementation:

class ActorA extends AbstractActor {
    private ActorRef sender;

    static Props props () {
        return Props.create(ActorA.class);
    }

    @Override
    public Receive createReceive() {
        return ReceiveBuilder.create()
                .matchAny(msg -> {
                    sender = getSender();
                    getContext().become(waiting());
                })
                .build();
    }

    private Receive waiting() {
        return ReceiveBuilder.create()
                .matchAny(msg -> sender.tell("COMPLETE", getSelf()))
                .build();
    }
}

A deployment happens at the same time, so the node containing Actor A receives a SIGTERM and starts a graceful shutdown. From what I've understood from the Akka docs, a graceful shutdown involves sending a PoisonPill to all actors on the node.

So what happens to Actor A? It was waiting for a response from Actor B but has now received a PoisonPill. What happens when Actor B replies to its sender?

In my case Actor A will never receive the response.


问:
Google Charts: Dynamically Add Series to Chart
There is a similar thread here but the answer isn't clear and there is no clear example to follow.

I need to dynamically add series to a Google Charts graph. Suppose each successive click of a button should add a new series from my array. Right now it just replaces it. What should I do?

// Init
google.charts.load('current', {'packages':['corechart']});

var currentclick = 0;

// My Data
var titles = ['Year1','Year2','Year3','Year4'];
var nums = [ [44,12,33,22], [33,11,7,8], [2,1,65,44] ];

$('#addSeries').click(function() {

   if (currentclick < 3) {
       draw(nums, currentclick);
   }
   currentclick++;
});

function draw(arr, seriesnum) {
  var chartData = new google.visualization.DataTable();
 chartData.addColumn('string', 'Year');
 chartData.addColumn('number', 'Value');

  var chartRowArray = $.makeArray();
 for (var i = 0; i < 4; i++) {
  chartRowArray.push( [ titles[i], arr[seriesnum][i] ] );
 }
 chartData.addRows(chartRowArray);
  var chart = new google.visualization.LineChart(document.getElementById('chartarea'));
  chart.draw(chartData, null);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="addSeries">Add Next Series</button>

<div id="chartarea">
</div></code>```

答:
You want to add a line chart from the data of nums every time when you clicked "Add Next Series" button.

If my understanding is correct, how about this modification? I think that there are several answers for your situation. So please think of this as just one of several answers.

Modification point:

In this modification, chartRowArray is declared as a global variable. When the button is clicked, the data is added to chartRowArray. By this, the line chars are added to the existing chart.

Modified script:

// Init
google.charts.load('current', {'packages':['corechart']});
var currentclick = 0;

// My Data
var titles = ['Year1','Year2','Year3','Year4'];
var nums = [ [44,12,33,22], [33,11,7,8], [2,1,65,44] ];

$('#addSeries').click(function() {
  if (currentclick < 3) {
    draw(nums, currentclick);
  }
  currentclick++;
});

// Below script was modified.
var chartRowArray = $.makeArray(); // Added

function draw(arr, seriesnum) {
  var chartData = new google.visualization.DataTable();
  chartData.addColumn('string', 'Year');
  for (var i = 0; i < seriesnum + 1; i++) { // Added
    chartData.addColumn('number', 'Value');
  }
  if (seriesnum === 0) { // Added
    for (var i = 0; i < 4; i++) {
      chartRowArray.push( [ titles[i], arr[seriesnum][i] ] );
    }
  } else { // Added
    for (var i = 0; i < 4; i++) {
      chartRowArray[i].push(arr[seriesnum][i]);
    }
  }
  chartData.addRows(chartRowArray);
  var chart = new google.visualization.LineChart(document.getElementById('chartarea'));
  chart.draw(chartData, null);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="addSeries">Add Next Series</button>
<div id="chartarea"></div></code>```

If I misunderstood your question and this was not the result you want, I apologize.

Body:
There is a similar thread here but the answer isn't clear and there is no clear example to follow.

I need to dynamically add series to a Google Charts graph. Suppose each successive click of a button should add a new series from my array. Right now it just replaces it. What should I do?

// Init
google.charts.load('current', {'packages':['corechart']});

var currentclick = 0;

// My Data
var titles = ['Year1','Year2','Year3','Year4'];
var nums = [ [44,12,33,22], [33,11,7,8], [2,1,65,44] ];

$('#addSeries').click(function() {

   if (currentclick < 3) {
       draw(nums, currentclick);
   }
   currentclick++;
});

function draw(arr, seriesnum) {
  var chartData = new google.visualization.DataTable();
 chartData.addColumn('string', 'Year');
 chartData.addColumn('number', 'Value');

  var chartRowArray = $.makeArray();
 for (var i = 0; i < 4; i++) {
  chartRowArray.push( [ titles[i], arr[seriesnum][i] ] );
 }
 chartData.addRows(chartRowArray);
  var chart = new google.visualization.LineChart(document.getElementById('chartarea'));
  chart.draw(chartData, null);
}

<button id="addSeries">Add Next Series</button>

Body:
You want to add a line chart from the data of nums every time when you clicked "Add Next Series" button.

If my understanding is correct, how about this modification? I think that there are several answers for your situation. So please think of this as just one of several answers.

Modification point:

In this modification, chartRowArray is declared as a global variable. When the button is clicked, the data is added to chartRowArray. By this, the line chars are added to the existing chart.

Modified script:

// Init
google.charts.load('current', {'packages':['corechart']});
var currentclick = 0;

// My Data
var titles = ['Year1','Year2','Year3','Year4'];
var nums = [ [44,12,33,22], [33,11,7,8], [2,1,65,44] ];

$('#addSeries').click(function() {
  if (currentclick < 3) {
    draw(nums, currentclick);
  }
  currentclick++;
});

// Below script was modified.
var chartRowArray = $.makeArray(); // Added

function draw(arr, seriesnum) {
  var chartData = new google.visualization.DataTable();
  chartData.addColumn('string', 'Year');
  for (var i = 0; i < seriesnum + 1; i++) { // Added
    chartData.addColumn('number', 'Value');
  }
  if (seriesnum === 0) { // Added
    for (var i = 0; i < 4; i++) {
      chartRowArray.push( [ titles[i], arr[seriesnum][i] ] );
    }
  } else { // Added
    for (var i = 0; i < 4; i++) {
      chartRowArray[i].push(arr[seriesnum][i]);
    }
  }
  chartData.addRows(chartRowArray);
  var chart = new google.visualization.LineChart(document.getElementById('chartarea'));
  chart.draw(chartData, null);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="addSeries">Add Next Series</button>
<div id="chartarea"></div>

If I misunderstood your question and this was not the result you want, I apologize.


问:
Python boto ec2 - How do I wait till an image is created or failed
I am writing a code to iterate through all available instances and create an AMI for them as below:

```<code>for reservation in reservations:
    ......
    ami_id = ec2_conn.create_image(instance.id, ami_name, description=ami_desc, no_reboot=True)
</code>```

But how do I wait till an image is created before proceeding with the creation of next image? Because I need to track the status of each ami created.

I know that I can retrieve the state using:

```<code>image_status = get_image(ami_id).state
</code>```

So, do I iterate through the list of ami_ids created and then fetch the state for each of them? If so, then what if the image is still pending when I read the state of the image? How will I find out if the image creation has failed eventually?

Thanks.

答:
I'll answer the exact same question.

Keep updating the image state variable while the state is not running.
At any point if the state is running, break the loop.
You can also check for terminated states or failed states.

```<code>image = ec2.Image(image_id)
if(image.state == 'pending'):
        print("Waiting for image to be available.")
        while(image.state != 'available'):
            image = ec2.Image(image_id)
        print("Image Available to use")
</code>```

TIP:
Don't wait for images to be available while creating the images.
Check for images to be available while creating the instances from those images. It will save you a lot of time because a lot of pending images will be able to concurrently come into the available state.

If you wait for each image to be available, you are just adding all the creation time to your program.

Hope it helps.

Body:
I am writing a code to iterate through all available instances and create an AMI for them as below:

for reservation in reservations:
    ......
    ami_id = ec2_conn.create_image(instance.id, ami_name, description=ami_desc, no_reboot=True)

But how do I wait till an image is created before proceeding with the creation of next image? Because I need to track the status of each ami created.

I know that I can retrieve the state using:

image_status = get_image(ami_id).state

So, do I iterate through the list of ami_ids created and then fetch the state for each of them? If so, then what if the image is still pending when I read the state of the image? How will I find out if the image creation has failed eventually?

Thanks.

Body:
I'll answer the exact same question.

Keep updating the image state variable while the state is not running.
At any point if the state is running, break the loop.
You can also check for terminated states or failed states.

image = ec2.Image(image_id)
if(image.state == 'pending'):
        print("Waiting for image to be available.")
        while(image.state != 'available'):
            image = ec2.Image(image_id)
        print("Image Available to use")

TIP:
Don't wait for images to be available while creating the images.
Check for images to be available while creating the instances from those images. It will save you a lot of time because a lot of pending images will be able to concurrently come into the available state.

If you wait for each image to be available, you are just adding all the creation time to your program.

Hope it helps.


问:
Meters/Measures Not Auto-Refreshing
I've made a widget that is supposed to tell me what % of my shift is complete, but it's not auto-refreshing so if I want the current value I have to manually refresh the skin. How can I make it auto-refresh?

I've tried setting the Update= manually, adding OnUpdateAction and [!Redraw] and a bunch of other things that I regrettably didn't save since they didn't work so now I can't remember them.  (Code below has left out metadata, xy coordinates, and irrelevant variables and values not pertaining to this question such as font settings.)

```<code>[Rainmeter]
MiddleMouseDownAction=[!WriteKeyValue Variables OffWorkTime1 #OffWorkTime2#][!WriteKeyValue Variables OffWorkTime2 #OffWorkTime3#][!WriteKeyValue Variables OffWorkTime3 #OffWorkTime4#][!WriteKeyValue Variables OffWorkTime4 #OffWorkTime5#][!WriteKeyValue Variables OffWorkTime5 #OffWorkTime1#][!Refresh]
OnUpdateAction=[!UpdateMeasure MeasurePercElaps][!UpdateMeter MeterPercentDisplay][!WriteKeyValue Variables OffWorkTime1 #OffWorkTime1#][!WriteKeyValue Variables OffWorkTime2 #OffWorkTime2#][!WriteKeyValue Variables OffWorkTime3 #OffWorkTime3#][!WriteKeyValue Variables OffWorkTime4 #OffWorkTime4#][!WriteKeyValue Variables OffWorkTime5 #OffWorkTime5#][!Redraw]
LeftMouseDownAction=[!UpdateMeasure MeasurePercElaps][!UpdateMeter MeterPercentDisplay][!Redraw]
Update=200

[Variables]
OffWorkTime1=870
OffWorkTime2=900
OffWorkTime3=990
OffWorkTime4=1140
OffWorkTime5=1260
HR=[MeasureHour]
MN=[MeasureMin]
PElaps=[MeasurePercElaps:0%]

;MEASURES===================

[MeasureHour]
measure=time
format=%H

[MeasureMin]
measure=time
format=%M

[MeasurePercElaps]
measure=calc
formula=(((540 - (#OffWorkTime1# - ((#HR# * 60) + #MN#))) / 540) * 100)
MinValue=0
MaxValue=100

;METERS===================

[MeterBarPercent]
meter=bar
MeasureName=MeasurePercElaps
W=201
h=23
ValueRemainder=100
BarColor=84,165,196,255
BarOrientation=Horizontal
DynamicVariables=1

[MeterPercentDisplay]
meter=string
MeasureName=MeasurePercElaps
AntiAlias=1
NumOfDecimals=1
DynamicVariables=1
Postfix=% COMPLETE
</code>```

It should be auto-refreshing every Update cycle, but instead the only way I can get it to refresh the values displayed is by manually refreshing it. It gives the correct value when refreshed, so I know the formulas aren't faulty, but it's just not updating automatically for some reason. The  LeftMouseDownAction= thing I put in there doesn't work either. Any pointers you have would be much appreciated.

~δelta

答:
You need to DynamicVariables=1 under the measure, [MeasurePercElaps] for it to keep updating.

Following script is more or less what are you trying to achieve but I just use a formula to calculate the % seconds left in 1 minute for an immediate effect.

```<code>;MEASURES===================

[MeasureHour]
measure=Time
format=%H

[MeasureMin]
measure=Time
format=%M

[MeasureSec]
measure=Time
format=%S

[MeasurePercElaps]
measure=Calc
;formula=(((540 - (#OffWorkTime1# - ((#HR# * 60) + #MN#))) / 540) * 100)
formula=((60.0-[MeasureSec])/60.0)*100.0
MinValue=0
MaxValue=100
DynamicVariables=1

[MeterBarPercent]
meter=Bar
MeasureName=MeasurePercElaps
AntiAlias=1
FontFace=#FontFace#
FontSize=12
SolidColor=47,47,47,255
StringAlign=Left
X=0
Y=0
W=190
H=20
ValueRemainder=100
BarColor=84,165,196,255
BarOrientation=Horizontal
DynamicVariables=1

[MeterPercentDisplay]
meter=String
MeasureName=MeasurePercElaps
AntiAlias=1
FontFace=#FontFace#
FontSize=12
FontColor=255,255,255,255
StringAlign=Left
X=0
Y=0
W=190
AntiAlias=1
NumOfDecimals=1
Postfix=% COMPLETE
DynamicVariables=1
</code>```

The bar meter should be like below:

Since the [MeasurePercElaps] now can update itself, LeftMouseDownAction in the [Rainmeter] is not needed anymore. If you still put it there, it will lock you from moving the skin anywhere in your desktop area and you won't be able to open the skin's popup menu.

You can keep OnUpdateAction if you need to make your OffWorkTime variables persist on the next skin load/reload. But, I don't see the point, since you are only saving variables that are always constant during the skin session. It is what !WriteKeyValue bang is doing.

On the other hand, MiddleMouseDownAction is quite redundant.

Title: Meters/Measures Not Auto-Refreshing

Body:
I've made a widget that is supposed to tell me what % of my shift is complete, but it's not auto-refreshing so if I want the current value I have to manually refresh the skin. How can I make it auto-refresh?

I've tried setting the Update= manually, adding OnUpdateAction and [!Redraw] and a bunch of other things that I regrettably didn't save since they didn't work so now I can't remember them.  (Code below has left out metadata, xy coordinates, and irrelevant variables and values not pertaining to this question such as font settings.)

[Rainmeter]
MiddleMouseDownAction=[!WriteKeyValue Variables OffWorkTime1 #OffWorkTime2#][!WriteKeyValue Variables OffWorkTime2 #OffWorkTime3#][!WriteKeyValue Variables OffWorkTime3 #OffWorkTime4#][!WriteKeyValue Variables OffWorkTime4 #OffWorkTime5#][!WriteKeyValue Variables OffWorkTime5 #OffWorkTime1#][!Refresh]
OnUpdateAction=[!UpdateMeasure MeasurePercElaps][!UpdateMeter MeterPercentDisplay][!WriteKeyValue Variables OffWorkTime1 #OffWorkTime1#][!WriteKeyValue Variables OffWorkTime2 #OffWorkTime2#][!WriteKeyValue Variables OffWorkTime3 #OffWorkTime3#][!WriteKeyValue Variables OffWorkTime4 #OffWorkTime4#][!WriteKeyValue Variables OffWorkTime5 #OffWorkTime5#][!Redraw]
LeftMouseDownAction=[!UpdateMeasure MeasurePercElaps][!UpdateMeter MeterPercentDisplay][!Redraw]
Update=200

[Variables]
OffWorkTime1=870
OffWorkTime2=900
OffWorkTime3=990
OffWorkTime4=1140
OffWorkTime5=1260
HR=[MeasureHour]
MN=[MeasureMin]
PElaps=[MeasurePercElaps:0%]

;MEASURES===================

[MeasureHour]
measure=time
format=%H

[MeasureMin]
measure=time
format=%M

[MeasurePercElaps]
measure=calc
formula=(((540 - (#OffWorkTime1# - ((#HR# * 60) + #MN#))) / 540) * 100)
MinValue=0
MaxValue=100

;METERS===================

[MeterBarPercent]
meter=bar
MeasureName=MeasurePercElaps
W=201
h=23
ValueRemainder=100
BarColor=84,165,196,255
BarOrientation=Horizontal
DynamicVariables=1

[MeterPercentDisplay]
meter=string
MeasureName=MeasurePercElaps
AntiAlias=1
NumOfDecimals=1
DynamicVariables=1
Postfix=% COMPLETE

It should be auto-refreshing every Update cycle, but instead the only way I can get it to refresh the values displayed is by manually refreshing it. It gives the correct value when refreshed, so I know the formulas aren't faulty, but it's just not updating automatically for some reason. The  LeftMouseDownAction= thing I put in there doesn't work either. Any pointers you have would be much appreciated.

~δelta

Body:
You need to DynamicVariables=1 under the measure, [MeasurePercElaps] for it to keep updating.

Following script is more or less what are you trying to achieve but I just use a formula to calculate the % seconds left in 1 minute for an immediate effect.

;MEASURES===================

[MeasureHour]
measure=Time
format=%H

[MeasureMin]
measure=Time
format=%M

[MeasureSec]
measure=Time
format=%S

[MeasurePercElaps]
measure=Calc
;formula=(((540 - (#OffWorkTime1# - ((#HR# * 60) + #MN#))) / 540) * 100)
formula=((60.0-[MeasureSec])/60.0)*100.0
MinValue=0
MaxValue=100
DynamicVariables=1

[MeterBarPercent]
meter=Bar
MeasureName=MeasurePercElaps
AntiAlias=1
FontFace=#FontFace#
FontSize=12
SolidColor=47,47,47,255
StringAlign=Left
X=0
Y=0
W=190
H=20
ValueRemainder=100
BarColor=84,165,196,255
BarOrientation=Horizontal
DynamicVariables=1

[MeterPercentDisplay]
meter=String
MeasureName=MeasurePercElaps
AntiAlias=1
FontFace=#FontFace#
FontSize=12
FontColor=255,255,255,255
StringAlign=Left
X=0
Y=0
W=190
AntiAlias=1
NumOfDecimals=1
Postfix=% COMPLETE
DynamicVariables=1

The bar meter should be like below:

Since the [MeasurePercElaps] now can update itself, LeftMouseDownAction in the [Rainmeter] is not needed anymore. If you still put it there, it will lock you from moving the skin anywhere in your desktop area and you won't be able to open the skin's popup menu.

You can keep OnUpdateAction if you need to make your OffWorkTime variables persist on the next skin load/reload. But, I don't see the point, since you are only saving variables that are always constant during the skin session. It is what !WriteKeyValue bang is doing.

On the other hand, MiddleMouseDownAction is quite redundant.


问:
Timer and TimerTask Problem: "Timer.class not in android.jar" and "The Application Has Stopped Unexpectedly"?
So I'm trying to make a "live feed" essentially, and my code is shown below. Basically, I got "The Application Has Stopped Unexpectedly" error, so I debugged. When I debugged, it said "Timer.class not in android.jar". I know my refreshFeed() static method works perfectly fine (tested it without the timer), so it can't be that. Is there something I'm missing here? Any help is greatly appreciated!</p>

```<code>Timer time = new Timer();
    TimerTask refresh = new TimerTask(){
        public void run(){
            feedEntry.refreshFeed();
        }
    };
    time.scheduleAtFixedRate(refresh, 0, 10000);
</code>```

答:
Both Timer and TimerTask present in java.util package.

What you need to is do is use handler.
Read about handler if you are new to android.
http://developer.android.com/reference/android/os/Handler.html

```<code>Handler handler = new Handler();

    t = new Timer();
    timeTask = new TimerTask() {
        public void run() {
                handler.post(new Runnable() {
                        public void run() {
                            feedEntry.refreshFeed();
                        }
               });
        }};

        t.scheduleAtFixedRate(timeTask, 0, 1000);
</code>```

Body:
So I'm trying to make a "live feed" essentially, and my code is shown below. Basically, I got "The Application Has Stopped Unexpectedly" error, so I debugged. When I debugged, it said "Timer.class not in android.jar". I know my refreshFeed() static method works perfectly fine (tested it without the timer), so it can't be that. Is there something I'm missing here? Any help is greatly appreciated!

Timer time = new Timer();
    TimerTask refresh = new TimerTask(){
        public void run(){
            feedEntry.refreshFeed();
        }
    };
    time.scheduleAtFixedRate(refresh, 0, 10000);

Body:
Both Timer and TimerTask present in java.util package.

What you need to is do is use handler.
Read about handler if you are new to android.
http://developer.android.com/reference/android/os/Handler.html

Handler handler = new Handler();

    t = new Timer();
    timeTask = new TimerTask() {
        public void run() {
                handler.post(new Runnable() {
                        public void run() {
                            feedEntry.refreshFeed();
                        }
               });
        }};

        t.scheduleAtFixedRate(timeTask, 0, 1000);


答:
Looks like A and C are from the same "type" family and B belongs to another Type.
In such a case you should define two types.
If you want to be able to have both types be treated as the same "family", have them implement the same interface:</p>

```<code>interface Type {
}

enum Type1 implements Type {
    A,
    C
}

enum Type2 implements Type {
    B
}

public class Action {
    public Action(Type1 type, String value) {}
    public Action(Type2 type, Float value) {}
}
</code>```

Body:
I have a Java class with multiple "type" values, and a class which can take one of those types.

I'm trying to change the implementation of the constructor depending the Type enum using Java's type system, but can't find any information on how to do it.

public enum Type {
    A,
    B,
    C
}

public class Action {
    public Action(Type.A type, String value) {}
    public Action(Type.B type, Float value) {}
    public Action(Type.C type, String value) {}
}

Is something to this effect possible in Java? Like it is in Typescript for example.

Body:
Looks like A and C are from the same "type" family and B belongs to another Type.
In such a case you should define two types.
If you want to be able to have both types be treated as the same "family", have them implement the same interface:

interface Type {
}

enum Type1 implements Type {
    A,
    C
}

enum Type2 implements Type {
    B
}

public class Action {
    public Action(Type1 type, String value) {}
    public Action(Type2 type, Float value) {}
}


问:
Populating cells in separate sheet based on info on original sheet
On my first sheet, I have 6 columns with lots of rows of data. The first column is date and the second is standard. In the second column, the info will either say met standard or not met standards. I want my second sheet to pull all of the rows that haven't met the standards.

I am new to Google Sheets, so I have attempted a few things, but I'm looking for some advise on what's the best way to do this.

I want my second sheet to be populated with data from the first based on a specific field in the second row of the first sheet.

答:
You might indicate whether this is a one-off, or regular event. In any event, it sounds like a query would meet your needs. There are dozens of topics on stack overflow (and the net generally) on using query. But it sounds like something like this would suit.

```<code>=query('sheetname'!A1:F27,"Select A, B, C, D, E where B='met standard'",-1)
</code>```

Instructions:

1 - Put this formula in cell A1 of the second sheet

2 - Edit the formula to replace "sheetname" with the actual name of the first sheet.

3 - Edit the formula to replace the range (A1:F27 in this example) with the actual range of the data on the first sheet.

In this example, I've included Row#1 to capture headers. The "-1" at the end of the query has the effect of displaying those headers.

Demo data

Query output

Body:
You might indicate whether this is a one-off, or regular event. In any event, it sounds like a query would meet your needs. There are dozens of topics on stack overflow (and the net generally) on using query. But it sounds like something like this would suit.

=query('sheetname'!A1:F27,"Select A, B, C, D, E where B='met standard'",-1)

Instructions:

1 - Put this formula in cell A1 of the second sheet

2 - Edit the formula to replace "sheetname" with the actual name of the first sheet.

3 - Edit the formula to replace the range (A1:F27 in this example) with the actual range of the data on the first sheet.

In this example, I've included Row#1 to capture headers. The "-1" at the end of the query has the effect of displaying those headers.

Demo data

Query output


问:
How do I solve problems that occur when Akka cannot get heartbeat?
When I work with Akka, I have problems if I do debug.They can't get heartbeat while they're debugging. Then they start not seeing each other anymore.

As far as I can tell, if he can't get a heartbeat after the next 10 seconds, he's out of the cluster and can't see each other anymore. I want to extend this period. For example, if you can't hearbeat for 5 minutes, then you should get out of the cluster.I'm looking for solutions like this.

答: Turn off auto-downing. That way the node you are debugging might get marked as unreachable, but it will never be removed from the cluster. (And as soon as you release it from being frozen the other nodes will mark it as reachable again.)</p>


问:
Calculate relative time in C#
Given a specific DateTime value, how do I display relative time, like:

2 hours ago

3 days ago

a month ago

答:
```<code>// Calculate total days in current year
int daysInYear;

for (var i = 1; i <= 12; i++)
    daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i);

// Past date
DateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582));

// Calculate difference between current date and past date
double diff = (DateTime.Now - dateToCompare).TotalMilliseconds;

TimeSpan ts = TimeSpan.FromMilliseconds(diff);

var years = ts.TotalDays / daysInYear; // Years
var months = ts.TotalDays / (daysInYear / (double)12); // Months
var weeks = ts.TotalDays / 7; // Weeks
var days = ts.TotalDays; // Days
var hours = ts.TotalHours; // Hours
var minutes = ts.TotalMinutes; // Minutes
var seconds = ts.TotalSeconds; // Seconds

if (years >= 1)
    Console.WriteLine(Math.Round(years, 0) + " year(s) ago");
else if (months >= 1)
    Console.WriteLine(Math.Round(months, 0) + " month(s) ago");
else if (weeks >= 1)
    Console.WriteLine(Math.Round(weeks, 0) + " week(s) ago");
else if (days >= 1)
    Console.WriteLine(Math.Round(days, 0) + " days(s) ago");
else if (hours >= 1)
    Console.WriteLine(Math.Round(hours, 0) + " hour(s) ago");
else if (minutes >= 1)
    Console.WriteLine(Math.Round(minutes, 0) + " minute(s) ago");
else if (seconds >= 1)
    Console.WriteLine(Math.Round(seconds, 0) + " second(s) ago");

Console.ReadLine();
</code>```

Title: Calculate relative time in C#


问:
Detect if data changed on jQuery.load()
I'm pretty sure this exists, but I don't know what to search for:

I am refreshing content via JQuery's $('#somediv').load() and another via $.ajax(). I would like to catch situations where the new content is identical to the old content and slow down the refresh rate.

I can imagine how to do it for the ajax case - but seems like I'd have to store in memory a lot of data.

But what about load?

答:
From a performance perspective, would I be right in assuming that the answer Jasie has provided requires that the browser load the entire remote file so that it can check the contents against the locally stored variable?

A more efficient method if you're looking for efficiency might be using ajax because it can just check the header and use the last modified date. (Stuff I read here http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06)

Therefore a simple header check could be on repeat and then exit to a file reload only when modified date has changed.

I'm going to work on using this method and will post the results here when/if I get them working.

ContentLicense: CC BY-SA 2.5

Title: Detect if data changed on jQuery.load()


问:
Unable to connect two call back functions together in dash app
Hello I am working on a dash app for the first time and I am unable to fix
an issue that I am facing. I have a front-end that takes the user input, does some calculation, stores the result in a hidden div and then updates the graph.

The app loads fine however it runs into an error as soon as I hit the submit button. Below is the code I have written. It looks like both the callback functions triggers at the same time.

```<code>app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
    html.Div([
        html.Div([
            html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()), className="nine columns")
        ], className="three columns"),
        html.Div([
            html.Div([
                html.Div([
                    html.P("Select Month Range:"),
                ],
                    className="two columns"
                ),

                html.Div([
                    dcc.RangeSlider(
                        id='month_slider',
                        # updatemode='drag',
                        # count=1,
                        min=1,
                        max=maxmarks,
                        step=1,
                        value=[maxmarks - 1, maxmarks],
                        marks=tags,
                        pushable=1
                    ),

                ],
                    className="six columns",
                    style={})
            ],
                className="twelve columns",
                style={
                    'backgroundColor': '#EFEAEA',
                    'padding-top': '1.5em',
                    'padding-bottom': '1em'
                }),
            html.Div([
                html.Div([
                    dcc.Dropdown(
                        id='demographics',
                        options=[
                            {'label': 'All 18-49', 'value': '18-49'},
                            {'label': 'Female 25-54', 'value': '25-54F'},
                            {'label': 'All 25-54', 'value': '25-54'},
                        ],
                        placeholder="Select Demographics",
                    )
                ],
                    className="two columns",
                    style={}),
                html.Div([
                    dcc.Dropdown(
                        id='ID',
                        options=[
                            {'label': '200', 'value': 200, 'type': 'number'},
                            {'label': '250', 'value': 250, 'type': 'number'},
                            {'label': '300', 'value': 300, 'type': 'number'},
                            {'label': '350', 'value': 350, 'type': 'number'},
                            {'label': '400', 'value': 400, 'type': 'number'},
                        ],
                        placeholder="Select ID",
                    )
                ],
                    className="two columns",
                    style={}),
                html.Div([
                    dcc.Dropdown(
                        id='Income',
                        options=[
                            {'label': '50,000', 'value': 50000, 'type': 'number'},
                            {'label': '100,000', 'value': 100000, 'type': 'number'},
                            {'label': '200,000', 'value': 200000, 'type': 'number'},
                            {'label': '350,000', 'value': 350000, 'type': 'number'},
                            {'label': '500,000', 'value': 500000, 'type': 'number'},
                        ],
                        placeholder="Select Income",
                    )
                ],
                    className="two columns",
                    style={}),
                html.Div([
                    dcc.Dropdown(
                        id='Frquency',
                        options=[
                            {'label': 'None per week, 'value': 0, 'type': 'number'},
                            {'label': 'Once per Week', 'value': 1, 'type': 'number'},
                            {'label': 'Thrice per Week', 'value': 3, 'type': 'number'},
                        ],
                        placeholder="Select Frequency",
                    )
                ],
                    className="two columns",
                    style={}),
                html.Div([
                    html.Button('Submit', id='submit_button', className='twelve columns',
                                style={'background-color': '#2D91C3', 'color': 'white', 'font-size': '1em'})
                ],
                    className="two columns",
                    style={}),
            ],
                className="twelve columns",
                style={
                    'backgroundColor': '#EFEAEA',
                    'padding-top': '1em',
                    'padding-bottom': '1.5em'
                })
        ], className="nine columns", style={})
    ], className="twelve columns"),

    # dcc.graph layout

    html.Div([
        html.Div([
            dcc.Graph(id='example-graph', config={"displayModeBar": False, "scrollZoom": False})

        ],
            className="six columns",
            style={'border-right': 'thin grey solid', 'border-left': 'thin grey solid',
                   'border-top': 'thin grey solid'}),

    html.Div(id='intermediate-value1', style={'display': 'none'})
])]

@app.callback(
    Output("intermediate-value1", "children"),
    [Input("submit_button", "n_clicks")],
    [
        State("month_slider", "value"),
        State("demographics", "value"),
        State("Income", "value"),
        State("Frequency", "value"),
    ],
)
def clean_data(n_clicks, month_range, demo, inc, fre_cap):
    if n_clicks is not None and n_clicks > 0:
        employee_data_temp = employee_data.copy()
        start_date = month_range[0]
        end_date = month_range[1]
        mask1 = employee_data_temp["total_months"] == int(end_date - start_date)
        employee_data_temp = employee_data_temp.loc[mask1]
        mask2 = (
            (employee_data_temp["demographic"] == demo)
            & (employee_data_temp["freq_cap"] == fre_cap)
            & (employee_data_temp["total_incressions"] == inc)
        )
        employee_data_temp = employee_data_temp.loc[mask2]
        employee_data_temp = employee_data_temp.sort_values(by=["reach"])
        employee_data_temp["income_percent"] = (employee_data_temp["reach"] / 955000) * 100
        employee_data_temp = employee_data_temp.reset_index(drop=True)
        return employee_data_temp.to_json(date_format="iso", orient="split")
    else:
        return []

@app.callback(Output("example-graph", "figure"),
              [Input("submit_button", "n_clicks")],
              [State("intermediate-value1", "children"),
               State("Income", "value")])

def update_graph(n_clicks, employee_data_temp, inc):
    t.sleep(2)
    if n_clicks is not None and n_clicks > 0:
        dff = pd.read_json(employee_data_temp, orient="split")
        max_income = dff["income_percent"].iloc[9]
        max_income = max_income.round(2)
        trace = Scatter(
            y=dff["income_percent"], x=dff["inc"], line=plotly.graph_objs.scatter.Line(color="#1a2d46"), mode="lines"
        )
        layout1 = Layout(
            plot_bgcolor="#FFFFFF",
            paper_bgcolor="#FFFFFF",
            height=450,
            title="Digital Reach - " + str(max_income) + " " + "%",
            xaxis=dict(showgrid=True, showline=True, zeroline=True, fixedrange=True, title="Total Income"),
            yaxis=dict(showline=True, fixedrange=True, zeroline=True, title="Income (%)"),
            margin=plotly.graph_objs.layout.Margin(t=45, l=50, r=50),
        )
        return Figure(data=[trace], layout=layout1)
    else:
        return []
</code>```

Below is the error I get:

```<code>Traceback (most recent call last):
  File "C:\Users\Tushar\Documents\django_projects\tvnz_dash_app\src\dash_app\incrementor\views.py", line 21, in dispatcher
    response = server.full_dispatch_request()
  File "C:\python37\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\python37\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\python37\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\python37\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\python37\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\python37\lib\site-packages\dash\dash.py", line 1073, in dispatch
    response.set_data(self.callback_map[output]['callback'](*args))
  File "C:\python37\lib\site-packages\dash\dash.py", line 969, in add_context
    output_value = func(*args, **kwargs)
  File "C:\Users\Tushar\Documents\django_projects\tvnz_dash_app\src\dash_app\incrementor\router.py", line 699, in update_graph
    dff = pd.read_json(employee_data_temp, orient="split")
  File "C:\python37\lib\site-packages\pandas\io\json\json.py", line 413, in read_json
    path_or_buf, encoding=encoding, compression=compression,
  File "C:\python37\lib\site-packages\pandas\io\common.py", line 232, in get_filepath_or_buffer
    raise ValueError(msg.format(_type=type(filepath_or_buffer)))
ValueError: Invalid file path or buffer object type: <class 'NoneType'>
</code>```

What I want is that the function should run when a user click a submit button and as the update graph function is dependent on the clean data function it should not run until and unless the clean data function is finished completing.

Please can some one help me to figure what am I missing here and help to resolve the issue.

Thanks a lot in advance !!

NEW UPDATED FUNCTIONS

```<code>
@app.callback(
    Output("intermediate-value1", "children"),
    [Input("submit_button", "n_clicks")],
    [
        State("month_slider", "value"),
        State("demographics", "value"),
        State("digital_impressions", "value"),
        State("digital_frequency", "value"),
    ],
)

def get_match(n_clicks, month_range, demo, tarps):
    if n_clicks is not None and n_clicks > 0:
        some long python script data calculatation
        return match_data_temp.to_json(date_format="iso", orient="split")

@app.callback(
    Output("intermediate-value2", "children"),
    [Input("submit_button", "n_clicks")],
    [
        State("month_slider", "value"),
        State("demographics", "value"),
        State("digital_impressions", "value"),
        State("digital_frequency", "value"),
    ],
)

def clean_data(n_clicks, month_range, demo, inc, fre_cap):
    if n_clicks is not None and n_clicks > 0:
        employee_data_temp = employee_data.copy()
        start_date = month_range[0]
        end_date = month_range[1]
        mask1 = employee_data_temp["total_months"] == int(end_date - start_date)
        employee_data_temp = employee_data_temp.loc[mask1]
        mask2 = (
            (employee_data_temp["demographic"] == demo)
            & (employee_data_temp["freq_cap"] == fre_cap)
            & (employee_data_temp["total_incressions"] == inc)
        )
        employee_data_temp = employee_data_temp.loc[mask2]
        employee_data_temp = employee_data_temp.sort_values(by=["reach"])
        employee_data_temp["income_percent"] = (employee_data_temp["reach"] / 955000) * 100
        employee_data_temp = employee_data_temp.reset_index(drop=True)
        return employee_data_temp.to_json(date_format="iso", orient="split")

@app.callback(
    Output("intermediate-value3", "children"),
    [
        Input("month_slider", "value"),
        Input("demographics", "value"),
        Input("intermediate-value2", "children"),
        Input("intermediate-value1", "children"),
    ],
)
def get_match_overlap(month_range, demo, match_data_temp, employee_data_temp):

    overlap_match = pd.read_json(match_data_temp, orient="split")
    overlap_employee = pd.read_json(employee_data_temp, orient="split")
    some long python calculatation
    return final.to_json(date_format="iso", orient="split")

@app.callback(
    Output("example-graph2", "figure"),
    [Input("intermediate-value3", "children"), Input("intermediate-value2", "children")],
)
def update_graph(final, match_data_temp):
    if final is not None:
        dff_overlap = pd.read_json(final, orient="split")
        dff_match_data = pd.read_json(match_data_temp, orient="split")
        overlap = Scatter(
            y=dff_overlap["final"],
            x=dff_overlap["percentage"],
            name="tile",
            line=plotly.graph_objs.scatter.Line(color="red"),
            mode="lines",
        )
        layout1 = Layout(
            plot_bgcolor="#FFFFFF",
            paper_bgcolor="#FFFFFF",
            title="title",
            height=550,
            xaxis=dict(showgrid=True, showline=True, zeroline=False, fixedrange=True, title="% Campaign Completion", range=[0, 100]),
            yaxis=dict(showline=True, fixedrange=True, zeroline=False, title="Audience Reached (%)", range=[0, (reach_increment + 10)]),
            margin=plotly.graph_objs.layout.Margin(t=45, l=50, r=50),
        )

        linear = Scatter(
            y=dff_match_data["Final"],
            x=dff_match_data["percentage"],
            name="title",
            line=plotly.graph_objs.scatter.Line(color="black"),
            mode="lines",
        )
        return Figure(data=[overlap, linear], layout=layout1)

@app.callback(Output("example-graph", "figure"),
              [Input("submit_button", "n_clicks")],
              [State("intermediate-value2", "children"),
               State("Income", "value")])

def update_graph(n_clicks, employee_data_temp, inc):

    if employee_data_temp is not None:
        dff = pd.read_json(employee_data_temp, orient="split")
        trace = Scatter(
            y=dff["income_percent"], x=dff["inc"], line=plotly.graph_objs.scatter.Line(color="#1a2d46"), mode="lines"
        )
        layout1 = Layout(
            plot_bgcolor="#FFFFFF",
            paper_bgcolor="#FFFFFF",
            height=450,
            title="Digital - " + str(max_income) + " " + "%",
            xaxis=dict(showgrid=True, showline=True, zeroline=True, fixedrange=True, title="Total Income"),
            yaxis=dict(showline=True, fixedrange=True, zeroline=True, title="Income (%)"),
            margin=plotly.graph_objs.layout.Margin(t=45, l=50, r=50),
        )
        return Figure(data=[trace], layout=layout1)

</code>```

答:
Ok, a few minor things first. There are some syntax errors here, though they may not be in your original file. You have a missing ID, because id='Frequency', has a typo. Easy fix. I got numerous warnings about an incorrect prop for Dropdown, which I solved by removing the type='number' you were passing in for each dropdown option. I also changed the default return value for update_graph to an empty dictionary, which resolved another type error.

Now for bigger things. You are triggering two callbacks using the same button. The first deals with the data, and stores it in a hidden div. The second sleeps long enough to allow the first one to finish, and then runs on what's in the hidden div. The problem is that the second callback will pull in the contents of that hidden div as soon as it runs, and the fact that it sleeps does not change the value it works with even if that value updates before the sleep timer ends.

The fix here would be to combine callbacks. You can remove the hidden div, and simply do all the work start to finish in the single callback.

Body:
Hello I am working on a dash app for the first time and I am unable to fix
an issue that I am facing. I have a front-end that takes the user input, does some calculation, stores the result in a hidden div and then updates the graph.

The app loads fine however it runs into an error as soon as I hit the submit button. Below is the code I have written. It looks like both the callback functions triggers at the same time.

app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
    html.Div([
        html.Div([
            html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()), className="nine columns")
        ], className="three columns"),
        html.Div([
            html.Div([
                html.Div([
                    html.P("Select Month Range:"),
                ],
                    className="two columns"
                ),

                html.Div([
                    dcc.RangeSlider(
                        id='month_slider',
                        # updatemode='drag',
                        # count=1,
                        min=1,
                        max=maxmarks,
                        step=1,
                        value=[maxmarks - 1, maxmarks],
                        marks=tags,
                        pushable=1
                    ),

                ],
                    className="six columns",
                    style={})
            ],
                className="twelve columns",
                style={
                    'backgroundColor': '#EFEAEA',
                    'padding-top': '1.5em',
                    'padding-bottom': '1em'
                }),
            html.Div([
                html.Div([
                    dcc.Dropdown(
                        id='demographics',
                        options=[
                            {'label': 'All 18-49', 'value': '18-49'},
                            {'label': 'Female 25-54', 'value': '25-54F'},
                            {'label': 'All 25-54', 'value': '25-54'},
                        ],
                        placeholder="Select Demographics",
                    )
                ],
                    className="two columns",
                    style={}),
                html.Div([
                    dcc.Dropdown(
                        id='ID',
                        options=[
                            {'label': '200', 'value': 200, 'type': 'number'},
                            {'label': '250', 'value': 250, 'type': 'number'},
                            {'label': '300', 'value': 300, 'type': 'number'},
                            {'label': '350', 'value': 350, 'type': 'number'},
                            {'label': '400', 'value': 400, 'type': 'number'},
                        ],
                        placeholder="Select ID",
                    )
                ],
                    className="two columns",
                    style={}),
                html.Div([
                    dcc.Dropdown(
                        id='Income',
                        options=[
                            {'label': '50,000', 'value': 50000, 'type': 'number'},
                            {'label': '100,000', 'value': 100000, 'type': 'number'},
                            {'label': '200,000', 'value': 200000, 'type': 'number'},
                            {'label': '350,000', 'value': 350000, 'type': 'number'},
                            {'label': '500,000', 'value': 500000, 'type': 'number'},
                        ],
                        placeholder="Select Income",
                    )
                ],
                    className="two columns",
                    style={}),
                html.Div([
                    dcc.Dropdown(
                        id='Frquency',
                        options=[
                            {'label': 'None per week, 'value': 0, 'type': 'number'},
                            {'label': 'Once per Week', 'value': 1, 'type': 'number'},
                            {'label': 'Thrice per Week', 'value': 3, 'type': 'number'},
                        ],
                        placeholder="Select Frequency",
                    )
                ],
                    className="two columns",
                    style={}),
                html.Div([
                    html.Button('Submit', id='submit_button', className='twelve columns',
                                style={'background-color': '#2D91C3', 'color': 'white', 'font-size': '1em'})
                ],
                    className="two columns",
                    style={}),
            ],
                className="twelve columns",
                style={
                    'backgroundColor': '#EFEAEA',
                    'padding-top': '1em',
                    'padding-bottom': '1.5em'
                })
        ], className="nine columns", style={})
    ], className="twelve columns"),

    # dcc.graph layout

    html.Div([
        html.Div([
            dcc.Graph(id='example-graph', config={"displayModeBar": False, "scrollZoom": False})

        ],
            className="six columns",
            style={'border-right': 'thin grey solid', 'border-left': 'thin grey solid',
                   'border-top': 'thin grey solid'}),

    html.Div(id='intermediate-value1', style={'display': 'none'})
])]

@app.callback(
    Output("intermediate-value1", "children"),
    [Input("submit_button", "n_clicks")],
    [
        State("month_slider", "value"),
        State("demographics", "value"),
        State("Income", "value"),
        State("Frequency", "value"),
    ],
)
def clean_data(n_clicks, month_range, demo, inc, fre_cap):
    if n_clicks is not None and n_clicks > 0:
        employee_data_temp = employee_data.copy()
        start_date = month_range[0]
        end_date = month_range[1]
        mask1 = employee_data_temp["total_months"] == int(end_date - start_date)
        employee_data_temp = employee_data_temp.loc[mask1]
        mask2 = (
            (employee_data_temp["demographic"] == demo)
            & (employee_data_temp["freq_cap"] == fre_cap)
            & (employee_data_temp["total_incressions"] == inc)
        )
        employee_data_temp = employee_data_temp.loc[mask2]
        employee_data_temp = employee_data_temp.sort_values(by=["reach"])
        employee_data_temp["income_percent"] = (employee_data_temp["reach"] / 955000) * 100
        employee_data_temp = employee_data_temp.reset_index(drop=True)
        return employee_data_temp.to_json(date_format="iso", orient="split")
    else:
        return []

@app.callback(Output("example-graph", "figure"),
              [Input("submit_button", "n_clicks")],
              [State("intermediate-value1", "children"),
               State("Income", "value")])

def update_graph(n_clicks, employee_data_temp, inc):
    t.sleep(2)
    if n_clicks is not None and n_clicks > 0:
        dff = pd.read_json(employee_data_temp, orient="split")
        max_income = dff["income_percent"].iloc[9]
        max_income = max_income.round(2)
        trace = Scatter(
            y=dff["income_percent"], x=dff["inc"], line=plotly.graph_objs.scatter.Line(color="#1a2d46"), mode="lines"
        )
        layout1 = Layout(
            plot_bgcolor="#FFFFFF",
            paper_bgcolor="#FFFFFF",
            height=450,
            title="Digital Reach - " + str(max_income) + " " + "%",
            xaxis=dict(showgrid=True, showline=True, zeroline=True, fixedrange=True, title="Total Income"),
            yaxis=dict(showline=True, fixedrange=True, zeroline=True, title="Income (%)"),
            margin=plotly.graph_objs.layout.Margin(t=45, l=50, r=50),
        )
        return Figure(data=[trace], layout=layout1)
    else:
        return []

Below is the error I get:

Traceback (most recent call last):
  File "C:\Users\Tushar\Documents\django_projects\tvnz_dash_app\src\dash_app\incrementor\views.py", line 21, in dispatcher
    response = server.full_dispatch_request()
  File "C:\python37\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\python37\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\python37\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "C:\python37\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\python37\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\python37\lib\site-packages\dash\dash.py", line 1073, in dispatch
    response.set_data(self.callback_map[output]['callback'](*args))
  File "C:\python37\lib\site-packages\dash\dash.py", line 969, in add_context
    output_value = func(*args, **kwargs)
  File "C:\Users\Tushar\Documents\django_projects\tvnz_dash_app\src\dash_app\incrementor\router.py", line 699, in update_graph
    dff = pd.read_json(employee_data_temp, orient="split")
  File "C:\python37\lib\site-packages\pandas\io\json\json.py", line 413, in read_json
    path_or_buf, encoding=encoding, compression=compression,
  File "C:\python37\lib\site-packages\pandas\io\common.py", line 232, in get_filepath_or_buffer
    raise ValueError(msg.format(_type=type(filepath_or_buffer)))
ValueError: Invalid file path or buffer object type: <class 'NoneType'>

What I want is that the function should run when a user click a submit button and as the update graph function is dependent on the clean data function it should not run until and unless the clean data function is finished completing.

Please can some one help me to figure what am I missing here and help to resolve the issue.

Thanks a lot in advance !!

NEW UPDATED FUNCTIONS

@app.callback(
    Output("intermediate-value1", "children"),
    [Input("submit_button", "n_clicks")],
    [
        State("month_slider", "value"),
        State("demographics", "value"),
        State("digital_impressions", "value"),
        State("digital_frequency", "value"),
    ],
)

def get_match(n_clicks, month_range, demo, tarps):
    if n_clicks is not None and n_clicks > 0:
        some long python script data calculatation
        return match_data_temp.to_json(date_format="iso", orient="split")

@app.callback(
    Output("intermediate-value2", "children"),
    [Input("submit_button", "n_clicks")],
    [
        State("month_slider", "value"),
        State("demographics", "value"),
        State("digital_impressions", "value"),
        State("digital_frequency", "value"),
    ],
)

def clean_data(n_clicks, month_range, demo, inc, fre_cap):
    if n_clicks is not None and n_clicks > 0:
        employee_data_temp = employee_data.copy()
        start_date = month_range[0]
        end_date = month_range[1]
        mask1 = employee_data_temp["total_months"] == int(end_date - start_date)
        employee_data_temp = employee_data_temp.loc[mask1]
        mask2 = (
            (employee_data_temp["demographic"] == demo)
            & (employee_data_temp["freq_cap"] == fre_cap)
            & (employee_data_temp["total_incressions"] == inc)
        )
        employee_data_temp = employee_data_temp.loc[mask2]
        employee_data_temp = employee_data_temp.sort_values(by=["reach"])
        employee_data_temp["income_percent"] = (employee_data_temp["reach"] / 955000) * 100
        employee_data_temp = employee_data_temp.reset_index(drop=True)
        return employee_data_temp.to_json(date_format="iso", orient="split")

@app.callback(
    Output("intermediate-value3", "children"),
    [
        Input("month_slider", "value"),
        Input("demographics", "value"),
        Input("intermediate-value2", "children"),
        Input("intermediate-value1", "children"),
    ],
)
def get_match_overlap(month_range, demo, match_data_temp, employee_data_temp):

    overlap_match = pd.read_json(match_data_temp, orient="split")
    overlap_employee = pd.read_json(employee_data_temp, orient="split")
    some long python calculatation
    return final.to_json(date_format="iso", orient="split")

@app.callback(
    Output("example-graph2", "figure"),
    [Input("intermediate-value3", "children"), Input("intermediate-value2", "children")],
)
def update_graph(final, match_data_temp):
    if final is not None:
        dff_overlap = pd.read_json(final, orient="split")
        dff_match_data = pd.read_json(match_data_temp, orient="split")
        overlap = Scatter(
            y=dff_overlap["final"],
            x=dff_overlap["percentage"],
            name="tile",
            line=plotly.graph_objs.scatter.Line(color="red"),
            mode="lines",
        )
        layout1 = Layout(
            plot_bgcolor="#FFFFFF",
            paper_bgcolor="#FFFFFF",
            title="title",
            height=550,
            xaxis=dict(showgrid=True, showline=True, zeroline=False, fixedrange=True, title="% Campaign Completion", range=[0, 100]),
            yaxis=dict(showline=True, fixedrange=True, zeroline=False, title="Audience Reached (%)", range=[0, (reach_increment + 10)]),
            margin=plotly.graph_objs.layout.Margin(t=45, l=50, r=50),
        )

        linear = Scatter(
            y=dff_match_data["Final"],
            x=dff_match_data["percentage"],
            name="title",
            line=plotly.graph_objs.scatter.Line(color="black"),
            mode="lines",
        )
        return Figure(data=[overlap, linear], layout=layout1)

@app.callback(Output("example-graph", "figure"),
              [Input("submit_button", "n_clicks")],
              [State("intermediate-value2", "children"),
               State("Income", "value")])

def update_graph(n_clicks, employee_data_temp, inc):

    if employee_data_temp is not None:
        dff = pd.read_json(employee_data_temp, orient="split")
        trace = Scatter(
            y=dff["income_percent"], x=dff["inc"], line=plotly.graph_objs.scatter.Line(color="#1a2d46"), mode="lines"
        )
        layout1 = Layout(
            plot_bgcolor="#FFFFFF",
            paper_bgcolor="#FFFFFF",
            height=450,
            title="Digital - " + str(max_income) + " " + "%",
            xaxis=dict(showgrid=True, showline=True, zeroline=True, fixedrange=True, title="Total Income"),
            yaxis=dict(showline=True, fixedrange=True, zeroline=True, title="Income (%)"),
            margin=plotly.graph_objs.layout.Margin(t=45, l=50, r=50),
        )
        return Figure(data=[trace], layout=layout1)


问:
How do I get a button to run a function in a fragment?
I have a fragment and I want a button to run the function Calculate() when I press it. My fragment is also based from one of the templates.

I've tried the XML android:onClick thing, though I assume its looking inside MainActivity instead of the Fragment so it throws an error.
I've also followed trying to use an OnClickListener from another post, though setting it up (as in code inside OnCreateCiew) gave errors, though it might just be my amateur knowledge of how it works.

This is my calculate function (the function I'm trying to get to run when my button is clicked), which is inside the fragment activity:

    public void Calculate(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }
```

<p>If needed, heres the whole fragment activity</p>

<p>When using the XML onclick, my app just crashes when the button is pressed.
When using OnClickListener, I can't even compile because of errors.
I don't have much coding expertise to know what the template fragment code is doing, but I assume its conflicting with however I'm setting up the OnClickListener.</p>

<p>Here's how I tried to set up my OnClickListener:</p>

```    Button calculatebutton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View kinematicsCalculatorView = inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);
        calculatebutton = (Button) kinematicsCalculatorView.findViewById(R.id.calculateButton);
        calculatebutton.setOnClickListener(this);
        return kinematicsCalculatorView;
        // Inflate the layout for this fragment
       // return inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);

    }

    public void onClick(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }
```

However, the this in calculatebutton.setOnClickListener(this); shows up as an error, (setOnClickListener(android.view.View.OnClickListener) in View cannot be applied to (com.example.myApp.FragmentCalculatorKinematics)). onClick method is shown as never being used.

答:
You need to implement View.OnClickListener interface to your fragment class.

Here's a snippet of code.

```<code>public class MyFragment extends Fragment implements View.OnClickListener{  // implements the View.OnClickListener interface here

Button calculatebutton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View kinematicsCalculatorView = inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);
    calculatebutton = (Button) kinematicsCalculatorView.findViewById(R.id.calculateButton);
    calculatebutton.setOnClickListener(this);
    return kinematicsCalculatorView;
    // Inflate the layout for this fragment
   // return inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);

}

public void onClick(View v) {
    switch(v.getId()){  // getting the id of clicked item.
       case R.id.calculateButton:  // When the button will pressed.
         EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
        break;
    }
}}
</code>```

Hope this will work for you.

Body:
I have a fragment and I want a button to run the function Calculate() when I press it. My fragment is also based from one of the templates.

I've tried the XML android:onClick thing, though I assume its looking inside MainActivity instead of the Fragment so it throws an error.
I've also followed trying to use an OnClickListener from another post, though setting it up (as in code inside OnCreateCiew) gave errors, though it might just be my amateur knowledge of how it works.

This is my calculate function (the function I'm trying to get to run when my button is clicked), which is inside the fragment activity:

    public void Calculate(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }

If needed, heres the whole fragment activity

When using the XML onclick, my app just crashes when the button is pressed.
When using OnClickListener, I can't even compile because of errors.
I don't have much coding expertise to know what the template fragment code is doing, but I assume its conflicting with however I'm setting up the OnClickListener.

Here's how I tried to set up my OnClickListener:

    Button calculatebutton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View kinematicsCalculatorView = inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);
        calculatebutton = (Button) kinematicsCalculatorView.findViewById(R.id.calculateButton);
        calculatebutton.setOnClickListener(this);
        return kinematicsCalculatorView;
        // Inflate the layout for this fragment
       // return inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);

    }

    public void onClick(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }

However, the this in calculatebutton.setOnClickListener(this); shows up as an error, (setOnClickListener(android.view.View.OnClickListener) in View cannot be applied to (com.example.myApp.FragmentCalculatorKinematics)). onClick method is shown as never being used.

Body:
You need to implement View.OnClickListener interface to your fragment class.

Here's a snippet of code.

public class MyFragment extends Fragment implements View.OnClickListener{  // implements the View.OnClickListener interface here

Button calculatebutton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View kinematicsCalculatorView = inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);
    calculatebutton = (Button) kinematicsCalculatorView.findViewById(R.id.calculateButton);
    calculatebutton.setOnClickListener(this);
    return kinematicsCalculatorView;
    // Inflate the layout for this fragment
   // return inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);

}

public void onClick(View v) {
    switch(v.getId()){  // getting the id of clicked item.
       case R.id.calculateButton:  // When the button will pressed.
         EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
        break;
    }
}}

Hope this will work for you.


问:
Set back default floating point print precision in C++
I want to control the precision for a double during a comparison, and then come back to default precision, with C++.

I intend to use setPrecision() to set precision. What is then syntax, if any, to set precision back to default?

I am doing something like this

```<code>std::setPrecision(math.log10(m_FTOL));
</code>```

I do some stuff, and I would like to come back to default double comparison right afterwards.

I modified like this, and I still have some errors

```<code>std::streamsize prec = std::ios_base::precision();
std::setprecision(cmath::log10(m_FTOL));
</code>```

with cmath false at compilation, and std::ios_base also false at compilation. Could you help?

答: You can use cout << setprecision(-1)

Body:
I want to control the precision for a double during a comparison, and then come back to default precision, with C++.

I intend to use setPrecision() to set precision. What is then syntax, if any, to set precision back to default?

I am doing something like this

std::setPrecision(math.log10(m_FTOL));

I do some stuff, and I would like to come back to default double comparison right afterwards.

I modified like this, and I still have some errors

std::streamsize prec = std::ios_base::precision();
std::setprecision(cmath::log10(m_FTOL));

with cmath false at compilation, and std::ios_base also false at compilation. Could you help?

Body: You can use cout << setprecision(-1)


问:
gettimeofday() does not fill its timeval argument
I'm testing if I could use gettimeofday() to measure the performance of a piece of code.

```<code>#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>

int main() {
  struct timeval *tp_begin;
  gettimeofday(tp_begin, NULL);
  if (tp_begin == NULL) printf("tp_begin: Strange...\n");

  struct timeval *tp_end;
  gettimeofday(tp_end, NULL);
  if (tp_end == NULL) printf("tp_end: Strange...\n");

  return 0;
}
</code>```

This code compiles (with gcc -g test.c -o test), and I would expect nothing to be printed stdout, but here's the output:

```<code>tp_end: Strange...
</code>```

I've tried running this multiple times, but the result is always the same. What's going on here?

答:
You are passing an uninitialized pointer to the function.  The result could be anything at all, it is undefined behavior.

To get a result from gettimeofday, you are required to pass a valid pointer to a buffer which the function will fill in.  The function does not provide the buffer (it couldn't even if it wanted to, because the pointer argument is passed by value).

Body:
I'm testing if I could use gettimeofday() to measure the performance of a piece of code.

#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>

int main() {
  struct timeval *tp_begin;
  gettimeofday(tp_begin, NULL);
  if (tp_begin == NULL) printf("tp_begin: Strange...\n");

  struct timeval *tp_end;
  gettimeofday(tp_end, NULL);
  if (tp_end == NULL) printf("tp_end: Strange...\n");

  return 0;
}

This code compiles (with gcc -g test.c -o test), and I would expect nothing to be printed stdout, but here's the output:

tp_end: Strange...

I've tried running this multiple times, but the result is always the same. What's going on here?


问:
Understanding the mask function in python
Hi Can someone please tell me the meaning of the following code

```<code>df.mask(df.sub(df.mean()).div(df.std()).abs().gt(2))
</code>```

What I'm trying to do is replacing the outliers with NaN values. This is what I found but I'm not so clear what it does

答:
That's a lot of chained method calls.

Basically, it calculates the mean of each column of df, then subtracts this mean from the elements in the corresponding columns. Then, it calculates the standard deviation, and divides by it, again column-wise. Finally, it masks (converts to nan) all values greater than 2.

This process is known as "standardisation" - converting values into a multiple of their distance from the mean, in terms of the standard deviation. Here, presumably, we consider all values more than two standard deviations outliers, and remove them from the dataset.

However, perhaps something like this, which mixes operators and method calls, might be more readable...?

```<code>df.mask(((df - df.mean()) / df.std()).abs() > 2)
</code>```

Body:
Hi Can someone please tell me the meaning of the following code

df.mask(df.sub(df.mean()).div(df.std()).abs().gt(2))

What I'm trying to do is replacing the outliers with NaN values. This is what I found but I'm not so clear what it does

Body:
That's a lot of chained method calls.

Basically, it calculates the mean of each column of df, then subtracts this mean from the elements in the corresponding columns. Then, it calculates the standard deviation, and divides by it, again column-wise. Finally, it masks (converts to nan) all values greater than 2.

This process is known as "standardisation" - converting values into a multiple of their distance from the mean, in terms of the standard deviation. Here, presumably, we consider all values more than two standard deviations outliers, and remove them from the dataset.

However, perhaps something like this, which mixes operators and method calls, might be more readable...?

df.mask(((df - df.mean()) / df.std()).abs() > 2)