问:
How Can I Update the activity(ListView) - android
I am using services and broadcast receiver, to launch a listview (I am using only two activity classes first as first class starts it starts service with it..in the services  hitting a webservice and parsing data, n passing data into the broadcast receiver,
now the data I am getting in onreceive, and storing that data into another data...now I want this data to access in my activity class which I wl use for listView...please tell how can I do it..without making that var. static.

I also tried this thing within another way please if it is possible in that way too.

There the first screen is getting launch there I kept one button as I click on the button service will start n will do the whole job as I wrote above.....but here as I click the button another activity is being launched which is that listview but that isn't extending listActivity that is extending activity.

so I want to update that list view dynamically how can I do this?

please, any Help is Appreciable.

my code is here where I am getting stuck

```<code>public class MessageList extends Activity {
 public static final String TAG = MessageList.class.getSimpleName();

 Context mContext;
 public static ArrayList<String> mData;

 public ListView mListView;
 private List<Message> messages;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.maina);
  System.out.println("check bro"+mData);

  System.out.println("In OnCreate of Messagelist class");

  System.out.println("1st");

  System.out.println("3rd");
  mListView = (ListView) findViewById(R.id.mylist);
  PlaceAdapter adapter = new PlaceAdapter(this, mData);
  mListView.setAdapter(adapter);
 }

 private OnItemClickListener mItemClickListener = new OnItemClickListener() {
  @Override
  public void onItemClick(android.widget.AdapterView<?> arg0, View arg1, int arg2, long arg3) {
   Intent viewMessage = new Intent(Intent.ACTION_VIEW,Uri.parse(messages.get(arg2).getLink().toExternalForm()));
   startActivity(viewMessage);
  }
 };

 /* @Override
  protected void onListItemClick(ListView l, View v, int position, long id)
  {
  super.onListItemClick(l, v, position, id);
  Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(messages
  .get(position).getLink().toExternalForm()));
  this.startActivity(viewMessage);
  }*/

 class MessageListBroadCast extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
   System.out.println("hello");
   System.out.println("final Done");
   Bundle bundle = intent.getExtras();
   mData = bundle.getStringArrayList("keya");
   Log.d(TAG, "" + mData);

   intent.putExtra("name", mData);

  }

 };
}
</code>```

that message list is the class which is a list view
Thanks

答: Rather than working like this, I would use a class derived from CursorAdapter as Adapter and let your service store its results in a ContentProvider and notify changes on your ContentResolver on the same Uri you are using in the CursorAdapter. That way it will refresh automatically and your data is not lost should anything happen with your app (crash, memory,...). But I reckon this might be a bit of overhead, it all depends on what your webservice exactly does etc.

Body:
I am using services and broadcast receiver, to launch a listview (I am using only two activity classes first as first class starts it starts service with it..in the services  hitting a webservice and parsing data, n passing data into the broadcast receiver,
now the data I am getting in onreceive, and storing that data into another data...now I want this data to access in my activity class which I wl use for listView...please tell how can I do it..without making that var. static.

I also tried this thing within another way please if it is possible in that way too.

There the first screen is getting launch there I kept one button as I click on the button service will start n will do the whole job as I wrote above.....but here as I click the button another activity is being launched which is that listview but that isn't extending listActivity that is extending activity.

so I want to update that list view dynamically how can I do this?

please, any Help is Appreciable.

my code is here where I am getting stuck

public class MessageList extends Activity {
 public static final String TAG = MessageList.class.getSimpleName();

 Context mContext;
 public static ArrayList<String> mData;

 public ListView mListView;
 private List<Message> messages;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.maina);
  System.out.println("check bro"+mData);

  System.out.println("In OnCreate of Messagelist class");

  System.out.println("1st");

  System.out.println("3rd");
  mListView = (ListView) findViewById(R.id.mylist);
  PlaceAdapter adapter = new PlaceAdapter(this, mData);
  mListView.setAdapter(adapter);
 }

 private OnItemClickListener mItemClickListener = new OnItemClickListener() {
  @Override
  public void onItemClick(android.widget.AdapterView<?> arg0, View arg1, int arg2, long arg3) {
   Intent viewMessage = new Intent(Intent.ACTION_VIEW,Uri.parse(messages.get(arg2).getLink().toExternalForm()));
   startActivity(viewMessage);
  }
 };

 /* @Override
  protected void onListItemClick(ListView l, View v, int position, long id)
  {
  super.onListItemClick(l, v, position, id);
  Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(messages
  .get(position).getLink().toExternalForm()));
  this.startActivity(viewMessage);
  }*/

 class MessageListBroadCast extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
   System.out.println("hello");
   System.out.println("final Done");
   Bundle bundle = intent.getExtras();
   mData = bundle.getStringArrayList("keya");
   Log.d(TAG, "" + mData);

   intent.putExtra("name", mData);

  }

 };
}

that message list is the class which is a list view
Thanks


来源: stackexchange

问:
How to pass arguments to an included file?
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

```<code><?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

<body>
.....
..
.
</code>```

header.php

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
</code>```

Obviously this doesn't work; how can I pass arguments to an included file?

答:
you are over thinking it

```<code><?php
$header = "aaaaaaaaaaaaaaaaa";
include("header.php");
?>
</code>```

::EDIT::

Decided I would add value

The included file will gain the scope of where you included it. So if you include a file INSIDE a function:

```<code><?php
$get_me = "yes";
function haha()
{
include("file.php");
}
haha();

// And file.php looks like

echo $get_me; // notice + blank

?>
</code>```

More over, you include the same file more than once to great effect.

```<code><?php

$output = "this";
include("cool_box.php");

$output = "will";
include("cool_box.php");

$output = "work";
include("cool_box.php");

?>
</code>```

And even use this to load templates that become part of a method in a class. So you can do something like:

```<code><?php

class template
{

    private $name;

    function __construct($name)
    {
        $this->name = preg_replace("/[^a-zA-Z0-9]/", "", $name);
    }

    function output(array $vars)
    {
        include($this->name.".php"); // Where $vars is an expected array of possible data
    }

}

$head = new template("header");
$body = new template("body");
$head->output();
$head->output(array("content" => "this is a cool page"));

?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

.....
..
.

header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="shortcut icon" href="favicon.ico">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />

Obviously this doesn't work; how can I pass arguments to an included file?

Body:
you are over thinking it

<?php
$header = "aaaaaaaaaaaaaaaaa";
include("header.php");
?>

::EDIT::

Decided I would add value

The included file will gain the scope of where you included it. So if you include a file INSIDE a function:

<?php
$get_me = "yes";
function haha()
{
include("file.php");
}
haha();

// And file.php looks like

echo $get_me; // notice + blank

?>

More over, you include the same file more than once to great effect.

<?php

$output = "this";
include("cool_box.php");

$output = "will";
include("cool_box.php");

$output = "work";
include("cool_box.php");

?>

And even use this to load templates that become part of a method in a class. So you can do something like:

<?php

class template
{

    private $name;

    function __construct($name)
    {
        $this->name = preg_replace("/[^a-zA-Z0-9]/", "", $name);
    }

    function output(array $vars)
    {
        include($this->name.".php"); // Where $vars is an expected array of possible data
    }

}

$head = new template("header");
$body = new template("body");
$head->output();
$head->output(array("content" => "this is a cool page"));

?>


问:
How to configure log4j 2 to asynchonous mode programmatically?
I've found several examples of programmatic configuration, but none of those mention asynchronous logging.
How can I configure log4j 2 to make all loggers asynchronous?
Just to be clear: I can't make it by setting the System property. What I need is something like this: How to configure log4j 2.x purely programmatically?</p>

答:
If you can't use system property and log4j2.component.properties file. You can try the ConfigurationFactory.setConfigurationFactory method.

Here's a brief example:

Log4j2.java

```<code>public class Log4j2 {

  static {
    ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory()); // This must be called before any other calls to Log4j
  }

  private static Logger logger = LogManager.getLogger();

  public static void main(String[] args) {
    logger.info("hello");
  }
}
</code>```

CustomConfigurationFactory.java

```<code>@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(50)
public class CustomConfigurationFactory extends ConfigurationFactory {

  private static Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);

    AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").
        addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.newLayout("PatternLayout").
        addAttribute("pattern", "%level: %msg%n"));
    builder.add(appenderBuilder);

    RootLoggerComponentBuilder rootLoggerBuilder = builder.newAsyncRootLogger(Level.DEBUG); // use newAsyncRootLogger instead of newRootLogger
    rootLoggerBuilder.add(builder.newAppenderRef("Stdout"));

    builder.add(rootLoggerBuilder);
    return builder.build();
  }

  @Override
  public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
    return getConfiguration(loggerContext, source.toString(), null);
  }

  @Override
  public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
    ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
    return createConfiguration(name, builder);
  }

  @Override
  protected String[] getSupportedTypes() {
    return new String[]{"*"};
  }
}
</code>```

Hope this helps :-)

ContentLicense: CC BY-SA 3.0

Body:
If you can't use system property and log4j2.component.properties file. You can try the ConfigurationFactory.setConfigurationFactory method.

Here's a brief example:

Log4j2.java

public class Log4j2 {

  static {
    ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory()); // This must be called before any other calls to Log4j
  }

  private static Logger logger = LogManager.getLogger();

  public static void main(String[] args) {
    logger.info("hello");
  }
}

CustomConfigurationFactory.java

@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(50)
public class CustomConfigurationFactory extends ConfigurationFactory {

  private static Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);

    AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").
        addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.newLayout("PatternLayout").
        addAttribute("pattern", "%level: %msg%n"));
    builder.add(appenderBuilder);

    RootLoggerComponentBuilder rootLoggerBuilder = builder.newAsyncRootLogger(Level.DEBUG); // use newAsyncRootLogger instead of newRootLogger
    rootLoggerBuilder.add(builder.newAppenderRef("Stdout"));

    builder.add(rootLoggerBuilder);
    return builder.build();
  }

  @Override
  public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
    return getConfiguration(loggerContext, source.toString(), null);
  }

  @Override
  public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
    ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
    return createConfiguration(name, builder);
  }

  @Override
  protected String[] getSupportedTypes() {
    return new String[]{"*"};
  }
}

Hope this helps :-)


问:
Gsutil downloading Android review stats csv files as binary
I'm trying to download the review data for my Android app.

But the files gsutil downloads are not text files!

FWIW, I'm running Ubuntu 14.04 with gsutil 4.7.

Below is an example

```<code>stats$ gsutil cat gs://pubsite_prod_rev_xxxxxxxxx/stats/ratings/ratings_com.yyyyyyyyyy_201501_overview.csv
��
�@��uO�X���]]GD/ �FP_G�%�fם���9;:��
                                            �� �5�����sv���g�T��S;�����v�jZ}�={H0B�y�cD~M�O���wC���2F����ZI��9�.p�wM�e��p�3���Rj#^�,�²Ԍ��bY�V`�jy���^�X-�p�2��b�&jg8�+�uV�|�~�N߰����xY:}��_��t�F[�,�������F���xY:}�aY�e���|U:
</code>```

答:
It's likely utf-16 encoded. You can run this to convert on the Mac:

```<code>iconv -f UTF-16 <file>.csv
</code>```

Google unfortunately makes it much more complicated to get reviews than Apple does with their RSS feeds…

Body:
I'm trying to download the review data for my Android app.

But the files gsutil downloads are not text files!

FWIW, I'm running Ubuntu 14.04 with gsutil 4.7.

Below is an example

stats$ gsutil cat gs://pubsite_prod_rev_xxxxxxxxx/stats/ratings/ratings_com.yyyyyyyyyy_201501_overview.csv
��
�@��uO�X���]]GD/ �FP_G�%�fם���9;:��
                                            �� �5�����sv���g�T��S;�����v�jZ}�={H0B�y�cD~M�O���wC���2F����ZI��9�.p�wM�e��p�3���Rj#^�,�²Ԍ��bY�V`�jy���^�X-�p�2��b�&jg8�+�uV�|�~�N߰����xY:}��_��t�F[�,�������F���xY:}�aY�e���|U:

Body:
It's likely utf-16 encoded. You can run this to convert on the Mac:

iconv -f UTF-16 <file>.csv

Google unfortunately makes it much more complicated to get reviews than Apple does with their RSS feeds…


问:
How do I know a process is blocking the reboot command in linux?
I added my packages and modules into the openwrt and then reboot doesn't work at all!!. Only way to reboot is to use reboot -f or hard reset.

I tried removing all the startup scripts from /etc/init.d which are added by me. I even tried removing the contents of /etc/modules.d/.

My /etc/rc.local file has just one line exit 0.

Where should I debug to figure this out? All these package were working earlier on x86 architecture.

Iam using openwrt chaos calmer on imx6 based board.

答:
As far as I know reboot uses the shutdown command. So when shutting down, Linux sends SIGTERMs to its processes. But the kernel protects the processes which are in uninterruptible state to preventing data loss. This may lead to stop the rebooting.

So in your case some processes (openwrt specific) may be in uninterruptible state. You can list out the process having uninterpreted state (check the STAT of the process) through ps aux command.

or you can directly list the uninterruptible state by ps -eo 'stat,pid,args' | grep -E 'D'

check Linux process states for more details about process in linux.


问:
Change icon for recorded activity from custom app in History list
I have made my own Connect IQ app for my Garmin Forerunner watch. I have changed the LauncherIcon to my own image instead of the default IQ-icon.

My app uses ActivityRecording so the activity can be saved to the list of activities in History. However, in this list the icon for the activity is just "IQ".

Is it possible to change this to a custom image? Otherwise, I won't be able to tell the activities from custom apps apart.

答: It is not possible to change the icon used for activities recorded by ConnectIQ apps.</p>


问:
HttpWebRequest returns 404s for 302s only in Internet Explorer
I have a Silverlight (v3) application that uses WebRequest to make an HTTP POST request to a webpage on the same website as the Silverlight app. This HTTP request gets back a 302 (a redirect) to another page on the same website, which HttpWebRequest is automatically supposed to follow (according to the documentation).

There's nothing particularly special about the code that makes the request (it uses the browser's HTTP stack, it is not configured to use the alternate inbuilt Silverlight HTTP stack):

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("{0}?name={1}&size={2}", _UploadUrl, Uri.EscapeUriString(Name), TotalBytes));
request.Method = "POST";
</code>```

All this works fine in Firefox and Chrome; Silverlight makes the POST HTTP request, receives a 302 response and automatically does a GET HTTP request of the specified redirect URL and returns that to me (I know this because I used Fiddler to watch the HTTP requests going on).
However, in Internet Explorer (v8), Silverlight does the POST HTTP request and then throws a WebException with a 404 error code!

Using Fiddler, I can see that Silverlight/Internet Explorer was successfully returned the 302 status code for the request, and I assume that the 404 status code (and associated WebException) that I get in Silverlight is because as far as I know HTTP requests that are done via the browser stack can only return 200 or 404 due to limitations. The real question is why does Internet Explorer not follow through the redirect like the other browsers?

Thanks in advance for any help!

EDIT: I would prefer not to use the Silverlight client HTTP stack because to my knowledge requests issued by it do not include cookies that are a part of the browser's session, critically including the ASP.NET authentication cookie that I need to be attached to the HTTP requests being made by the Silverlight control.

EDIT 2: I have discovered that Internet Explorer only exhibits this behaviour when you do a POST request. A GET request redirects successfully. This seems like pretty bad behaviour considering how many websites now do things in the Post-Redirect-Get style.

答:
IE is closer to the specification, in that in responding to a 302 for a POST the user agent should send a POST (though it should not do so without user confirmation).

On the other hand, FF and Chrome are deliberately wrong, in copying ways in which user agents were frequently wrong some considerable time ago (the problem started in the early days of HTTP).

For this reason, 307 was introduced in HTTP/1.1 to be clearer that the same HTTP method should be used (i.e. in this case, it should be a POST) while 303 has always meant that one should use GET.

Therefore, instead of doing Response.Redirect which results in a 302 - that different user agents will handle in different ways, send a 303. The following code does so (and includes a valid entity body just to be within the letter of the spec). There is an overload so you can call it with either a Uri or a string:

```<code>private void SeeOther(Uri uri)
{
  if(!uri.IsAbsoluteUri)
    uri = new Uri(Request.Url, uri);
  Response.StatusCode = 303;
  Response.AddHeader("Location", uri.AbsoluteUri);
  Response.ContentType = "text/uri-list";
  Response.Write(uri.AbsoluteUri);
  Context.ApplicationInstance.CompleteRequest();
}
private void SeeOther(string relUri)
{
  SeeOther(new Uri(Request.Url, relUri));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Silverlight (v3) application that uses WebRequest to make an HTTP POST request to a webpage on the same website as the Silverlight app. This HTTP request gets back a 302 (a redirect) to another page on the same website, which HttpWebRequest is automatically supposed to follow (according to the documentation).

There's nothing particularly special about the code that makes the request (it uses the browser's HTTP stack, it is not configured to use the alternate inbuilt Silverlight HTTP stack):

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("{0}?name={1}&size={2}", _UploadUrl, Uri.EscapeUriString(Name), TotalBytes));
request.Method = "POST";

All this works fine in Firefox and Chrome; Silverlight makes the POST HTTP request, receives a 302 response and automatically does a GET HTTP request of the specified redirect URL and returns that to me (I know this because I used Fiddler to watch the HTTP requests going on).
However, in Internet Explorer (v8), Silverlight does the POST HTTP request and then throws a WebException with a 404 error code!

Using Fiddler, I can see that Silverlight/Internet Explorer was successfully returned the 302 status code for the request, and I assume that the 404 status code (and associated WebException) that I get in Silverlight is because as far as I know HTTP requests that are done via the browser stack can only return 200 or 404 due to limitations. The real question is why does Internet Explorer not follow through the redirect like the other browsers?

Thanks in advance for any help!

EDIT: I would prefer not to use the Silverlight client HTTP stack because to my knowledge requests issued by it do not include cookies that are a part of the browser's session, critically including the ASP.NET authentication cookie that I need to be attached to the HTTP requests being made by the Silverlight control.

EDIT 2: I have discovered that Internet Explorer only exhibits this behaviour when you do a POST request. A GET request redirects successfully. This seems like pretty bad behaviour considering how many websites now do things in the Post-Redirect-Get style.

Body:
IE is closer to the specification, in that in responding to a 302 for a POST the user agent should send a POST (though it should not do so without user confirmation).

On the other hand, FF and Chrome are deliberately wrong, in copying ways in which user agents were frequently wrong some considerable time ago (the problem started in the early days of HTTP).

For this reason, 307 was introduced in HTTP/1.1 to be clearer that the same HTTP method should be used (i.e. in this case, it should be a POST) while 303 has always meant that one should use GET.

Therefore, instead of doing Response.Redirect which results in a 302 - that different user agents will handle in different ways, send a 303. The following code does so (and includes a valid entity body just to be within the letter of the spec). There is an overload so you can call it with either a Uri or a string:

private void SeeOther(Uri uri)
{
  if(!uri.IsAbsoluteUri)
    uri = new Uri(Request.Url, uri);
  Response.StatusCode = 303;
  Response.AddHeader("Location", uri.AbsoluteUri);
  Response.ContentType = "text/uri-list";
  Response.Write(uri.AbsoluteUri);
  Context.ApplicationInstance.CompleteRequest();
}
private void SeeOther(string relUri)
{
  SeeOther(new Uri(Request.Url, relUri));
}


问:
Why is exponential integrator method giving poor results?
```<code>//u' + Au = g(t,u) can be solved by exponential integrators also
//Following snippet is for exp INtegrators
A = -full(Strang(11))
A[end,1]=1;A[1,end]=1;
g(t,u) = 2-u
u0 = zeros(11);u0[6]=1
nsteps = 1000
tmax = 10.0
h = tmax/nsteps
u = u0
t = 0
for k in 1:nsteps
    u = expm(-h*A)*u + h*((expm(-h*A)-1)\(-h*A))*g(t,u)
    t = k*h
end
//this is for euler's method
for k in 1:nsteps
    u += h*(A*u + h*g(t,u))
    t = k*h
end
</code>```

Why are they giving poor results?

The method is exploding very badly, it should converge to [1.99]*11 , or something like that?

Is there any mistake while implementing Exp Integrator?

答:
The test problem is a singular matrix. A better test is the setup:

```<code>using SpecialMatrices
A = -full(Strang(11))
g(t,u) = 2-u
u = zeros(11);u[6]=1
nsteps = 10000
tmax = 1.0
h = tmax/nsteps
t = 0
</code>```

Using this, fix the h in the Euler to get (notice there's an extra h, my bad:

```<code>u = zeros(11);u[6]=1
for k in 1:nsteps
    u += h*(A*u + g(t,u))
    t = k*h
end
@show u

u = [0.93573,1.19361,1.26091,1.29627,1.34313,1.37767,1.34313,1.29627,1.26091,1.19361,0.93573]
</code>```

But to find out what's wrong, start looking at numbers. What happens A=0? Well, we know that phi(z) = (e^z - 1)/z. By L'Hopital's rule, phi(z) -> 1 as z->0. Therefore, in order for our implementation to have the same behavior, we have to have that same result. But let's check what happens:

```<code>expm(zeros(5,5))

5×5 Array{Float64,2}:
 1.0  0.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0  0.0
 0.0  0.0  1.0  0.0  0.0
 0.0  0.0  0.0  1.0  0.0
 0.0  0.0  0.0  0.0  1.0
</code>```

Notice that this gives the identity matrix. So think about the limit: if the bottom is going to zero... how can this be constant? We must have that the top is going to zero... so the top is going to I.

And that's the moment of clarity: the author meant 1 in the field that you're in. So for a matrix input, 1=I. When you realize that, you fix the code:

```<code># Norsett-Euler
u = zeros(11);u[6]=1
for k in 1:nsteps
  u = expm(h*A)*u + ((expm(h*A)-I)/A)*g(t,u)
  t = k*h
end
@show u

u = [0.935722,1.1936,1.26091,1.29627,1.34313,1.37768,1.34313,1.29627,1.26091,1.1936,0.935722]
</code>```

Moral of the story: for programming mathematics, you also have to debug your math.

Edit

Get a more efficient form one step at a time. First, try and force another varphi term:

```<code># Norsett-Euler
u = zeros(11);u[6]=1
for k in 1:nsteps
  u = (I + A*(expm(h*A)-I)/A)*u + ((expm(h*A)-I)/A)*g(t,u)
  t = k*h
end
@show u
</code>```

Now gather:

```<code># Norsett-Euler
u = zeros(11);u[6]=1
for k in 1:nsteps
  u = u + ((expm(h*A)-I)/A)*(A*u + g(t,u))
  t = k*h
end
@show u
</code>```

This is the efficient form of the method you were trying to write. Then you can cache the operator since A is constant:

```<code># Norsett-Euler
u = zeros(11);u[6]=1
phi1 = ((expm(h*A)-I)/A)
for k in 1:nsteps
  u = u + phi1*(A*u + g(t,u))
  t = k*h
end
@show u
</code>```

Body:
//u' + Au = g(t,u) can be solved by exponential integrators also
//Following snippet is for exp INtegrators
A = -full(Strang(11))
A[end,1]=1;A[1,end]=1;
g(t,u) = 2-u
u0 = zeros(11);u0[6]=1
nsteps = 1000
tmax = 10.0
h = tmax/nsteps
u = u0
t = 0
for k in 1:nsteps
    u = expm(-h*A)*u + h*((expm(-h*A)-1)\(-h*A))*g(t,u)
    t = k*h
end
//this is for euler's method
for k in 1:nsteps
    u += h*(A*u + h*g(t,u))
    t = k*h
end

Why are they giving poor results?

The method is exploding very badly, it should converge to [1.99]*11 , or something like that?

Is there any mistake while implementing Exp Integrator?

Body:
The test problem is a singular matrix. A better test is the setup:

using SpecialMatrices
A = -full(Strang(11))
g(t,u) = 2-u
u = zeros(11);u[6]=1
nsteps = 10000
tmax = 1.0
h = tmax/nsteps
t = 0

Using this, fix the h in the Euler to get (notice there's an extra h, my bad:

u = zeros(11);u[6]=1
for k in 1:nsteps
    u += h*(A*u + g(t,u))
    t = k*h
end
@show u

u = [0.93573,1.19361,1.26091,1.29627,1.34313,1.37767,1.34313,1.29627,1.26091,1.19361,0.93573]

But to find out what's wrong, start looking at numbers. What happens A=0? Well, we know that phi(z) = (e^z - 1)/z. By L'Hopital's rule, phi(z) -> 1 as z->0. Therefore, in order for our implementation to have the same behavior, we have to have that same result. But let's check what happens:

expm(zeros(5,5))

5×5 Array{Float64,2}:
 1.0  0.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0  0.0
 0.0  0.0  1.0  0.0  0.0
 0.0  0.0  0.0  1.0  0.0
 0.0  0.0  0.0  0.0  1.0

Notice that this gives the identity matrix. So think about the limit: if the bottom is going to zero... how can this be constant? We must have that the top is going to zero... so the top is going to I.

And that's the moment of clarity: the author meant 1 in the field that you're in. So for a matrix input, 1=I. When you realize that, you fix the code:

# Norsett-Euler
u = zeros(11);u[6]=1
for k in 1:nsteps
  u = expm(h*A)*u + ((expm(h*A)-I)/A)*g(t,u)
  t = k*h
end
@show u

u = [0.935722,1.1936,1.26091,1.29627,1.34313,1.37768,1.34313,1.29627,1.26091,1.1936,0.935722]

Moral of the story: for programming mathematics, you also have to debug your math.

Edit

Get a more efficient form one step at a time. First, try and force another varphi term:

# Norsett-Euler
u = zeros(11);u[6]=1
for k in 1:nsteps
  u = (I + A*(expm(h*A)-I)/A)*u + ((expm(h*A)-I)/A)*g(t,u)
  t = k*h
end
@show u

Now gather:

# Norsett-Euler
u = zeros(11);u[6]=1
for k in 1:nsteps
  u = u + ((expm(h*A)-I)/A)*(A*u + g(t,u))
  t = k*h
end
@show u

This is the efficient form of the method you were trying to write. Then you can cache the operator since A is constant:

# Norsett-Euler
u = zeros(11);u[6]=1
phi1 = ((expm(h*A)-I)/A)
for k in 1:nsteps
  u = u + phi1*(A*u + g(t,u))
  t = k*h
end
@show u


问:
Passing JSON array to view CodeIgniter through AJAX
I'm having a problem trying to pass a JSON array from my controller to the view to be able to produce a chart using chart js.
I've tried echoing the JSON from the controller and it gets the necessary values.

In my PHP file, there is an ajax call that gets data using a function in the controller.

```<code>$.ajax({
    url: "index.php/Sales/topClients",
    method: "GET",
    success: function(data){
        var parsedData = JSON.parse(data);
        console.log(parsedData[0].Name);
        var clientname = [];
        var orqty = [];

        for(var i in parsedData){
            clientname.push(parsedData[i].Name);
            orqty.push(parsedData[i].Quantity);
        }
        var chartdata= {
            labels: clientname,
            datasets:[
                {
                    label: 'Ordered Quantity',
                    backgroundColor: [
                        'rgba(231, 76, 60,0.7)',
                        'rgba(52, 152, 219,0.7)',
                        'rgba(46, 204, 113,0.7)',
                        'rgba(230, 126, 34,0.7)',
                        'rgba(155, 89, 182,0.7)',
                    ],
                    borderColor: [
                        'rgba(231, 76, 60,1.0)',
                        'rgba(52, 152, 219,1.0)',
                        'rgba(46, 204, 113,1.0)',
                        'rgba(230, 126, 34,1.0)',
                        'rgba(155, 89, 182,1.0)',
                    ],
                    borderWidth: 1,
                    data: orqty
                }
            ]
        };
        Chart.defaults.scale.ticks.beginAtZero=true;
        Chart.defaults.global.title.display= true;

        var ctx= $("#RMCanvas");
        var barGraph= new Chart(ctx,{
            type: 'bar',
            data: chartdata
        });
    },
    error: function(data){
        console.log(data);
    }
});
</code>```

This is the controller (Inventory)

```<code>public function topGoods(){
    $top5fgsold= $this -> Inventory_Model -> getTopGoods();
    echo json_encode($top5fgsold);
    //$this->load->view("SA_Home-Latest");
}
</code>```

This is the model: Inventory_Model

```<code><?php date_default_timezone_set('Asia/Manila');

class Sales_Model extends CI_Model {
    public function __construct() {
        $this->load->database();
    }
    public function getTopClients(){
        $this->db-> select("clients.ClientName, SUM(salesinvoicedetails.orderedQuantity) as q");
        $this->db         -> from("salesinvoicedetails");
        $this->db         -> join ("salesinvoice", "salesinvoicedetails.InvoiceNo = salesinvoice.InvoiceNo");
        $this->db         -> join("clients", "clients.ClientNo = salesinvoice.ClientNo");
        $this->db         -> where("salesinvoice.Status", 2);
        $this->db         -> where("OrderDate >=", " DATE_ADD(NOW(), INTERVAL -30 DAY)");
        $this->db         -> where("OrderDate <= NOW()");
        $this->db         ->group_by("1");
        $this->db         ->order_by("q", "desc");
        $this->db         ->limit(5);

        $topclientresult= $this-> db -> get();
        return $topclientresult-> result_array();
    }
}
</code>```

?>

答:
You should use dataType:"json" in you ajax method.

For example:

```<code>$.ajax({
                url: url
                type: 'GET',
                dataType: 'json',

                success: function() {

                    //your code
                },
                error: function() {
                    //your code
                }
            });
</code>```

Body:
I'm having a problem trying to pass a JSON array from my controller to the view to be able to produce a chart using chart js.
I've tried echoing the JSON from the controller and it gets the necessary values.

In my PHP file, there is an ajax call that gets data using a function in the controller.

$.ajax({
    url: "index.php/Sales/topClients",
    method: "GET",
    success: function(data){
        var parsedData = JSON.parse(data);
        console.log(parsedData[0].Name);
        var clientname = [];
        var orqty = [];

        for(var i in parsedData){
            clientname.push(parsedData[i].Name);
            orqty.push(parsedData[i].Quantity);
        }
        var chartdata= {
            labels: clientname,
            datasets:[
                {
                    label: 'Ordered Quantity',
                    backgroundColor: [
                        'rgba(231, 76, 60,0.7)',
                        'rgba(52, 152, 219,0.7)',
                        'rgba(46, 204, 113,0.7)',
                        'rgba(230, 126, 34,0.7)',
                        'rgba(155, 89, 182,0.7)',
                    ],
                    borderColor: [
                        'rgba(231, 76, 60,1.0)',
                        'rgba(52, 152, 219,1.0)',
                        'rgba(46, 204, 113,1.0)',
                        'rgba(230, 126, 34,1.0)',
                        'rgba(155, 89, 182,1.0)',
                    ],
                    borderWidth: 1,
                    data: orqty
                }
            ]
        };
        Chart.defaults.scale.ticks.beginAtZero=true;
        Chart.defaults.global.title.display= true;

        var ctx= $("#RMCanvas");
        var barGraph= new Chart(ctx,{
            type: 'bar',
            data: chartdata
        });
    },
    error: function(data){
        console.log(data);
    }
});

This is the controller (Inventory)

public function topGoods(){
    $top5fgsold= $this -> Inventory_Model -> getTopGoods();
    echo json_encode($top5fgsold);
    //$this->load->view("SA_Home-Latest");
}

This is the model: Inventory_Model

<?php date_default_timezone_set('Asia/Manila');

class Sales_Model extends CI_Model {
    public function __construct() {
        $this->load->database();
    }
    public function getTopClients(){
        $this->db-> select("clients.ClientName, SUM(salesinvoicedetails.orderedQuantity) as q");
        $this->db         -> from("salesinvoicedetails");
        $this->db         -> join ("salesinvoice", "salesinvoicedetails.InvoiceNo = salesinvoice.InvoiceNo");
        $this->db         -> join("clients", "clients.ClientNo = salesinvoice.ClientNo");
        $this->db         -> where("salesinvoice.Status", 2);
        $this->db         -> where("OrderDate >=", " DATE_ADD(NOW(), INTERVAL -30 DAY)");
        $this->db         -> where("OrderDate <= NOW()");
        $this->db         ->group_by("1");
        $this->db         ->order_by("q", "desc");
        $this->db         ->limit(5);

        $topclientresult= $this-> db -> get();
        return $topclientresult-> result_array();
    }
}

?>

Body:
You should use dataType:"json" in you ajax method.

For example:

$.ajax({
                url: url
                type: 'GET',
                dataType: 'json',

                success: function() {

                    //your code
                },
                error: function() {
                    //your code
                }
            });


问:
Iterate through populated rows, Match based on criteria, add value to specific cell in another sheet in Excel using VBA
I am trying to select a value in column hours in tab Time and put it in the appropriate column in tab Month. I would like to iterate through every row in sheet Time and add all of the Data to tab Month.

For every line in Tab TIME add the Hours to the appropriate engagement in Tab Month based on Engagement Number, Engagement Phase, Staff Level. I do this manually every month. I create a copy of last months tab and add on to that each month. Most columns have cells with something like this in them: =1+3+6+4+14+5+2+5 which are the hours that have been worked on that engagement. For cells with something in them i would just like to add on to what is there. For cells with nothing in them i would like to make the new value: = 1 if the value was 1. I want to automate this as it takes up a few days every first of the month, This one just so happens to be on a weekend so guess what I'll be doing. :)

This is where I am at.

```<code>Sub Recon()

'Macro to add time to reconciliation report

'Declare variables

Dim Last_Row_TIME As Double
Dim Last_Row_MONTH As Double
Dim wb As Workbook
Dim ws As Worksheet
Dim rw As Range
Dim wstime As

Set wb = ActiveWorkbook
Set wstime = Sheets("TIME")
Set wsmonth = Sheets("MONTH")

wstime.Select

'Find the last non-blank cell in column A(1)
Last_Row_wstime = wstime.Cells(Rows.Count, 1).End(xlUp).Row

'Find the first blank cell in column A
First_Empty_Row_wstime = Last_Row_wstime + 1

I_Col = 1

For i = 1 To Last_Row_wstime

For Each rw In wstime.Rows

If wstime.Cells(rw.Row,1).Value = wsmonth.Cells(rw.Row, 3).Value
And

End Sub
</code>```

I am stuck at the if statement and not sure how to make this work.

```<code>IF
TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = PARTNER or MANAGING DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Partner/MD (Column I)

'If blank then "=TIME.Hours) elseif add to the previous value "previous     addition statement +(hours)"

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SR. MANAGER/DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Director (Column J)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = MANAGER

THEN

Add Value TIME.Hours (Column Y) to  Month.Manager (Column K)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SENIOR ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Sr.Assoc (Column L)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Associate (Column M)

ELSEIF

'Create a new line after the biggest primary key, located in Month.Primary Key (Column A)

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Eng. Description (Column B) = Month.Project Name (Column D)

End If
</code>```

答:
This is a very brave effort you have made. I shall be glad to help you, but for the moment I don't understand what you want. As far as my understanding goes, I have written code as follows.

```<code>Sub Recon()
    ' Macro to add time to reconciliation report
    ' 01 Apr 2017

    Dim Wb As Workbook
    Dim WsTime As Worksheet, WsMonth As Worksheet
    Dim Crit As String                          ' Search criterium
    Dim Rl As Long                              ' last row (Time)
    Dim R As Long                               ' row counter (Time)

    With WsTime
        Rl = .Cells(.Rows.Count, 1).End(xlUp).Row
        For R = 2 To Rl                         ' skip captions row
            Crit = .Cells(R, 1).Value
            Debug.Print Crit                    ' print value to Immediate Window (for testing)
        Next R
    End With
End Sub
</code>```

In fact, this code goes further than my understanding because it presumes that both worksheets are in the same workbook. It presumes that the workbook containing those two sheets will be the active workbook. The implication is that the code might be in another workbook, perhaps one you keep for having the code in it.

Now, proceeding in somewhat smaller steps than you would probably like, the above code loops through all rows in the Time worksheet and finds the value in column A. Just so that you see if it works, it prints these values to the Immediate Window (Ctrl+G, if it isn't shown in your VBE window).

And this is where it gets murky: I presume that this value must be name, perhaps, and you now need to find that same name in the Month sheet. For that one would need to know the column in the Month sheet where that name might be found, what to do if it is found, and what to do if it isn't found.

Body:
I am trying to select a value in column hours in tab Time and put it in the appropriate column in tab Month. I would like to iterate through every row in sheet Time and add all of the Data to tab Month.

For every line in Tab TIME add the Hours to the appropriate engagement in Tab Month based on Engagement Number, Engagement Phase, Staff Level. I do this manually every month. I create a copy of last months tab and add on to that each month. Most columns have cells with something like this in them: =1+3+6+4+14+5+2+5 which are the hours that have been worked on that engagement. For cells with something in them i would just like to add on to what is there. For cells with nothing in them i would like to make the new value: = 1 if the value was 1. I want to automate this as it takes up a few days every first of the month, This one just so happens to be on a weekend so guess what I'll be doing. :)

This is where I am at.

Sub Recon()

'Macro to add time to reconciliation report

'Declare variables

Dim Last_Row_TIME As Double
Dim Last_Row_MONTH As Double
Dim wb As Workbook
Dim ws As Worksheet
Dim rw As Range
Dim wstime As

Set wb = ActiveWorkbook
Set wstime = Sheets("TIME")
Set wsmonth = Sheets("MONTH")

wstime.Select

'Find the last non-blank cell in column A(1)
Last_Row_wstime = wstime.Cells(Rows.Count, 1).End(xlUp).Row

'Find the first blank cell in column A
First_Empty_Row_wstime = Last_Row_wstime + 1

I_Col = 1

For i = 1 To Last_Row_wstime

For Each rw In wstime.Rows

If wstime.Cells(rw.Row,1).Value = wsmonth.Cells(rw.Row, 3).Value
And

End Sub

I am stuck at the if statement and not sure how to make this work.

IF
TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = PARTNER or MANAGING DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Partner/MD (Column I)

'If blank then "=TIME.Hours) elseif add to the previous value "previous     addition statement +(hours)"

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SR. MANAGER/DIRECTOR

THEN

Add Value TIME.Hours (Column Y) to  Month.Director (Column J)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = MANAGER

THEN

Add Value TIME.Hours (Column Y) to  Month.Manager (Column K)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = SENIOR ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Sr.Assoc (Column L)

ELSEIF

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Staff Level (Column M) = ASSOCIATE

THEN

Add Value TIME.Hours (Column Y) to  Month.Associate (Column M)

ELSEIF

'Create a new line after the biggest primary key, located in Month.Primary Key (Column A)

TIME.Eng. No. (Column A) = Month.Eng. No (Column B)
AND
TIME.Eng. Phase (Column C)  = Month.Eng.Phase (Column C)
AND
TIME.Eng. Description (Column B) = Month.Project Name (Column D)

End If

Body:
This is a very brave effort you have made. I shall be glad to help you, but for the moment I don't understand what you want. As far as my understanding goes, I have written code as follows.

Sub Recon()
    ' Macro to add time to reconciliation report
    ' 01 Apr 2017

    Dim Wb As Workbook
    Dim WsTime As Worksheet, WsMonth As Worksheet
    Dim Crit As String                          ' Search criterium
    Dim Rl As Long                              ' last row (Time)
    Dim R As Long                               ' row counter (Time)

    With WsTime
        Rl = .Cells(.Rows.Count, 1).End(xlUp).Row
        For R = 2 To Rl                         ' skip captions row
            Crit = .Cells(R, 1).Value
            Debug.Print Crit                    ' print value to Immediate Window (for testing)
        Next R
    End With
End Sub

In fact, this code goes further than my understanding because it presumes that both worksheets are in the same workbook. It presumes that the workbook containing those two sheets will be the active workbook. The implication is that the code might be in another workbook, perhaps one you keep for having the code in it.

Now, proceeding in somewhat smaller steps than you would probably like, the above code loops through all rows in the Time worksheet and finds the value in column A. Just so that you see if it works, it prints these values to the Immediate Window (Ctrl+G, if it isn't shown in your VBE window).

And this is where it gets murky: I presume that this value must be name, perhaps, and you now need to find that same name in the Month sheet. For that one would need to know the column in the Month sheet where that name might be found, what to do if it is found, and what to do if it isn't found.


问:
Is it possible to read the previous state of a row in a transaction?
I have .NET code that creates a transaction and in this transaction, it performs an insert/update followed by validation.  If validation fails, an exception is thrown to rollback changes.

I need add an validation rule to this VB.NET code that require checking the current state and the previous state of a row (ie: the state before the insert/update). Basically my validation rule allows a state transition from A->B but not B->A.

How can I query the state of the row outside of the current transaction? In other words, can I query the state of the row before the insert/update?

答:
You could also create a stored procedure with return values. Inside the stored procedure you should first select the row you want to update, assign the variables you wan't to return, continue with your update (you could also validate here), and then return the assigned variables like this:</p>

```<code>DECLARE @MyTableVar table(Name varchar(50),Age int);
DECLARE @Name,
        @Age
BEGIN
    SET @Name = (SELECT Name from YourTable WHERE ID=1)
    SET @Age = (SELECT Age from YourTable WHERE ID=1)

    -- Here goes your update statement..

END

RETURN @MyTableVar
</code>```

Body:
You could also create a stored procedure with return values. Inside the stored procedure you should first select the row you want to update, assign the variables you wan't to return, continue with your update (you could also validate here), and then return the assigned variables like this:

DECLARE @MyTableVar table(Name varchar(50),Age int);
DECLARE @Name,
        @Age
BEGIN
    SET @Name = (SELECT Name from YourTable WHERE ID=1)
    SET @Age = (SELECT Age from YourTable WHERE ID=1)

    -- Here goes your update statement..

END

RETURN @MyTableVar


问:
Run jQuery Counter with value from MySQL
I have jQuery counter which move numbers from one fixed number to other fixed number. But I want to create the Counter which end at number which come from MySQL database.

Counter Function Code:

Now It starts value from 99950 and end value is 100000 but I want to change end value. It should be the value which I fetch from mysql.

```<code><script type="text/javascript">

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

jQuery(function($) {
        $('.timer').countTo({
            from: 99950,
            to: 100000,
            speed: 2000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });

</script>
</code>```

HTML Code:

```<code><h2><span class="timer" style="color:#F44336;font-weight:700; font-size:20px;"></span></h2>
</code>```

答:
You will need a server side language for getting data extracted from mysql. Say for instance, if you are using PHP as your server side language, in that case you can simply put :</p>

```<code><?php
 mysql_connect('host','username','password') or die();
 mysql_select_db('your_database_name') or die();
 $query='SELECT `min_count`, `max_count` FROM 'your_table_name`;
 $row=mysql_query($query);
 while($rs=mysql_fetch_array($row)){
  $from=$rs[0];
  $to=$rs[1];
 }
?>
<script type="text/javascript">

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

jQuery(function($) {
        $('.timer').countTo({
            from: <?php echo "$from"; ?>,
            to: <?php echo "$to"; ?>,
            speed: 2000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });
</code>```

Body:
I have jQuery counter which move numbers from one fixed number to other fixed number. But I want to create the Counter which end at number which come from MySQL database.

Counter Function Code:

Now It starts value from 99950 and end value is 100000 but I want to change end value. It should be the value which I fetch from mysql.

HTML Code:

Body:
You will need a server side language for getting data extracted from mysql. Say for instance, if you are using PHP as your server side language, in that case you can simply put :

<?php
 mysql_connect('host','username','password') or die();
 mysql_select_db('your_database_name') or die();
 $query='SELECT `min_count`, `max_count` FROM 'your_table_name`;
 $row=mysql_query($query);
 while($rs=mysql_fetch_array($row)){
  $from=$rs[0];
  $to=$rs[1];
 }
?>
<script type="text/javascript">

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

jQuery(function($) {
        $('.timer').countTo({
            from: <?php echo "$from"; ?>,
            to: <?php echo "$to"; ?>,
            speed: 2000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });


问:
Abstract class in Java
What is an "abstract class" in Java?</p>

答:
An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses.  It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods.  These are methods with a signature but no method body.  Any subclass must define a body for each abstract method, otherwise it too must be declared abstract.
Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized.  Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.</p>

OwnerDisplayName: keyur

Title: Abstract class in Java

Body: What is an "abstract class" in Java?


问:
Slave I/O: error connecting to master
I'm following this tutorial for Master-slave-replication
for my database replication and this working fine for test servers in which both servers have not ssl installed. But when I trying to do the same with my production server where only master has ssl installed not slave server, I'm getting this error Slave I/O: error connecting to master 'server-ipaddress:3306' - retry-time: 60  retries: 86400, Error_code: 2003. Is this problem of ssl connection or something else.

Also when setting up mysql configuration on master server after taking dump file of database and unlocking tables my mysql server shut down with my website showing this error error establishing database connection after restarting mysql my website working fine again.

My master server is running on nginx server with wordpress installed and I have also checked that 3306 is listening on my master server.
Why my slave unable to connect to my master server, any solution?

答:
You can use command below to check the ip address mysql server is listening

```<code>netstat -nlt | grep 3306

sample result:

tcp 0  0  xxx.xxx.xxx.xxx:3306  0.0.0.0:*   LISTEN
</code>```

If the result showing same result like me then add a replication master user to access the server database.

If netfilter firewall is enabled (sudo ufw enable) on mysql server machine, do the following to open port 3306 for remote access:

```<code>sudo ufw allow 3306
</code>```

check status again :

```<code>sudo ufw status
</code>```

You will see your tcp port for 3306 is open for connection from anywhere. Now you try to connect from slave server you will get the result.

Title: Slave I/O: error connecting to master

Body:
You can use command below to check the ip address mysql server is listening

netstat -nlt | grep 3306

sample result:

tcp 0  0  xxx.xxx.xxx.xxx:3306  0.0.0.0:*   LISTEN

If the result showing same result like me then add a replication master user to access the server database.

If netfilter firewall is enabled (sudo ufw enable) on mysql server machine, do the following to open port 3306 for remote access:

sudo ufw allow 3306

check status again :

sudo ufw status

You will see your tcp port for 3306 is open for connection from anywhere. Now you try to connect from slave server you will get the result.


问:
Java-Abstract method not overridden
Can you help with one of the true/false questions asked in my test today:

If an abstract method is inherited by a subclass but is not overridden the whole subclass becomes abstract. Would this be true or false?

答:
We are studying Abstract Classes in class this week as well, and as part of the weekly discussion post we have to respond to a question posed here on Stack Overflow, so this is my attempt.

Oracle States:

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

The answer to the true/false question would be true given that because the subclass method is not overridden, the subclass inherits an abstract method, and therefor is by default abstract given that only abstract classes can contain abstract methods.

If a class includes abstract methods, then the class itself must be declared abstract.

Therefor it can be argued that the whole subclass "becomes" abstract as well.

Title: Java-Abstract method not overridden


问:
Find maximum and minimum values of three columns in a python
I would like to know how can I find the difference between maximum and minimum values of three columns in python. (The columns name are POPESTIMATE2010-POPESTIMATE2012)
Then I should find the maximum result among all my records.
in other words, Which county has had the largest absolute change in population within the period 2010-2012?

e.g. If County Population in the 3 year period is 100, 80, 130, then its largest change in the period would be |130-80| = 50.

Here is my code:

```<code>import pandas as pd
census_df = pd.read_csv('census.csv')

def answer_one():
    return ((census_df['POPESTIMATE2010'],census_df ['POPESTIMATE2011'],census_df ['POPESTIMATE2012']).max()-(census_df['POPESTIMATE2010'],census_df ['POPESTIMATE2011'],census_df ['POPESTIMATE2012']).min()).max()

answer_one()
</code>```

答:
I had the same problem, as I solved:</p>

```<code>f1 = census_df[census_df['SUMLEV'] == 50].set_index(['STNAME','CTYNAME'])
f1 = f1.ix[:,'POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013'
,'POPESTIMATE2014','POPESTIMATE2015']].stack()
f2 = f1.max(level=['STNAME','CTYNAME']) - f1.min(level=['STNAME','CTYNAME'])
return f2.idxmax()[1]
</code>```

Body:
I would like to know how can I find the difference between maximum and minimum values of three columns in python. (The columns name are POPESTIMATE2010-POPESTIMATE2012)
Then I should find the maximum result among all my records.
in other words, Which county has had the largest absolute change in population within the period 2010-2012?

e.g. If County Population in the 3 year period is 100, 80, 130, then its largest change in the period would be |130-80| = 50.

Here is my code:

import pandas as pd
census_df = pd.read_csv('census.csv')

def answer_one():
    return ((census_df['POPESTIMATE2010'],census_df ['POPESTIMATE2011'],census_df ['POPESTIMATE2012']).max()-(census_df['POPESTIMATE2010'],census_df ['POPESTIMATE2011'],census_df ['POPESTIMATE2012']).min()).max()

answer_one()

Body:
I had the same problem, as I solved:

f1 = census_df[census_df['SUMLEV'] == 50].set_index(['STNAME','CTYNAME'])
f1 = f1.ix[:,'POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013'
,'POPESTIMATE2014','POPESTIMATE2015']].stack()
f2 = f1.max(level=['STNAME','CTYNAME']) - f1.min(level=['STNAME','CTYNAME'])
return f2.idxmax()[1]


问:
SQL Server: set NULL value to today's value
I have a column EntryDate in a SQL Server database.

How can I set a NULL value to fill it with today's date (server time) if value was not provided in a query?

答:
```<code>Update table
set EntryDate = getdate()
where EntryDate is null
</code>```


问:
Comparing data in 2 separate DataFrames and producing a result in Python/Pandas
I am new to Python and I'm trying to produce a similar result of Excel's IndexMatch function with Python & Pandas, though I'm struggling to get it working.

Basically, I have 2 separate DataFrames:

The first DataFrame ('market') has 7 columns, though I only need 3 of those columns for this exercise ('symbol', 'date', 'close'). This df has 13,948,340 rows.

The second DataFrame ('transactions') has 14 columns, though only I only need 2 of those columns ('i_symbol', 'acceptance_date'). This df has 1,428,026 rows.

My logic is: If i_symbol is equal to symbol and acceptance_date is equal to date: print symbol, date & close. This should be easy.

I have achieved it with iterrows() but because of the size of the dataset, it returns a single result every 3 minutes - which means I would have to run the script for 1,190 hours to get the final result.

Based on what I have read online, itertuples should be a faster approach, but I am currently getting an error:

ValueError: too many values to unpack (expected 2)

This is the code I have written (which currently produces the above ValueError):

```<code>for i_symbol, acceptance_date in transactions.itertuples(index=False):
  for symbol, date in market.itertuples(index=False):
    if i_symbol == symbol and acceptance_date == date:
        print(market.symbol + market.date + market.close)
</code>```

2 questions:

Is itertuples() the best/fastest approach? If so, how can I get the above working?

Does anyone know a better way? Would indexing work? Should I use an external db (e.g. mysql) instead?

Thanks, Matt

答:
@Parfait provided the best answer below as a comment. Very clean, worked incredibly fast - thank you.

```<code> pd.merge(market[['symbol', 'date', 'close']], transactions[['i_symbol',
 'acceptance_date']], left_on=['symbol', 'date'], right_on=['i_symbol',
 'acceptance_date']).
</code>```

No need for looping.

Body:
I am new to Python and I'm trying to produce a similar result of Excel's IndexMatch function with Python & Pandas, though I'm struggling to get it working.

Basically, I have 2 separate DataFrames:

The first DataFrame ('market') has 7 columns, though I only need 3 of those columns for this exercise ('symbol', 'date', 'close'). This df has 13,948,340 rows.

The second DataFrame ('transactions') has 14 columns, though only I only need 2 of those columns ('i_symbol', 'acceptance_date'). This df has 1,428,026 rows.

My logic is: If i_symbol is equal to symbol and acceptance_date is equal to date: print symbol, date & close. This should be easy.

I have achieved it with iterrows() but because of the size of the dataset, it returns a single result every 3 minutes - which means I would have to run the script for 1,190 hours to get the final result.

Based on what I have read online, itertuples should be a faster approach, but I am currently getting an error:

ValueError: too many values to unpack (expected 2)

This is the code I have written (which currently produces the above ValueError):

for i_symbol, acceptance_date in transactions.itertuples(index=False):
  for symbol, date in market.itertuples(index=False):
    if i_symbol == symbol and acceptance_date == date:
        print(market.symbol + market.date + market.close)

2 questions:

Is itertuples() the best/fastest approach? If so, how can I get the above working?

Does anyone know a better way? Would indexing work? Should I use an external db (e.g. mysql) instead?

Thanks, Matt

Body:
@Parfait provided the best answer below as a comment. Very clean, worked incredibly fast - thank you.

 pd.merge(market[['symbol', 'date', 'close']], transactions[['i_symbol',
 'acceptance_date']], left_on=['symbol', 'date'], right_on=['i_symbol',
 'acceptance_date']).

No need for looping.


问:
Google/Facebook oauth works in dev but not in prod
I implemented google and facebook oauth on my website. Everything worked fine and then yesterday I've noticed that it doesn't work anymore. I have not change anything in the google and facebook console and I don't remember changing codes related to that lately. Both google and facebook returns the same error.

I've tested Google oauth on my localhost and it works, but not in production.

The google login window appears and I can login correctly but my code crashes when google redirects me to my website.

I've notice that the variable $http_response_header has 14 headers in dev but is empty in prod. It seems to be the source of the problem but I don't know why nor how to debug it.

I'm using the Yii2 framework and the code that crashes is part of the framework.

See the call stack below (it's not complete).

```
   TypeError

   Argument 2 passed to yii\httpclient\Client::createResponse() must be of
   the type array, null given, called in /home/folder/vendor/yiisoft/yii2-
   httpclient/StreamTransport.php on line 73
   1. in /home/folder/vendor/yiisoft/yii2-httpclient/Client.php at line
   200
       return Yii::createObject($config);
    }

    /**
     * Creates a response instance.
     * @param string $content raw content
     * @param array $headers headers list.
     * @return Response request instance.
     */
    public function createResponse($content = null, array $headers = [])
    {
        $config = $this->responseConfig;
        if (!isset($config['class'])) {
            $config['class'] = Response::className();
        }
        $config['client'] = $this;
        $response = Yii::createObject($config);
        $response->setContent($content);
        $response->setHeaders($headers);
    2. in /home/folder/vendor/yiisoft/yii2-httpclient/StreamTransport.php
    at line 73 – yii\httpclient\Client::createResponse(false, null)
       Yii::endProfile($token, __METHOD__);
            throw new Exception($e->getMessage(), $e->getCode(), $e);
        }

        Yii::endProfile($token, __METHOD__);

      $response = $request->client->createResponse($responseContent,
    $responseHeaders);

        $request->afterSend($response);

        return $response;
    }
```

Can someone help me I don't know where to start and I don't know how to debug this.

Thanks.

答:
I don't get the -1 but anyway I found the problem.

The php variable "allow_url_fopen" setting was disabled and it must be activated. I didn't change it, something happened on the host.

Body:
I implemented google and facebook oauth on my website. Everything worked fine and then yesterday I've noticed that it doesn't work anymore. I have not change anything in the google and facebook console and I don't remember changing codes related to that lately. Both google and facebook returns the same error.

I've tested Google oauth on my localhost and it works, but not in production.

The google login window appears and I can login correctly but my code crashes when google redirects me to my website.

I've notice that the variable $http_response_header has 14 headers in dev but is empty in prod. It seems to be the source of the problem but I don't know why nor how to debug it.

I'm using the Yii2 framework and the code that crashes is part of the framework.

See the call stack below (it's not complete).

   TypeError

   Argument 2 passed to yii\httpclient\Client::createResponse() must be of
   the type array, null given, called in /home/folder/vendor/yiisoft/yii2-
   httpclient/StreamTransport.php on line 73
   1. in /home/folder/vendor/yiisoft/yii2-httpclient/Client.php at line
   200
       return Yii::createObject($config);
    }

    /**
     * Creates a response instance.
     * @param string $content raw content
     * @param array $headers headers list.
     * @return Response request instance.
     */
    public function createResponse($content = null, array $headers = [])
    {
        $config = $this->responseConfig;
        if (!isset($config['class'])) {
            $config['class'] = Response::className();
        }
        $config['client'] = $this;
        $response = Yii::createObject($config);
        $response->setContent($content);
        $response->setHeaders($headers);
    2. in /home/folder/vendor/yiisoft/yii2-httpclient/StreamTransport.php
    at line 73 – yii\httpclient\Client::createResponse(false, null)
       Yii::endProfile($token, __METHOD__);
            throw new Exception($e->getMessage(), $e->getCode(), $e);
        }

        Yii::endProfile($token, __METHOD__);

      $response = $request->client->createResponse($responseContent,
    $responseHeaders);

        $request->afterSend($response);

        return $response;
    }

Can someone help me I don't know where to start and I don't know how to debug this.

Thanks.


问:
How to improve canvas fabric.js performance with large number of Objects
I need make an App that has about 30k Objects, a user can Pan, Zoom or "Select on click" any of those objects.
Fabric.js Canvas is being used

I have done the same using SVG's and the svg-pan-zoom plugin (no Canvas Element) with better results

Problem: there is a significant Lag while Zooming, Panning or Object on Click

will removing Fabric.js improve performance?

will switching to WebGL improve performance?

Have tried Fabric specific options

```<code>fabric.Object.prototype.objectCaching = false;
fabric.Object.prototype.statefullCache = false;
fabric.Object.prototype.noScaleCache = true;
fabric.Object.prototype.needsItsOwnCache = false;
</code>```

UPDATE
Heres the updated Fiddle

for reference :

canvas-vs-svg-vs-div Stackoverflow

Stackoverflow

答:
Don't Render in IO EVENTS!

Though not a complete fix to the update speed this answer will about double the interaction speed.

A common, almost standard, mistake made with mouse and event interaction with the canvas (and DOM) is to delegate rendering to mouse/touch events. This is very bad practice as mouse events fire at much higher rates than the display can display. It becomes worse when your rendering time is high as you queue up mouse events (pseudo render events) and do a re render for every movement of the mouse

Note blocking code will stop mouse events but as soon as the engine is idle the mouse will start firing at full rate again.

Use the mouse events just to get the mouse state. Use an animation loop that is synced to the display to render only when needed and there is time available. Things like the wheel and mouse movement deltas should be recorded cumulatively.

```<code>mouse.dx += event.movementX;
mouse.dy += event.movementY;
mouse.wheel += event.wheelDelta;
</code>```

And consume them in the main render loop...

```<code>function update(){

    // ... code to use mouse
    // consume deltas
    mouse.x = mouse.y = mouse.wheel = 0;
</code>```

...this ensures that the mouse state is accurately followed when you may have many mouse events between render updates.

Example, separating events from rendering.

Change you code in the fiddle you provided to the following, on my machine it about doubled the rendering speed (which is still very slow).

```<code>// from just after the function applyZoom replace all the code
var mouse = {  // holds the mouse state
    x : 0,
    y : 0,
    down : false,
    w : 0,
    delta : new fabric.Point(0,0),
}
// event just track mouse state
function zoom(e) {
    if(e != null) { e.preventDefault() }
    var evt=window.event || e;
    mouse.x = e.offsetX;
    mouse.y = e.offsetY;
    mouse.w += evt.detail? evt.detail*(-120) : evt.wheelDelta;
    return false;
}
canvas.on('mouse:up', function (e) { mouse.down = false });
canvas.on('mouse:out', function (e) { mouse.down = false });
canvas.on('mouse:down', function (e) { mouse.down = true });
canvas.on('mouse:move', function(e) {
    if (e && e.e) {
        mouse.delta.x += e.e.movementX;
        mouse.delta.y += e.e.movementY;
    }
});
// main animation loop
function update(){
    if(mouse.w !== 0){  // if the wheel has moved do zoom
        var curZoom = canvas.getZoom();
         canvas.zoomToPoint(
             { x : mouse.x, y: mouse.y },
             canvas.getZoom() + mouse.w / 4000
         );
         mouse.w = 0; // consume wheel delta
    }else if(mouse.down) {  // if mouse button down
         canvas.relativePan(mouse.delta);
    }
    // consume mouse delta
    mouse.delta.x = 0;
    mouse.delta.y = 0;
    requestAnimationFrame(update);
}
requestAnimationFrame(update);
</code>```

Body:
I need make an App that has about 30k Objects, a user can Pan, Zoom or "Select on click" any of those objects.
Fabric.js Canvas is being used

I have done the same using SVG's and the svg-pan-zoom plugin (no Canvas Element) with better results

Problem: there is a significant Lag while Zooming, Panning or Object on Click

will removing Fabric.js improve performance?

will switching to WebGL improve performance?

Have tried Fabric specific options

fabric.Object.prototype.objectCaching = false;
fabric.Object.prototype.statefullCache = false;
fabric.Object.prototype.noScaleCache = true;
fabric.Object.prototype.needsItsOwnCache = false;

UPDATE
Heres the updated Fiddle

for reference :

canvas-vs-svg-vs-div Stackoverflow

Stackoverflow

Body:
Don't Render in IO EVENTS!

Though not a complete fix to the update speed this answer will about double the interaction speed.

A common, almost standard, mistake made with mouse and event interaction with the canvas (and DOM) is to delegate rendering to mouse/touch events. This is very bad practice as mouse events fire at much higher rates than the display can display. It becomes worse when your rendering time is high as you queue up mouse events (pseudo render events) and do a re render for every movement of the mouse

Note blocking code will stop mouse events but as soon as the engine is idle the mouse will start firing at full rate again.

Use the mouse events just to get the mouse state. Use an animation loop that is synced to the display to render only when needed and there is time available. Things like the wheel and mouse movement deltas should be recorded cumulatively.

mouse.dx += event.movementX;
mouse.dy += event.movementY;
mouse.wheel += event.wheelDelta;

And consume them in the main render loop...

function update(){

    // ... code to use mouse
    // consume deltas
    mouse.x = mouse.y = mouse.wheel = 0;

...this ensures that the mouse state is accurately followed when you may have many mouse events between render updates.

Example, separating events from rendering.

Change you code in the fiddle you provided to the following, on my machine it about doubled the rendering speed (which is still very slow).

// from just after the function applyZoom replace all the code
var mouse = {  // holds the mouse state
    x : 0,
    y : 0,
    down : false,
    w : 0,
    delta : new fabric.Point(0,0),
}
// event just track mouse state
function zoom(e) {
    if(e != null) { e.preventDefault() }
    var evt=window.event || e;
    mouse.x = e.offsetX;
    mouse.y = e.offsetY;
    mouse.w += evt.detail? evt.detail*(-120) : evt.wheelDelta;
    return false;
}
canvas.on('mouse:up', function (e) { mouse.down = false });
canvas.on('mouse:out', function (e) { mouse.down = false });
canvas.on('mouse:down', function (e) { mouse.down = true });
canvas.on('mouse:move', function(e) {
    if (e && e.e) {
        mouse.delta.x += e.e.movementX;
        mouse.delta.y += e.e.movementY;
    }
});
// main animation loop
function update(){
    if(mouse.w !== 0){  // if the wheel has moved do zoom
        var curZoom = canvas.getZoom();
         canvas.zoomToPoint(
             { x : mouse.x, y: mouse.y },
             canvas.getZoom() + mouse.w / 4000
         );
         mouse.w = 0; // consume wheel delta
    }else if(mouse.down) {  // if mouse button down
         canvas.relativePan(mouse.delta);
    }
    // consume mouse delta
    mouse.delta.x = 0;
    mouse.delta.y = 0;
    requestAnimationFrame(update);
}
requestAnimationFrame(update);


问:
How to make RecyclerView stops recycling defined positions?
My problem is: I have a video streaming happening on one of the views inside the RecyclerView.

When the user scrolls, the view gets recycled and other cameras starts their own streaming on that recycled viewholder. This is bad for user interface since the streaming process takes some seconds to start.

How can I say to the RecyclerView: "Hey Recycler, please, do not recycle that exact position x and give that position ALWAYS the same viewholder you gave it the first time, instead of random one"?

Please someone help me =(

答:
Your problem comes from the viewholder itself. Viewholders keep reference to views, while the adapter don't. The adapter keeps the data collection only. So, add a field to the viewholder to keep a reference of the data element you used to populate the view in the viewholder. In other words:

```<code>public class SomeViewHolder extends RecyclerView.ViewHolder{

    private View view;
    private Data data;

    public SomeViewHolder(View itemView) {
        super(itemView);
        view = itemView;
    }

    public void bindData(Data data){
        view.setData(data);
        this.data = data;
    }

    public void setData(Data data){
       this.data = data;
    }

    public Data getData(){
        return data;
    }

    public View getView(){
        return view;
    }
}
</code>```

Now, the viewholder know which element of the adapter is using. Therefore, when overriding the binding method in the adapter, you can check if the holder has already bonded with some data, and, if the data contains video, you can avoid the binding and forcefully set an already loaded view.

```<code>@Override
public void onBindViewHolder(SomeViewHolder holder, int position) {

    //videoViewData is a data field you have to put into the adapter.
    //videoView is a view field you have to put into the adapter.

    if(adapterData.get(position).equals(videoViewData)){
        holder.setView(videoView);
        holder.setData(adapterData.get(position));
    }else{
        holder.bindData(adapterData.get(position));
        if(adapterData.get(position).isVideo()){
            videoViewData = adapterData.get(position);
            videoView = holder.getView();
        }
    }

}
</code>```

Finally, you'll have to override the onViewRecycled method in the adapter, so, when a view containing a video gets recycled, you can get the view and put it somewhere else.

```<code>public void onViewRecycled(SomeViewHolder holder){
    if(holder.getData().isVideo()){
        videoViewData = holder.getData().
        videoView = holder.getView();
        videoView.pauseVideo();
    }
}
</code>```

keep in mind, this can cause some serious leaks if you don't manage the stored view. Also, you have to define methods for telling when your data is video, and a properly defined equals method.

Body:
Your problem comes from the viewholder itself. Viewholders keep reference to views, while the adapter don't. The adapter keeps the data collection only. So, add a field to the viewholder to keep a reference of the data element you used to populate the view in the viewholder. In other words:

public class SomeViewHolder extends RecyclerView.ViewHolder{

    private View view;
    private Data data;

    public SomeViewHolder(View itemView) {
        super(itemView);
        view = itemView;
    }

    public void bindData(Data data){
        view.setData(data);
        this.data = data;
    }

    public void setData(Data data){
       this.data = data;
    }

    public Data getData(){
        return data;
    }

    public View getView(){
        return view;
    }
}

Now, the viewholder know which element of the adapter is using. Therefore, when overriding the binding method in the adapter, you can check if the holder has already bonded with some data, and, if the data contains video, you can avoid the binding and forcefully set an already loaded view.

@Override
public void onBindViewHolder(SomeViewHolder holder, int position) {

    //videoViewData is a data field you have to put into the adapter.
    //videoView is a view field you have to put into the adapter.

    if(adapterData.get(position).equals(videoViewData)){
        holder.setView(videoView);
        holder.setData(adapterData.get(position));
    }else{
        holder.bindData(adapterData.get(position));
        if(adapterData.get(position).isVideo()){
            videoViewData = adapterData.get(position);
            videoView = holder.getView();
        }
    }

}

Finally, you'll have to override the onViewRecycled method in the adapter, so, when a view containing a video gets recycled, you can get the view and put it somewhere else.

public void onViewRecycled(SomeViewHolder holder){
    if(holder.getData().isVideo()){
        videoViewData = holder.getData().
        videoView = holder.getView();
        videoView.pauseVideo();
    }
}

keep in mind, this can cause some serious leaks if you don't manage the stored view. Also, you have to define methods for telling when your data is video, and a properly defined equals method.


问:
Adding "remember my password" in Drupal
I want to add an option 'Remember My Password' in Login Page of Drupal 6. Is there any module for this ?

Is there any drupal module which remembers user's name and password on login page and auto-fill fields when user comes back after signout ?

答: Are you looking for the Remember me module? </p>

Title: Adding "remember my password" in Drupal


问:
Slow JDBC & Hibernate query performance (compared to PhpMyAdmin)
I am working on a Spring MVC/Hibernate web app and the DB queries are awfully slow. I already searched, but none of the performance problems people asked about here seem to match my problem (suggestions included issues with model mapping or connection pooling).

No matter if I use plain JDBC or Hibernate to query the DB it takes equally long. To make sure it is not related with the Spring framework I wrote this simple application:

```<code>public class JDBCTest {

  static final String JDBC_DRIVER = ...;
  static final String DB_URL = ...;
  static final String USER = ...;
  static final String PASS = ...;

  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    double time;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      start = System.currentTimeMillis();
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      System.out.println("Conn. duration: " + (System.currentTimeMillis() - start));
      stmt = conn.createStatement();
      String sql = "SELECT * FROM temperature WHERE SensorId = 1 AND metered >= '2016-09-15 14:00:00' AND metered <= '2016-09-16 20:00:00'";
      start = System.currentTimeMillis();
      ResultSet rs = stmt.executeQuery(sql);
      System.out.println("Query duration: " + (System.currentTimeMillis() - start));
...
</code>```

While opening the connection takes 200-300ms (seems reasonable), the query takes 1500-2000ms.

When executing the very same query in PHPMyAdmin it says the query took 0.0312 seconds (compared to >1 second with JDBC).

What could be the issue? No matter if it is a minimalistic JDBC app as shown above, the Spring app using JDBC or using Hibernate - the query always takes roughly the same amount of time.

It doesn't seem to have to do with the timestamps either, as even simple "SELECT * FROM temperature" queries are many times slower than what PHPMyAdmin takes.

答:
For that query, this composite index is optimal:

```<code>INDEX(SensorId, metered)
</code>```

Why would a query run faster the second time?  Usually because of caching.  Or it could be that one driver gets the rows incrementally; the other gets them all at once.

If you want to discuss further, please provide SHOW CREATE TABLE and EXPLAIN SELECT ...;

Body:
I am working on a Spring MVC/Hibernate web app and the DB queries are awfully slow. I already searched, but none of the performance problems people asked about here seem to match my problem (suggestions included issues with model mapping or connection pooling).

No matter if I use plain JDBC or Hibernate to query the DB it takes equally long. To make sure it is not related with the Spring framework I wrote this simple application:

public class JDBCTest {

  static final String JDBC_DRIVER = ...;
  static final String DB_URL = ...;
  static final String USER = ...;
  static final String PASS = ...;

  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    double time;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      start = System.currentTimeMillis();
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      System.out.println("Conn. duration: " + (System.currentTimeMillis() - start));
      stmt = conn.createStatement();
      String sql = "SELECT * FROM temperature WHERE SensorId = 1 AND metered >= '2016-09-15 14:00:00' AND metered <= '2016-09-16 20:00:00'";
      start = System.currentTimeMillis();
      ResultSet rs = stmt.executeQuery(sql);
      System.out.println("Query duration: " + (System.currentTimeMillis() - start));
...

While opening the connection takes 200-300ms (seems reasonable), the query takes 1500-2000ms.

When executing the very same query in PHPMyAdmin it says the query took 0.0312 seconds (compared to >1 second with JDBC).

What could be the issue? No matter if it is a minimalistic JDBC app as shown above, the Spring app using JDBC or using Hibernate - the query always takes roughly the same amount of time.

It doesn't seem to have to do with the timestamps either, as even simple "SELECT * FROM temperature" queries are many times slower than what PHPMyAdmin takes.

Body:
For that query, this composite index is optimal:

INDEX(SensorId, metered)

Why would a query run faster the second time?  Usually because of caching.  Or it could be that one driver gets the rows incrementally; the other gets them all at once.

If you want to discuss further, please provide SHOW CREATE TABLE and EXPLAIN SELECT ...;


问:
Simple breadcrum logo in jsx of react binding
```<code>{breadcrumbs.map((obj,i) =>
    <p> {i} > 1 ? "<span className="seperator">|</span>" : <span className="bold">{obj}</span> </p>
)}
</code>```

I want to make breadcrumbs from an array but failed using above code. breadcrumbs is just an array ['books','javascript'] and my expected output will be

Books -> javascript and so on, it should be working if I have more than 2 item in the array.

答:
One problem with this code is with syntax.  Curly braces are placed improperly and elements should not be strings, ie. the spans.

The other issue is how you are trying to handle separators and their classes.  You need to insert a separator before all elements except the first. One way to do this is with a reduce that modifies the array before you map it.

A side point, place a key on all mapped items.

Here's what it looks like working:

```<code>  <p>
    {['books','javascript'].reduce((all, one, i) => {
        i > 0 && all.push('->');
        all.push(one);
        return all;
    }, []).map((obj, i) =>
      <span key={i} className={i%2 ? 'seperator' : 'bold'}>{obj}</span>
    )}
  </p>
</code>```

https://jsfiddle.net/q0vt53po/1/

Body:
{breadcrumbs.map((obj,i) =>

 {i} > 1 ? "|" : {obj}

)}

I want to make breadcrumbs from an array but failed using above code. breadcrumbs is just an array ['books','javascript'] and my expected output will be

Books -> javascript and so on, it should be working if I have more than 2 item in the array.

Body:
One problem with this code is with syntax.  Curly braces are placed improperly and elements should not be strings, ie. the spans.

The other issue is how you are trying to handle separators and their classes.  You need to insert a separator before all elements except the first. One way to do this is with a reduce that modifies the array before you map it.

A side point, place a key on all mapped items.

Here's what it looks like working:

  <p>
    {['books','javascript'].reduce((all, one, i) => {
        i > 0 && all.push('->');
        all.push(one);
        return all;
    }, []).map((obj, i) =>
      <span key={i} className={i%2 ? 'seperator' : 'bold'}>{obj}</span>
    )}
  </p>

https://jsfiddle.net/q0vt53po/1/


问:
Nodemon not refreshing browser in React-Express-Node App
I have installed nodemon locally in my workspace, but even though it restarts in the terminal after changes are made, it does not refresh the browser page. I have to manually refresh it each time.

I've got Express, Node, React and Webpack running in the environment.

This is how my setup looks like -

My package.json starts up server.js -

```<code>"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
</code>```

and server.js is -

```<code>var express = require('express');

     var app = express();
        app.use(express.static('public'));
        app.listen(3000, function () {
            console.log("Express server is up on port 3000");
        });
</code>```

The entry point in the webpack config file is -

```<code>module.exports = {
    entry: './public/scripts/app.jsx',
    output: {
        path: __dirname,
        filename: './public/scripts/bundle.js'
    }
</code>```

What should I do to fix it?

Update -

I made a video to describe the situation, if it helps.

答: nodemon is only for restarting the server when your server code changes. It has no functionality to reload your page in the browser. If you want automatic browser reload, you could, for example, run a webpack dev server in addition to your nodemon. webpack dev server is able reload the page in the browser when your client code changes, it can even update the page in the browser without a full page reload, if you use its hot module reloading feature. </p>

Body:
I have installed nodemon locally in my workspace, but even though it restarts in the terminal after changes are made, it does not refresh the browser page. I have to manually refresh it each time.

I've got Express, Node, React and Webpack running in the environment.

This is how my setup looks like -

My package.json starts up server.js -

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },

and server.js is -

var express = require('express');

     var app = express();
        app.use(express.static('public'));
        app.listen(3000, function () {
            console.log("Express server is up on port 3000");
        });

The entry point in the webpack config file is -

module.exports = {
    entry: './public/scripts/app.jsx',
    output: {
        path: __dirname,
        filename: './public/scripts/bundle.js'
    }

What should I do to fix it?

Update -

I made a video to describe the situation, if it helps.


问:
How to pass arguments to an included file?
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

```<code><?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

<body>
.....
..
.
</code>```

header.php

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
</code>```

Obviously this doesn't work; how can I pass arguments to an included file?

答:
You can't pass arguments to include, but it has access to all variables you've already set. From the include documentation:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.

Thus:

index.php

```<code><?php
$header = 'aaaaaaaaaaaaaaaaaaaaa';
include("header.php");
?>
</code>```

header.php

```<code><title> <?php echo $header; ?> </title>
</code>```

Body:
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

.....
..
.

header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="shortcut icon" href="favicon.ico">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />

Obviously this doesn't work; how can I pass arguments to an included file?

Body:
You can't pass arguments to include, but it has access to all variables you've already set. From the include documentation:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.

Thus:

index.php

<?php
$header = 'aaaaaaaaaaaaaaaaaaaaa';
include("header.php");
?>

header.php

<title> <?php echo $header; ?> </title>