问:
Order By 2 columns
I have this table and .

```<code> id  |  item_id  | created_at
-----+-----------+------------
  1  |   Apple   | 2017-03-21
  2  |   Grape   | 2017-03-23
  3  |   Grape   | 2017-03-24
  4  |   Apple   | 2017-03-25
</code>```

I want to order by created_at and also at the same time order by item_id like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
</code>```

So if i add a new row for item_id: Grape my new results should be like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  5  |   Grape   | 2017-03-28  (NEW)
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
</code>```

and then if i add new row for item_id: Apple it should be like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28  (NEW)
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  5  |   Grape   | 2017-03-27
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
</code>```

...So it orders by the latest created_at and show the other rows with the same item_id below it

I have tried ORDER BY created_at, item_id  DESC but it does not works and give me this instead:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28
  5  |   Grape   | 2017-03-27
  4  |   Apple   | 2017-03-25
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  1  |   Apple   | 2017-03-21
</code>```

答:
SQLFiddle: PostgreSQL

```<code>WITH grouped AS (
  select   item_id, max(created_at) as max_dt
  from     tbl
  group by item_id
)
SELECT     tbl.*
FROM       grouped
LEFT JOIN  tbl      USING (item_id)
ORDER BY   grouped.max_dt desc,
           grouped.item_id,      -- important if apple and grape both have same max dt
           tbl.created_at desc;
</code>```

subquery to get the most recent dates by item (the item grouping)

left join those results on the actual table to get desired records

Title: Order By 2 columns

Body:
I have this table and .

 id  |  item_id  | created_at
-----+-----------+------------
  1  |   Apple   | 2017-03-21
  2  |   Grape   | 2017-03-23
  3  |   Grape   | 2017-03-24
  4  |   Apple   | 2017-03-25

I want to order by created_at and also at the same time order by item_id like this:

 id  |  item_id  | created_at
-----+-----------+------------
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23

So if i add a new row for item_id: Grape my new results should be like this:

 id  |  item_id  | created_at
-----+-----------+------------
  5  |   Grape   | 2017-03-28  (NEW)
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21

and then if i add new row for item_id: Apple it should be like this:

 id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28  (NEW)
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  5  |   Grape   | 2017-03-27
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23

...So it orders by the latest created_at and show the other rows with the same item_id below it

I have tried ORDER BY created_at, item_id  DESC but it does not works and give me this instead:

 id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28
  5  |   Grape   | 2017-03-27
  4  |   Apple   | 2017-03-25
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  1  |   Apple   | 2017-03-21

Body:
SQLFiddle: PostgreSQL

WITH grouped AS (
  select   item_id, max(created_at) as max_dt
  from     tbl
  group by item_id
)
SELECT     tbl.*
FROM       grouped
LEFT JOIN  tbl      USING (item_id)
ORDER BY   grouped.max_dt desc,
           grouped.item_id,      -- important if apple and grape both have same max dt
           tbl.created_at desc;

subquery to get the most recent dates by item (the item grouping)

left join those results on the actual table to get desired records


来源: stackexchange

问:
How can I create a PayPal link that will send money to a specific e-mail address?
This if for an internal CMS, so it's not public facing. I have my publishers that I need to pay via PayPal. I'd like to be able to click one link and it goes directly to a PayPal page with their email address filled in and a particular value.

Is this possible?

答:
For those that don't want to, or can't use PayPal.me links, here is a Uri that will work with the new and old PayPal UI.</p>

```<code>https://www.paypal.com/cgi-bin/webscr
?cmd=_xclick
&business=email@address.com
&tax=0
&currency=USD
&item_name=NAME
&item_number=NUMBER
&quantity=1
&amount=2.50
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For those that don't want to, or can't use PayPal.me links, here is a Uri that will work with the new and old PayPal UI.

https://www.paypal.com/cgi-bin/webscr
?cmd=_xclick
&business=email@address.com
&tax=0
&currency=USD
&item_name=NAME
&item_number=NUMBER
&quantity=1
&amount=2.50


问:
Add chart using chart.js in codeigniter
I am trying to display a simple chart on my view (Codeigniter), however it is not appearing.

Can someone tell me what am I missing?

Appreciate your help with this.

```<code><div class="container">
  <h2>This is a sample — Line Chart</h2>
  <div>
      <canvas id="myChart"></canvas>
  </div>
 </div>

 <script type="text/javascript" src="http://www.chartjs.org/assets/Chart.js">
var ctx = document.getElementById("myChart").getContext("2d");

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>
</code>```

答:
you are missing script tag for your js code</p>

```<code><script>
var ctx = document.getElementById("myChart").getContext("2d");

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Add chart using chart.js in codeigniter

Body:
I am trying to display a simple chart on my view (Codeigniter), however it is not appearing.

Can someone tell me what am I missing?

Appreciate your help with this.

This is a sample — Line Chart

      <canvas id="myChart"></canvas>

Body:
you are missing script tag for your js code

<script>
var ctx = document.getElementById("myChart").getContext("2d");

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>


问:
Using C++ class in D
I am trying to find a way to use C++ classes in D.

http://www.digitalmars.com/d/2.0/cpp_interface.html

D cannot call C++ special member functions, and vice versa. These include constructors, destructors, conversion operators, operator overloading, and allocators.

So, I am attempting to dumb down these C++ functions to C style function calls. Here is the proof I am working with.

helper.h

```<code>class someClass {
    public:
        someClass();
        char *whatSayYou();
};

extern "C"
{
    someClass *hearMeOut();
}
</code>```

helper.cpp

```<code>#include "helper.h"

someClass::someClass()
{

}

char *someClass::whatSayYou()
{
    return "Everything is gravy";
}

someClass *hearMeOut()
{
    return new someClass;
}
</code>```

main.d

```<code>import std.stdio;

int main(string[] args)
{
    someClass *awesomeExample = hearMeOut();
    char *shoutoutToTheWorld = awesomeExample.whatSayYou();
    writefln(std.string.toString(shoutoutToTheWorld));
    return 0;
}

extern (C++)
{
    interface someClass
    {
        char *whatSayYou();
    }

    someClass *hearMeOut();
}
</code>```

And here is how I complied it.

```<code>g++-4.3 -c -I code/dg3d_helper -I /usr/local/include/ -o code/dg3d_helper/helper.o code/dg3d_helper/helper.cpp
code/dg3d_helper/helper.cpp: In member function ‘char* someClass::whatSayYou()’:
code/dg3d_helper/helper.cpp:19: warning: deprecated conversion from string constant to ‘char*’
gdc-4.3 -g -c -I code/ -o code/main.o code/main.d
gdc-4.3 -g -I code/ -o main code/dg3d_helper/helper.o code/main.o -lstdc++
</code>```

And I get a segmentation fault as soon as the method is called.

```<code>Program received signal SIGSEGV, Segmentation fault.
0x0000000000402fa0 in _Dmain (args=...) at code/main.d:7
7       char *shoutoutToTheWorld = awesomeExample.whatSayYou();
(gdb) bt
#0  0x0000000000402fa0 in _Dmain (args=...) at code/main.d:7
#1  0x000000000041b1aa in _D9dgccmain211_d_run_mainUiPPaPUAAaZiZi2goMFZv ()
#2  0x000000000041b235 in _d_run_main ()
#3  0x00002aaaab8cfc4d in __libc_start_main () from /lib/libc.so.6
#4  0x0000000000402d59 in _start ()
</code>```

答:
Your C++ version returns by value.

Your D version expects it to return by reference.

Essentially, your C++ version sticks a copy of someClass on the stack. D thinks that C++ will have put a pointer on the stack. It tries to interpret the copy of someClass as a pointer, and bad things happen.

The problem is that in D, classes and interfaces are always returned by reference. C++ returns everything by value unless you indicate that its either a reference or a pointer.

Thus you need this:

```<code>someClass * hearMeOut() { return new someClass; }
</code>```

Don't forget to delete it later.

ContentLicense: CC BY-SA 2.5

Title: Using C++ class in D

Body:
I am trying to find a way to use C++ classes in D.

http://www.digitalmars.com/d/2.0/cpp_interface.html

D cannot call C++ special member functions, and vice versa. These include constructors, destructors, conversion operators, operator overloading, and allocators.

So, I am attempting to dumb down these C++ functions to C style function calls. Here is the proof I am working with.

helper.h

class someClass {
    public:
        someClass();
        char *whatSayYou();
};

extern "C"
{
    someClass *hearMeOut();
}

helper.cpp

#include "helper.h"

someClass::someClass()
{

}

char *someClass::whatSayYou()
{
    return "Everything is gravy";
}

someClass *hearMeOut()
{
    return new someClass;
}

main.d

import std.stdio;

int main(string[] args)
{
    someClass *awesomeExample = hearMeOut();
    char *shoutoutToTheWorld = awesomeExample.whatSayYou();
    writefln(std.string.toString(shoutoutToTheWorld));
    return 0;
}

extern (C++)
{
    interface someClass
    {
        char *whatSayYou();
    }

    someClass *hearMeOut();
}

And here is how I complied it.

g++-4.3 -c -I code/dg3d_helper -I /usr/local/include/ -o code/dg3d_helper/helper.o code/dg3d_helper/helper.cpp
code/dg3d_helper/helper.cpp: In member function ‘char* someClass::whatSayYou()’:
code/dg3d_helper/helper.cpp:19: warning: deprecated conversion from string constant to ‘char*’
gdc-4.3 -g -c -I code/ -o code/main.o code/main.d
gdc-4.3 -g -I code/ -o main code/dg3d_helper/helper.o code/main.o -lstdc++

And I get a segmentation fault as soon as the method is called.

Program received signal SIGSEGV, Segmentation fault.
0x0000000000402fa0 in _Dmain (args=...) at code/main.d:7
7       char *shoutoutToTheWorld = awesomeExample.whatSayYou();
(gdb) bt
#0  0x0000000000402fa0 in _Dmain (args=...) at code/main.d:7
#1  0x000000000041b1aa in _D9dgccmain211_d_run_mainUiPPaPUAAaZiZi2goMFZv ()
#2  0x000000000041b235 in _d_run_main ()
#3  0x00002aaaab8cfc4d in __libc_start_main () from /lib/libc.so.6
#4  0x0000000000402d59 in _start ()

Body:
Your C++ version returns by value.

Your D version expects it to return by reference.

Essentially, your C++ version sticks a copy of someClass on the stack. D thinks that C++ will have put a pointer on the stack. It tries to interpret the copy of someClass as a pointer, and bad things happen.

The problem is that in D, classes and interfaces are always returned by reference. C++ returns everything by value unless you indicate that its either a reference or a pointer.

Thus you need this:

someClass * hearMeOut() { return new someClass; }

Don't forget to delete it later.


问:
How can I use a background task within an adapter?
I have this image adapter, that is supposed to handle updating a grid of images. The problem is that I have a BackgroundImageTask running that fetches the bitmap from a URL. The getView method returns the imageView before the Background Task can finish updating it. How Can I force the Background Task to finish before it returns the imageview?

```<code>public class ImageAdapter extends BaseAdapter {
private Context mContext;
Bitmap bitmap;
List<Post> postList;
ImageView imageView;
int pos;

public ImageAdapter(Context c, List<Post> p) {
    mContext = c;
    postList = p;
}
public int getCount() {
    return postList.size();
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    pos=position;
    View convert = convertView;
    if (convert == null) {
        // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, 320));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(0, 0, 0, 0);
    } else {
        imageView = (ImageView) convert;
    }
    new BackgroundImageTask().execute();

    return imageView;
}

public View SetBit(Bitmap b){
    imageView.setImageBitmap(b);
    return imageView;
}

class BackgroundImageTask extends AsyncTask<Void, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(Void... params) {
        Bitmap bit1=bitmap;
        try {

           bit1 = BitmapFactory.decodeStream((InputStream)new URL(postList.get(pos).thumbnail).getContent());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bit1;
    }

    @Override
    protected void onPostExecute(Bitmap bit) {
        SetBit(bit);
    }
}
</code>```

}

答:
Instead You can pass the ImageView Object to the background Task like

```<code>    new BackgroundImageTask(imageView).execute();
</code>```

and

```<code>  class BackgroundImageTask extends AsyncTask<Void, Void, Bitmap> {
  ImageView iv;
BackgroundImageTask(ImageView imageView){
 iv = imageView;
}

@Override
protected Bitmap doInBackground(Void... params) {
    Bitmap bit1=bitmap;
    try {

       bit1 = BitmapFactory.decodeStream((InputStream)new URL(postList.get(pos).thumbnail).getContent());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bit1;
}

@Override
protected void onPostExecute(Bitmap bit) {
    iv.setImageBitmap(bit);
}
}
</code>```

Body:
I have this image adapter, that is supposed to handle updating a grid of images. The problem is that I have a BackgroundImageTask running that fetches the bitmap from a URL. The getView method returns the imageView before the Background Task can finish updating it. How Can I force the Background Task to finish before it returns the imageview?

public class ImageAdapter extends BaseAdapter {
private Context mContext;
Bitmap bitmap;
List<Post> postList;
ImageView imageView;
int pos;

public ImageAdapter(Context c, List<Post> p) {
    mContext = c;
    postList = p;
}
public int getCount() {
    return postList.size();
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    pos=position;
    View convert = convertView;
    if (convert == null) {
        // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, 320));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(0, 0, 0, 0);
    } else {
        imageView = (ImageView) convert;
    }
    new BackgroundImageTask().execute();

    return imageView;
}

public View SetBit(Bitmap b){
    imageView.setImageBitmap(b);
    return imageView;
}

class BackgroundImageTask extends AsyncTask<Void, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(Void... params) {
        Bitmap bit1=bitmap;
        try {

           bit1 = BitmapFactory.decodeStream((InputStream)new URL(postList.get(pos).thumbnail).getContent());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bit1;
    }

    @Override
    protected void onPostExecute(Bitmap bit) {
        SetBit(bit);
    }
}

}

Body:
Instead You can pass the ImageView Object to the background Task like

    new BackgroundImageTask(imageView).execute();

and

  class BackgroundImageTask extends AsyncTask<Void, Void, Bitmap> {
  ImageView iv;
BackgroundImageTask(ImageView imageView){
 iv = imageView;
}

@Override
protected Bitmap doInBackground(Void... params) {
    Bitmap bit1=bitmap;
    try {

       bit1 = BitmapFactory.decodeStream((InputStream)new URL(postList.get(pos).thumbnail).getContent());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bit1;
}

@Override
protected void onPostExecute(Bitmap bit) {
    iv.setImageBitmap(bit);
}
}


问:
Method in MyApplication never gets called
When I try to connect my Android APP to BlueTooth printer, the key method is never called. I followed the introduction of SDK:

Add permission

Init SDK in Application.onCreate()

public void onCreate() {
    super.onCreate();
    WPXMain.init(this);
}

Wnen I run sample offered by SDK, I can see log:

03-29 11:15:25.399 10820-10820/com.wpx.printer.sample D/WPXMain: init

Here is the sample code:

```<code>public class MyApplication extends Application {
    private List<Activity> list = new ArrayList<Activity>();

    public void addActivity(Activity activity) {}

    public void clearActivity(){
        for(Activity activity : list){
            if(activity != null && !activity.isFinishing()){
                activity.finish();
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        WPXMain.init(this);
    }

    public void exit() {
        clearActivity();

        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
</code>```

However, when I put that WPXMain.init(this); into my own MyApplication, I can neither see the init log, nor use any functionality of the SDK.

I guess it is because the WPXMain.init(this); in MyApplication is not called. Because if it's called, I should see the init log. Here is the init code in SDK:

```<code>public static void init(Application app) {
    init(app, false);
}

public static void init(Application app, boolean isBleModel) {
    WPXUtils.log(TAG, "init");
    WPXMain.Bean.wpx.filter.add("NP100");
    if(app != null) {
        WPXMain.Bean.wpx.isInit = true;
        WPXMain.Bean.wpx.isBleModel = isBleModel;
        WPXMain.Bean.wpx.app = app;
        if(isBleModel) {
            WPXMain.Bean.wpx.wblec = com.wpx.WPXBleControl.Bean.getInstance();
            WPXMain.Bean.wpx.wblec.init(app);
        } else {
            WPXMain.Bean.wpx.wbc = com.wpx.WPXBluetoothControl.Bean.getInstance();
            WPXMain.Bean.wpx.wbc.init(app);
            regReceiver();
        }

    }
}
</code>```

Any idea? Thank you guys.

答:
In your Manifest file mention your application name</p>

```<code><application
    android:name=".MyApplication"

    >
</code>```

Body:
When I try to connect my Android APP to BlueTooth printer, the key method is never called. I followed the introduction of SDK:

Add permission

Init SDK in Application.onCreate()

public void onCreate() {
    super.onCreate();
    WPXMain.init(this);
}

Wnen I run sample offered by SDK, I can see log:

03-29 11:15:25.399 10820-10820/com.wpx.printer.sample D/WPXMain: init

Here is the sample code:

public class MyApplication extends Application {
    private List<Activity> list = new ArrayList<Activity>();

    public void addActivity(Activity activity) {}

    public void clearActivity(){
        for(Activity activity : list){
            if(activity != null && !activity.isFinishing()){
                activity.finish();
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        WPXMain.init(this);
    }

    public void exit() {
        clearActivity();

        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}

However, when I put that WPXMain.init(this); into my own MyApplication, I can neither see the init log, nor use any functionality of the SDK.

I guess it is because the WPXMain.init(this); in MyApplication is not called. Because if it's called, I should see the init log. Here is the init code in SDK:

public static void init(Application app) {
    init(app, false);
}

public static void init(Application app, boolean isBleModel) {
    WPXUtils.log(TAG, "init");
    WPXMain.Bean.wpx.filter.add("NP100");
    if(app != null) {
        WPXMain.Bean.wpx.isInit = true;
        WPXMain.Bean.wpx.isBleModel = isBleModel;
        WPXMain.Bean.wpx.app = app;
        if(isBleModel) {
            WPXMain.Bean.wpx.wblec = com.wpx.WPXBleControl.Bean.getInstance();
            WPXMain.Bean.wpx.wblec.init(app);
        } else {
            WPXMain.Bean.wpx.wbc = com.wpx.WPXBluetoothControl.Bean.getInstance();
            WPXMain.Bean.wpx.wbc.init(app);
            regReceiver();
        }

    }
}

Any idea? Thank you guys.

Body:
In your Manifest file mention your application name

<application
    android:name=".MyApplication"

    >


问:
Regular Expression to match account number consisting of specific 3 character string followed by 9 digits
I'm trying to craft a regular expression which will match an account number which consists of specific 3 characters strings followed by 9 digits.
e.g.

```<code>abc123456789
xyz123456789
def987654321
</code>```

I've figured out how to accomplish with the following expression but wanted to know if there was a better way:

```<code>abc[0-9]{9}|xyz[0-9]{9}|def[0-9]{9}
</code>```

答:
If the account number can only consist of abc, def or xyz, you can use | specifically for those strings, as pointed out by Jorge Campos:

```<code>(abc|def|xyz)\d{9}
</code>```

However, assuming it can start with any combination of non-numerical characters, this is the most compact way to put it:

```<code>\D{3}\d{9}
</code>```

Body:
I'm trying to craft a regular expression which will match an account number which consists of specific 3 characters strings followed by 9 digits.
e.g.

abc123456789
xyz123456789
def987654321

I've figured out how to accomplish with the following expression but wanted to know if there was a better way:

abc[0-9]{9}|xyz[0-9]{9}|def[0-9]{9}

Body:
If the account number can only consist of abc, def or xyz, you can use | specifically for those strings, as pointed out by Jorge Campos:

(abc|def|xyz)\d{9}

However, assuming it can start with any combination of non-numerical characters, this is the most compact way to put it:

\D{3}\d{9}


问:
Where can I permanently set java heap size on Windows pc?
I recently downloaded the latest Java 1.6 JDK. I'm using VisualVM which came with the SDK to test/monitor my webapp (using Tomcat server) on my local pc. I'm running Windows XP.

Where are the parameters located for setting the min. and max. java heap size? VisualVM indicates that the max. heap is at about 256mb. I looked in the server.xml file for Tomcat, but didn't find any settings in there.

Thank you

答: The best place to place these settings is in setenv.bat or setenv.sh in the bin folder. Take a look at a recent SO question on the same topic which has excellent answers.


问:
Setting A Callback Function To A Timer
I'm so close to finishing this program and I can't figure out this last piece. I have my webpage reaching out to a server to grab a randomly generated number, which it then plots onto a graph. I need to set it so it plots the data points every 2 seconds and I can't figure out how to set up my setInterval command. I can get it to work with a for loop, but this obviously isn't timed. It also crashes when I set the limit past a certain threshold, which may indicate a problem when trying to use the timer. I'll post my code along with some of the things I've tried.

Code first:

```<code>function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

context.strokeStyle="#0000FF";
context.beginPath();

for (i = 1; i <= 10; i++)
{
  getRequest(function(random)
  {
    var diff = (dataSet[0]*100) - (dataSet[1] * 100);
    diff = diff/5;
    y = y+(diff*23);

    context.lineTo(x, y);
    context.moveTo(x, y);
    context.stroke();

    x=x+xScale;
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    dataSet[0] = dataSet[1];
  });
}
}
</code>```

I have it set to a loop for debugging purposes right now.

The callback function reaches to an XMLHttpRequest to grab the random number (I can post this code too if needed).

What I was trying to do was implement setInterval along with some booleans to stop the function upon a second function call.

Something like this:

```<code>var isRunning = false;

function plotData(dataSet)
{
 if (isRunning == false)
 {
  isRunning = true;
 }

 if (isRunning == true)
 {
  isRunning = false;
  myTimer = clearInterval();
 }
var myTimer;
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

context.strokeStyle="#0000FF";
context.beginPath();

 while (isRunning == true)
 {
  myTimer = setInterval(function()
  {
   getRequest(function(random)
   {
    var diff = (dataSet[0]*100) - (dataSet[1] * 100);
    diff = diff/5;
    y = y+(diff*23);

    context.lineTo(x, y);
    context.moveTo(x, y);
    context.stroke();

    x=x+xScale;
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    dataSet[0] = dataSet[1];
   });
  }, 2000);

 }
}
</code>```

I added a global boolean isRunning for handling purposes.

I set isRunning to true if it was previously false (indicating that it is now in progress).

I set isRunning to false if it was previously true then proceed to clearInterval to stop it.

And lastly set up a while loop for the callback function to execute while isRunning == true

All this did was crash my program. How can I use the setInterval function correctly in this case?

答:
Instead of a setInterval, use can use setTimeout.

There will be one function that calls the XMLHttpRequest and handles the response. Call this function in a setTimeout from the response callback in the XMLHttpRequest. This will mean that the next request will always be 2 seconds after the last response (and the last plot). This will avoid using the flags to check if there is a request in progress.

```<code>function plotData(dataSet) {
  var x = xScale+20; // 20 = margin length
  var y = 260;    //origin of graph

  context.strokeStyle="#0000FF";
  context.beginPath();

  var counter = 10;

  function plotPoint() {
    getRequest(function(data) {
      var diff = (dataSet[0]*100) - (dataSet[1] * 100);
      diff = diff/5;
      y = y+(diff*23);

      context.lineTo(x, y);
      context.moveTo(x, y);
      context.stroke();

      x = x + xScale;
      console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
      dataSet[0] = dataSet[1];

      if (counter-- > 0) {
        setTimeout(plotPoint, 2000);
      }
    }
  }

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

Title: Setting A Callback Function To A Timer

Body:
I'm so close to finishing this program and I can't figure out this last piece. I have my webpage reaching out to a server to grab a randomly generated number, which it then plots onto a graph. I need to set it so it plots the data points every 2 seconds and I can't figure out how to set up my setInterval command. I can get it to work with a for loop, but this obviously isn't timed. It also crashes when I set the limit past a certain threshold, which may indicate a problem when trying to use the timer. I'll post my code along with some of the things I've tried.

Code first:

function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

context.strokeStyle="#0000FF";
context.beginPath();

for (i = 1; i <= 10; i++)
{
  getRequest(function(random)
  {
    var diff = (dataSet[0]*100) - (dataSet[1] * 100);
    diff = diff/5;
    y = y+(diff*23);

    context.lineTo(x, y);
    context.moveTo(x, y);
    context.stroke();

    x=x+xScale;
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    dataSet[0] = dataSet[1];
  });
}
}

I have it set to a loop for debugging purposes right now.

The callback function reaches to an XMLHttpRequest to grab the random number (I can post this code too if needed).

What I was trying to do was implement setInterval along with some booleans to stop the function upon a second function call.

Something like this:

var isRunning = false;

function plotData(dataSet)
{
 if (isRunning == false)
 {
  isRunning = true;
 }

 if (isRunning == true)
 {
  isRunning = false;
  myTimer = clearInterval();
 }
var myTimer;
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

context.strokeStyle="#0000FF";
context.beginPath();

 while (isRunning == true)
 {
  myTimer = setInterval(function()
  {
   getRequest(function(random)
   {
    var diff = (dataSet[0]*100) - (dataSet[1] * 100);
    diff = diff/5;
    y = y+(diff*23);

    context.lineTo(x, y);
    context.moveTo(x, y);
    context.stroke();

    x=x+xScale;
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    dataSet[0] = dataSet[1];
   });
  }, 2000);

 }
}

I added a global boolean isRunning for handling purposes.

I set isRunning to true if it was previously false (indicating that it is now in progress).

I set isRunning to false if it was previously true then proceed to clearInterval to stop it.

And lastly set up a while loop for the callback function to execute while isRunning == true

All this did was crash my program. How can I use the setInterval function correctly in this case?

Body:
Instead of a setInterval, use can use setTimeout.

There will be one function that calls the XMLHttpRequest and handles the response. Call this function in a setTimeout from the response callback in the XMLHttpRequest. This will mean that the next request will always be 2 seconds after the last response (and the last plot). This will avoid using the flags to check if there is a request in progress.

function plotData(dataSet) {
  var x = xScale+20; // 20 = margin length
  var y = 260;    //origin of graph

  context.strokeStyle="#0000FF";
  context.beginPath();

  var counter = 10;

  function plotPoint() {
    getRequest(function(data) {
      var diff = (dataSet[0]*100) - (dataSet[1] * 100);
      diff = diff/5;
      y = y+(diff*23);

      context.lineTo(x, y);
      context.moveTo(x, y);
      context.stroke();

      x = x + xScale;
      console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
      dataSet[0] = dataSet[1];

      if (counter-- > 0) {
        setTimeout(plotPoint, 2000);
      }
    }
  }

  plotPoint();
}


问:
Externalizing a module in Angular 2
So, i was working on my application and i realized that several modules could be extracted to separate libraries, that could be installed via NPM and reused across other applications. The current structure looks like this:

```<code>app/
    search/
        component1/
        component2/
        component3/
        search.module.ts
        search.service.ts
    login/
    register/
</code>```

Let's say i want to extract search, what's the first step? How do i organize this separate repository? Does it also have a src dir and a package.json? Is there any specific documentation on this topic?

答:
To build an external module that you can install with npm, you should bundle your source files into a distribution folder, using any one of the several module loader formats available: UMD, CJS, AMD, etc. I recommend UMD as its universally loadable by any module loader.

If you want to have your components to work in an AOT build, you'll need to deploy the JS files along with the metadata files. You should also output .d.ts files - mainly for making code completion support available in the IDE of your choice (i.e. I prefer Vscode)

Here is a seed sample application that demonstrates building a re-usable module for distribution:

https://www.npmjs.com/package/ng2-starter-app

https://github.com/pixelbits-mk/ng2-starter-app

The built target to run is:

```<code>gulp module
</code>```

To publish to npm:

```<code>npm publish
</code>```

Title: Externalizing a module in Angular 2

Body:
So, i was working on my application and i realized that several modules could be extracted to separate libraries, that could be installed via NPM and reused across other applications. The current structure looks like this:

app/
    search/
        component1/
        component2/
        component3/
        search.module.ts
        search.service.ts
    login/
    register/

Let's say i want to extract search, what's the first step? How do i organize this separate repository? Does it also have a src dir and a package.json? Is there any specific documentation on this topic?

Body:
To build an external module that you can install with npm, you should bundle your source files into a distribution folder, using any one of the several module loader formats available: UMD, CJS, AMD, etc. I recommend UMD as its universally loadable by any module loader.

If you want to have your components to work in an AOT build, you'll need to deploy the JS files along with the metadata files. You should also output .d.ts files - mainly for making code completion support available in the IDE of your choice (i.e. I prefer Vscode)

Here is a seed sample application that demonstrates building a re-usable module for distribution:

https://www.npmjs.com/package/ng2-starter-app

https://github.com/pixelbits-mk/ng2-starter-app

The built target to run is:

gulp module

To publish to npm:

npm publish


问:
Setting a variable in AppleScript based on a list in a Numbers sheet
AppleScript beginner here. Searching high and low hasn't led me to the answer yet.

I'm using AppleScript to help run youth wrestling tournaments. Each division (based on age) is broken down into weight classes. For example: Novice 80 or Cadet 105.

Once a certain group of kids is put into a certain division/weight class, those kids get added to a new sheet that contains their bracket (think March Madness bracket but a small number of kids wrestling instead of playing basketball).

I've figured out how to get a group into a new sheet where they populate the bracket, but when this new sheet is created, I don't know how to make AppleScript change the name of the sheet to the correct division/weight class. I'm sure it has something to do with creating variables based on a list of the divisions/weight classes (that I have), but I can't figure out how to do it. Here's the relevant portion of the code:

```<code>tell document 1
        set active sheet to the last sheet
        set thisSheet to make new sheet
        set the name of thisSheet to "[Division variable – Weight class variable]"
        tell thisSheet
            delete every table
        end tell
</code>```

Any ideas on how to make AppleScript name the sheet like I want?

答:
To give you a small example that you're able to visualize what you're going after, heres a small snippet. I think its self explanatory, iterate through a list of titles, then apply the names to the sheets.

```<code>set divisionNames to {"Novice", "Cadet"} -- How You Grab These Values Matters
set weightClasses to {"80", "105"} -- These Values Too

tell application "Numbers"
    activate
set thisDocument to make new document
tell thisDocument
    repeat with i from 1 to count of divisionNames
        make new sheet with properties {name:item i of divisionNames & space & item i of weightClasses}
    end repeat
end tell
end tell
</code>```

Alternately, if you're pulling the values from a list as a whole then you could

```<code>set sheetTitles to {"Novice 80", "Cadet 105"}

tell application "Numbers"
activate
set thisDocument to make new document
tell thisDocument
    repeat with division in sheetTitles
        make new sheet with properties {name:division}
    end repeat
end tell
end tell
</code>```

EDIT: In the spirit of helping a low to no budget school/organization.. here's another example answering the second question issued in comments. Again without knowing the structure of your data its hard to give you an exact answer on your specific case. Additionally, here's a link to a site they may help further the advancement on your project. https://iworkautomation.com/numbers/index.html

```<code>(*
set sampleKids to {"John Doe", "Jane Doe", "Johnny Foe", "Janie Foe", "Tommy Joe", "Tammy Joe"}
set sampleDivisions to {"Novice-80", "Novice-85", "Cadet-105", "Cadet-110", "Novice-80", "Cadet-105"}

tell application "Numbers"
activate
set thisDoc to make new document with properties {name:"Wrestling Sample"}
tell thisDoc
    set the name of sheet 1 to "Sign In Sheet"
    tell active sheet
        delete every table
        set newTable to make new table with properties {row count:(count of sampleKids) + 1, column count:2, name:"Sign In Sheet"}
        tell newTable
            set value of cell 1 of column "A" to "Name"
            set value of cell 1 of column "B" to "Division"
            set x to 2
            repeat with eachName in sampleKids
                set value of cell x of column "A" to eachName
                set x to (x + 1)
            end repeat
            set x to 2
            repeat with eachDivision in sampleDivisions
                set value of cell x of column "B" to eachDivision
                set x to (x + 1)
            end repeat
        end tell
    end tell
end tell
end tell
*)

--********** IGNORE ABOVE THIS LINE IT'S ONLY BUILDING A SAMPLE TABLE **********--
--********** SAVE ABOVE TO ANOTHER SCRIPT FOR TESTING WITH NEW TABLE **********--

(*
ERROR HANDLING ISN'T PRESENT - AN EMPTY CELL IN FIRST COLUMN OR CHOSEN COLUMN WILL THROW AN
ERROR SINCE THEY ARE THE IMPORTANT PIECES OF DATA FOR GRABBING LISTS - SAVE SCRIPT
TO NUMBERS SCRIPT FOLDER OF YOUR CHOICE - ENTER ALL INFO ON FIRST TABLE OF FIRST SHEET OF
DOCUMENT THEN RUN SCRIPT - SCRIPT ACCEPTS ANY AMOUNT OF ROWS OR COLUMNS
*)

tell application "Numbers"
activate
-- Display A Simple Reminder That You're About To Lose Some Existing Data
display dialog "This Script Will Delete All Sheets Except The First Sheet Of This Document Before It Proceeds To Make New Sheets & Tables Based On The First Table Of The First Sheet." buttons {"Cancel", "Start"} default button 2 with icon 1
tell document 1
    -- Get A List of the Sheet Names
    set sheetNames to name of sheets
    -- Start With A Fresh Slate, No Old Sheets
    delete (every sheet whose name is not item 1 of sheetNames)
    tell sheet 1
        -- Grab and Set Future Header Values
        set columnHeaders to value of cell of row 1 in table 1
        -- Display A List Of Possible Choices To Create New Sheets With From The List We Make Above
        set chosenColumn to choose from list columnHeaders with prompt "Which Column Do You Want To Use For New Sheets?" default items item 1 of columnHeaders
        set chosenColumn to chosenColumn as text
        tell table 1
            -- Remove All Empty Rows to Help Prevent Error In Script
            set {row_count, col_count} to {count rows, count columns}
            set blank_row to {}
            repeat with x from 1 to col_count
                set blank_row to blank_row & missing value
            end repeat
            set x to 1
            -- Delete Empty Rows In Reverse, It's Logical
            repeat with y from row_count to 1 by -1
                set row_values to value of cells of row y
                if row_values = blank_row then delete row y
            end repeat

            -- Grab A List of All Divisions for Future Use Depending on Choice From Prompt, excluding the First Row Which Is A Header. If You Selected The First Column, We Have to Handle That Differently
            if chosenColumn is item 1 of columnHeaders then
                set theDivisions to the value of every cell of column "A" whose value is not chosenColumn
            else
                set theDivisions to the value of every cell of column named chosenColumn whose value is not chosenColumn
            end if

        end tell
    end tell
    -- Start the New "Sheet Making" Loop
    repeat with division in theDivisions
        -- Make An Empty Blank List At the Start of Every Loop
        set matchingDivisions to {}
        tell table 1 of sheet 1

            -- Get All Rows Matching the Current Division of the Loop We Are On, to Make New Tables With Later
            repeat with x from 1 to count of cells
                if the value of cell x is division then
                    -- Put All Data About the Rows We Gathered Above Into the Empty List We Made
                    set the end of matchingDivisions to value of cells of row of cell x
                end if
            end repeat
            -- Reset x, Because I'm Not Creative and Want to Use It Later
            set x to 1
        end tell
        -- If The Sheet Of the Division We Are On, of the Loop, Doesn't Exist, Make It
        if not (exists sheet division) then
            make new sheet with properties {name:division}
            tell sheet division
                -- Start With A Fresh Slate On This New Sheet
                delete every table
                -- Make the Table With All Relevant Parameters
                set currentDivisionTable to make new table with properties ¬
                    {row count:((count of matchingDivisions) + 1), column count:count of item 1 of matchingDivisions, name:division}
                tell currentDivisionTable
                    set x to 1
                    -- Set The Header Values from A List We Created Earlier
                    repeat with theHeader in columnHeaders
                        set the value of cell x to theHeader
                        set x to (x + 1)
                    end repeat
                    -- Reset x Again, I'm Lazy
                    set x to 1
                    -- Set Starting Point to Start Filling The Table, Compensate For Our Headers
                    set rowIndex to 1
                    set columnIndex to 0
                    -- Start Filling The Table With Data, Which Comes From The List Earlier
                    repeat with x from 1 to count of the matchingDivisions
                        set rowData to item x of the matchingDivisions
                        tell row (rowIndex + x)
                            repeat with i from 1 to the count of rowData
                                tell cell (columnIndex + i)
                                    set value to item i of rowData
                                end tell
                            end repeat
                        end tell
                    end repeat
                end tell
            end tell
        end if
    end repeat
    -- Return To the First Sheet
    set the active sheet to the first sheet
    -- Display Notification That The Tables Are Done Being Made -- OPTIONAL
    display notification "Processing is complete." with title "Numbers Table Converter" subtitle "All Tables Have Been Made." sound name "Hero"
end tell
end tell
</code>```

Body:
AppleScript beginner here. Searching high and low hasn't led me to the answer yet.

I'm using AppleScript to help run youth wrestling tournaments. Each division (based on age) is broken down into weight classes. For example: Novice 80 or Cadet 105.

Once a certain group of kids is put into a certain division/weight class, those kids get added to a new sheet that contains their bracket (think March Madness bracket but a small number of kids wrestling instead of playing basketball).

I've figured out how to get a group into a new sheet where they populate the bracket, but when this new sheet is created, I don't know how to make AppleScript change the name of the sheet to the correct division/weight class. I'm sure it has something to do with creating variables based on a list of the divisions/weight classes (that I have), but I can't figure out how to do it. Here's the relevant portion of the code:

tell document 1
        set active sheet to the last sheet
        set thisSheet to make new sheet
        set the name of thisSheet to "[Division variable – Weight class variable]"
        tell thisSheet
            delete every table
        end tell

Any ideas on how to make AppleScript name the sheet like I want?

Body:
To give you a small example that you're able to visualize what you're going after, heres a small snippet. I think its self explanatory, iterate through a list of titles, then apply the names to the sheets.

set divisionNames to {"Novice", "Cadet"} -- How You Grab These Values Matters
set weightClasses to {"80", "105"} -- These Values Too

tell application "Numbers"
    activate
set thisDocument to make new document
tell thisDocument
    repeat with i from 1 to count of divisionNames
        make new sheet with properties {name:item i of divisionNames & space & item i of weightClasses}
    end repeat
end tell
end tell

Alternately, if you're pulling the values from a list as a whole then you could

set sheetTitles to {"Novice 80", "Cadet 105"}

tell application "Numbers"
activate
set thisDocument to make new document
tell thisDocument
    repeat with division in sheetTitles
        make new sheet with properties {name:division}
    end repeat
end tell
end tell

EDIT: In the spirit of helping a low to no budget school/organization.. here's another example answering the second question issued in comments. Again without knowing the structure of your data its hard to give you an exact answer on your specific case. Additionally, here's a link to a site they may help further the advancement on your project. https://iworkautomation.com/numbers/index.html

(*
set sampleKids to {"John Doe", "Jane Doe", "Johnny Foe", "Janie Foe", "Tommy Joe", "Tammy Joe"}
set sampleDivisions to {"Novice-80", "Novice-85", "Cadet-105", "Cadet-110", "Novice-80", "Cadet-105"}

tell application "Numbers"
activate
set thisDoc to make new document with properties {name:"Wrestling Sample"}
tell thisDoc
    set the name of sheet 1 to "Sign In Sheet"
    tell active sheet
        delete every table
        set newTable to make new table with properties {row count:(count of sampleKids) + 1, column count:2, name:"Sign In Sheet"}
        tell newTable
            set value of cell 1 of column "A" to "Name"
            set value of cell 1 of column "B" to "Division"
            set x to 2
            repeat with eachName in sampleKids
                set value of cell x of column "A" to eachName
                set x to (x + 1)
            end repeat
            set x to 2
            repeat with eachDivision in sampleDivisions
                set value of cell x of column "B" to eachDivision
                set x to (x + 1)
            end repeat
        end tell
    end tell
end tell
end tell
*)

--********** IGNORE ABOVE THIS LINE IT'S ONLY BUILDING A SAMPLE TABLE **********--
--********** SAVE ABOVE TO ANOTHER SCRIPT FOR TESTING WITH NEW TABLE **********--

(*
ERROR HANDLING ISN'T PRESENT - AN EMPTY CELL IN FIRST COLUMN OR CHOSEN COLUMN WILL THROW AN
ERROR SINCE THEY ARE THE IMPORTANT PIECES OF DATA FOR GRABBING LISTS - SAVE SCRIPT
TO NUMBERS SCRIPT FOLDER OF YOUR CHOICE - ENTER ALL INFO ON FIRST TABLE OF FIRST SHEET OF
DOCUMENT THEN RUN SCRIPT - SCRIPT ACCEPTS ANY AMOUNT OF ROWS OR COLUMNS
*)

tell application "Numbers"
activate
-- Display A Simple Reminder That You're About To Lose Some Existing Data
display dialog "This Script Will Delete All Sheets Except The First Sheet Of This Document Before It Proceeds To Make New Sheets & Tables Based On The First Table Of The First Sheet." buttons {"Cancel", "Start"} default button 2 with icon 1
tell document 1
    -- Get A List of the Sheet Names
    set sheetNames to name of sheets
    -- Start With A Fresh Slate, No Old Sheets
    delete (every sheet whose name is not item 1 of sheetNames)
    tell sheet 1
        -- Grab and Set Future Header Values
        set columnHeaders to value of cell of row 1 in table 1
        -- Display A List Of Possible Choices To Create New Sheets With From The List We Make Above
        set chosenColumn to choose from list columnHeaders with prompt "Which Column Do You Want To Use For New Sheets?" default items item 1 of columnHeaders
        set chosenColumn to chosenColumn as text
        tell table 1
            -- Remove All Empty Rows to Help Prevent Error In Script
            set {row_count, col_count} to {count rows, count columns}
            set blank_row to {}
            repeat with x from 1 to col_count
                set blank_row to blank_row & missing value
            end repeat
            set x to 1
            -- Delete Empty Rows In Reverse, It's Logical
            repeat with y from row_count to 1 by -1
                set row_values to value of cells of row y
                if row_values = blank_row then delete row y
            end repeat

            -- Grab A List of All Divisions for Future Use Depending on Choice From Prompt, excluding the First Row Which Is A Header. If You Selected The First Column, We Have to Handle That Differently
            if chosenColumn is item 1 of columnHeaders then
                set theDivisions to the value of every cell of column "A" whose value is not chosenColumn
            else
                set theDivisions to the value of every cell of column named chosenColumn whose value is not chosenColumn
            end if

        end tell
    end tell
    -- Start the New "Sheet Making" Loop
    repeat with division in theDivisions
        -- Make An Empty Blank List At the Start of Every Loop
        set matchingDivisions to {}
        tell table 1 of sheet 1

            -- Get All Rows Matching the Current Division of the Loop We Are On, to Make New Tables With Later
            repeat with x from 1 to count of cells
                if the value of cell x is division then
                    -- Put All Data About the Rows We Gathered Above Into the Empty List We Made
                    set the end of matchingDivisions to value of cells of row of cell x
                end if
            end repeat
            -- Reset x, Because I'm Not Creative and Want to Use It Later
            set x to 1
        end tell
        -- If The Sheet Of the Division We Are On, of the Loop, Doesn't Exist, Make It
        if not (exists sheet division) then
            make new sheet with properties {name:division}
            tell sheet division
                -- Start With A Fresh Slate On This New Sheet
                delete every table
                -- Make the Table With All Relevant Parameters
                set currentDivisionTable to make new table with properties ¬
                    {row count:((count of matchingDivisions) + 1), column count:count of item 1 of matchingDivisions, name:division}
                tell currentDivisionTable
                    set x to 1
                    -- Set The Header Values from A List We Created Earlier
                    repeat with theHeader in columnHeaders
                        set the value of cell x to theHeader
                        set x to (x + 1)
                    end repeat
                    -- Reset x Again, I'm Lazy
                    set x to 1
                    -- Set Starting Point to Start Filling The Table, Compensate For Our Headers
                    set rowIndex to 1
                    set columnIndex to 0
                    -- Start Filling The Table With Data, Which Comes From The List Earlier
                    repeat with x from 1 to count of the matchingDivisions
                        set rowData to item x of the matchingDivisions
                        tell row (rowIndex + x)
                            repeat with i from 1 to the count of rowData
                                tell cell (columnIndex + i)
                                    set value to item i of rowData
                                end tell
                            end repeat
                        end tell
                    end repeat
                end tell
            end tell
        end if
    end repeat
    -- Return To the First Sheet
    set the active sheet to the first sheet
    -- Display Notification That The Tables Are Done Being Made -- OPTIONAL
    display notification "Processing is complete." with title "Numbers Table Converter" subtitle "All Tables Have Been Made." sound name "Hero"
end tell
end tell


问:
Char Array to Lambda Expression
I am now learning lambda expression used in Java.
In this case, I have a problem in changing char[] array to lambda expression.
So, I would like to ask some help.
My sample code is below.

```<code>    Map<String, String> tempMap = new HashMap<String, String>();
    tempMap.put("a", "A");
    tempMap.put("b", "B");
    tempMap.put("c", "C");
    tempMap.put("d", "D");
    tempMap.put("e", "E");
    String tempStr = "abcdef";
    StringBuilder tempBuilder = new StringBuilder();
    char[] tempArray = tempStr.toCharArray();
    for(char c : tempArray) {
    tempBuilder.append(tempMap.getOrDefault(String.ValueOf(c),
    String.ValueOf(c));
    }
</code>```

Result should be "ABCDEf". Thanks.

答:
You can use CharSequence#codePoints to create a stream of characters (which is more surrogate-pair safe than chars), make your transformations, and then use Collectors.joining().

```<code>String input = "abcdef";
String output = input.codePoints()
                     .mapToObj(Character::toChars)
                     .map(String::valueOf)
                     .map(s -> tempMap.getOrDefault(s, s))
                     .collect(Collectors.joining());
</code>```

Title: Char Array to Lambda Expression

Body:
I am now learning lambda expression used in Java.
In this case, I have a problem in changing char[] array to lambda expression.
So, I would like to ask some help.
My sample code is below.

    Map<String, String> tempMap = new HashMap<String, String>();
    tempMap.put("a", "A");
    tempMap.put("b", "B");
    tempMap.put("c", "C");
    tempMap.put("d", "D");
    tempMap.put("e", "E");
    String tempStr = "abcdef";
    StringBuilder tempBuilder = new StringBuilder();
    char[] tempArray = tempStr.toCharArray();
    for(char c : tempArray) {
    tempBuilder.append(tempMap.getOrDefault(String.ValueOf(c),
    String.ValueOf(c));
    }

Result should be "ABCDEf". Thanks.

Body:
You can use CharSequence#codePoints to create a stream of characters (which is more surrogate-pair safe than chars), make your transformations, and then use Collectors.joining().

String input = "abcdef";
String output = input.codePoints()
                     .mapToObj(Character::toChars)
                     .map(String::valueOf)
                     .map(s -> tempMap.getOrDefault(s, s))
                     .collect(Collectors.joining());


答:
You've not exposed a C interface. You still have your function returning a C++ class rather than something recognizable by C. Expose your class as void *s instead. For example:

```<code>class MyClass
{
//private members
public:
//public members
    int MyMethod(int argument) const;
    virtual float MyVirtualMethod();
    virtual ~MyClass() {}
};

class MySecondClass : public MyClass
{
public:
    virtual float MyVirtualMethod();
    int MyMethod2(int argument) const;
};

extern "C" {
    void * CreateMyClass()
    {
        return static_cast<void *>(new(std::nothrow) MyClass);
    }

    void * CreateMySecondClass()
    {
        //Note the cast to the base class first (This is needed
        //because it might actually change the position of the pointer,
        //which would not be automatically adjusted later)
        return static_cast<void *>(static_cast<MyClass *>(new(std::nothrow) MySecondClass));
    }

    int CallMyClassMethod(void * thisMember, int argument)
    {
        return static_cast<MyClass *>(thisMember)->MyMethod(argument);
    }

    float CallMyVirtualMethod(void * thisMember)
    {
        return static_cast<MyClass *>(thisMember)->MyVirtualMethod();
    }

    int CallMyMethod2(void thisMember, int argument)
    {
        MyClass * convertedToMyClass = static_cast<MyClass *>(thisMember);
        MySecondClass * asSecondClass = dynamic_cast<MySecondClass *>(convertedToMyClass);
        if (!asSecondClass)
        {
            //Return error (thisMember not an instance of MySecondClass)
        }
        else
        {
            return asSecondClass->MyMethod2(argument);
        }
    }

    void DestroyMyClass(void * classMember)
    {
        delete static_cast<MyClass *>(classMember);
    }
}
</code>```

This will make your class usable by D, but also by C (and every other language that binds to C) as well.

Title: Using C++ class in D

Body:
You've not exposed a C interface. You still have your function returning a C++ class rather than something recognizable by C. Expose your class as void *s instead. For example:

class MyClass
{
//private members
public:
//public members
    int MyMethod(int argument) const;
    virtual float MyVirtualMethod();
    virtual ~MyClass() {}
};

class MySecondClass : public MyClass
{
public:
    virtual float MyVirtualMethod();
    int MyMethod2(int argument) const;
};

extern "C" {
    void * CreateMyClass()
    {
        return static_cast<void *>(new(std::nothrow) MyClass);
    }

    void * CreateMySecondClass()
    {
        //Note the cast to the base class first (This is needed
        //because it might actually change the position of the pointer,
        //which would not be automatically adjusted later)
        return static_cast<void *>(static_cast<MyClass *>(new(std::nothrow) MySecondClass));
    }

    int CallMyClassMethod(void * thisMember, int argument)
    {
        return static_cast<MyClass *>(thisMember)->MyMethod(argument);
    }

    float CallMyVirtualMethod(void * thisMember)
    {
        return static_cast<MyClass *>(thisMember)->MyVirtualMethod();
    }

    int CallMyMethod2(void thisMember, int argument)
    {
        MyClass * convertedToMyClass = static_cast<MyClass *>(thisMember);
        MySecondClass * asSecondClass = dynamic_cast<MySecondClass *>(convertedToMyClass);
        if (!asSecondClass)
        {
            //Return error (thisMember not an instance of MySecondClass)
        }
        else
        {
            return asSecondClass->MyMethod2(argument);
        }
    }

    void DestroyMyClass(void * classMember)
    {
        delete static_cast<MyClass *>(classMember);
    }
}

This will make your class usable by D, but also by C (and every other language that binds to C) as well.


问:
Trim whitespaces on a String
How can I trim whitespaces on strings from their left and right sides?

For example,

```<code>___abc_d__
</code>```

will be:

```<code>abc_d
</code>```

答:
Python has lstrip and rstrip methods on strings that trim whitespace from their left and right sides, respectively:

```<code>>>> '   abc d  '.lstrip()
'abc d  '
>>> 'abc d  '.rstrip()
'abc d'
</code>```

Combine this with len(s) giving you the length of a string s, and you should be good to go!

Title: Trim whitespaces on a String

Body:
How can I trim whitespaces on strings from their left and right sides?

For example,

___abc_d__

will be:

abc_d

Body:
Python has lstrip and rstrip methods on strings that trim whitespace from their left and right sides, respectively:

>>> '   abc d  '.lstrip()
'abc d  '
>>> 'abc d  '.rstrip()
'abc d'

Combine this with len(s) giving you the length of a string s, and you should be good to go!


问:
Can you execute chdk scripts externally via USB?
I have been tinkering around with CHDK (canon hack development kit). I have been able to run chdk via SD card on my powershot g12 and even been able to run a script on it.

My interest lies more in controlling this externally via a USB cable. For starters I want to try controlling it from the computer, then maybe another device.

I have been to the CHDK website http://chdk.wikia.com/wiki/CHDK and peeked around their forum as well but have not seen any mention of external execution.

答:
Yes, you can.  There are two approaches I've used with some success.

1.) I can control my Powershot G9 using CHDKPTP (https://app.assembla.com/spaces/chdkptp/wiki).  I'm using Ubuntu 16.04 and the r735 binary from the website.  The GUI lets you control the camera and run scripts.  This approach should work for any camera that CHDK supports.  (There is also a python binding for CHDKPTP, although I haven't managed to successfully build it yet.)

2.) Another approach is to use gphoto2, if your camera is supported by gphoto2. (NOTE:  It doesn't look like the G12 is supported by gphoto2, but I'm including it here in case it's useful to others)  On the G9, CHDK adds a property chdk_script to the available options in gphoto2.  Then scripts should be runnable with

gphoto2 --set-config chdk_script="scriptname"

The gphoto2 approach is demonstrated here (https://www.youtube.com/watch?v=v_42jd9tGF0)


问:
Component does not remount when route parameters change
I'm working on a react application using react-router. I have a project page that has a url as follows:

```<code>myapplication.com/project/unique-project-id
</code>```

When the project component loads, I trigger a data request for that project from the componentDidMount event. I'm now running into an issue where if I switch directly between two projects so only the id changes like this...

```<code>myapplication.com/project/982378632
myapplication.com/project/782387223
myapplication.com/project/198731289
</code>```

componentDidMount is not triggered again so the data is not refreshed. Is there another lifecycle event I should be using to trigger my data request or a different strategy to tackle this issue?

答:
You have to be clear, that a route change will not cause a page refresh, you have to handle it yourself.</p>

```<code>import theThingsYouNeed from './whereYouFindThem'

export default class Project extends React.Component {

    componentWillMount() {

        this.state = {
            id: this.props.router.params.id
        }

        // fire action to update redux project store
        this.props.dispatch(fetchProject(this.props.router.params.id))
    }

    componentDidUpdate(prevProps, prevState) {
         /**
         * this is the initial render
         * without a previous prop change
         */
        if(prevProps == undefined) {
            return false
        }

        /**
         * new Project in town ?
         */
        if (this.state.id != this.props.router.params.id) {
           this.props.dispatch(fetchProject(this.props.router.params.id))
           this.setState({id: this.props.router.params.id})
        }

    }

    render() { <Project .../> }
}
</code>```

Body:
I'm working on a react application using react-router. I have a project page that has a url as follows:

myapplication.com/project/unique-project-id

When the project component loads, I trigger a data request for that project from the componentDidMount event. I'm now running into an issue where if I switch directly between two projects so only the id changes like this...

myapplication.com/project/982378632
myapplication.com/project/782387223
myapplication.com/project/198731289

componentDidMount is not triggered again so the data is not refreshed. Is there another lifecycle event I should be using to trigger my data request or a different strategy to tackle this issue?

Body:
You have to be clear, that a route change will not cause a page refresh, you have to handle it yourself.

import theThingsYouNeed from './whereYouFindThem'

export default class Project extends React.Component {

    componentWillMount() {

        this.state = {
            id: this.props.router.params.id
        }

        // fire action to update redux project store
        this.props.dispatch(fetchProject(this.props.router.params.id))
    }

    componentDidUpdate(prevProps, prevState) {
         /**
         * this is the initial render
         * without a previous prop change
         */
        if(prevProps == undefined) {
            return false
        }

        /**
         * new Project in town ?
         */
        if (this.state.id != this.props.router.params.id) {
           this.props.dispatch(fetchProject(this.props.router.params.id))
           this.setState({id: this.props.router.params.id})
        }

    }

    render() { <Project .../> }
}


问:
I am having to use RegEx to validate several parts of a form
For this project, I have to create a pizza delivery form. There are multiple steps, and the first part is to create a form that validates the user's input. So far I have been able to partially tackle this problem. My question is
1: Is there a more concise for validating?
2: I am trying to make it so that the submit button only appears once all the fields are validated, however, I can't figure out how to do that.
Below is my GitHub link

https://github.com/jcast90/JavaScript-RegEx-Form

```<code>var addressType = document.getElementById('addressType');
var submit = document.getElementById('submit');
var input = document.getElementById('otherInput');
var allInputs = document.querySelectorAll('input[type="text"]');

addressType.addEventListener('change', function () {
    if (addressType.value === 'other') {
        input.classList.remove('hidden');
    } else {
        input.classList.add('hidden');
    }
}, false);

var state = document.getElementById('state');
var phone = document.getElementById('phone');
var name = document.getElementById('name');
var zip = document.getElementById('zip');
var email = document.getElementById('email');

// NAME VERIFICATION => + check if empty
name.addEventListener('focusout', focus, false);
function focus() {
    if (name.value.match(/^[a-zA-z ]*$/)) {
        name.style.border = 'solid 3px green';
        return true;
    } else {
        name.style.border = 'solid 3px red';
        name.value = '';
    }
}

// ZIP VERIFICATION => + check if empty
zip.addEventListener('focusout', zipF, false);
function zipF() {
    var zipTest = /^([0-9]{5}(?:-[0-9]{4})?)/;
    if (zip.value.match(zipTest)) {
        zip.style.border = 'solid 3px green';
        return true;
    } else {
        zip.style.border = 'solid 3px red';
    }
}

// EMAIL VERIFICATION => + check if empty
email.addEventListener('focusout', emailF, false);
function emailF() {
    var emailTest = /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})*$/;
    if (email.value.match(emailTest)) {
        email.style.border = 'solid 3px green';
        return true;
    } else {
        email.style.border = 'solid 3px red';
    }
}

// STATE VERIFICATION => + check if empty
var state = document.getElementById('state');
state.addEventListener('focusout', stateF, false);
function stateF() {
    var stateTest = /^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY |O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$/;
    if (state.value.match(stateTest)) {
        state.style.border = 'solid 3px green';
        return true;
    } else {
        state.style.border = 'solid 3px red';
        return state.value = '';
    }
}

// PHONE VERIFICATION => add to check if empty
var phone = document.getElementById('phone');
phone.addEventListener('focusout', phoneF, false);
function phoneF() {
    var phoneTest = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (phone.value.match(phoneTest)) {
        phone.style.border = 'solid 3px green';
        return true;
    } else {
        phone.style.border = 'solid 3px red';
        return phone.value = '';
    }
}

function inputsTrue() {
    if (allInputs === true) {
        submit.classList.remove('hidden');
    } else {
        submit.classList.add('hidden');
    }
}

inputsTrue();
</code>```

答:
Since it looks like this is an assignment, I've done my best to give hints instead of just giving you the answer.

Input elements have a pattern attribute. You can use this to more easily check the input against a regular expression without the need for any Javascript.

There is a :valid CSS pseudo class. You can use this to style invalid elements instead of directly applying styles in an event listener. You can also use it to style the entire form (and thus any child elements) if any input is invalid, this would be my prefered solution for hiding the submit button.

It may be the case that your teacher wants you to use Javascript for validation, in this case you can change a few things to make your life a bit easier.

You may have noticed that you have a lot of repeated code, you can pull this out into its own function that accepts the input to check, and the regex to check it against and applies the correct style depending on whether or not the regex matches. Once this is done, you can just call the function in each event listener with the correct regex and element.

What happens if you suddenly decide that instead of invalid inputs getting a red border, the border should be orange? Right now you would have to go back and change every function in your code. To remedy this situation, you could add and remove a class like .valid / .invalid to style the input.

If you use a .valid class, it is pretty easy to check if everything is valid. You can check if any elements with .invalid exist, or you can check that every one of your inputs has .valid.

Body:
For this project, I have to create a pizza delivery form. There are multiple steps, and the first part is to create a form that validates the user's input. So far I have been able to partially tackle this problem. My question is
1: Is there a more concise for validating?
2: I am trying to make it so that the submit button only appears once all the fields are validated, however, I can't figure out how to do that.
Below is my GitHub link

https://github.com/jcast90/JavaScript-RegEx-Form

var addressType = document.getElementById('addressType');
var submit = document.getElementById('submit');
var input = document.getElementById('otherInput');
var allInputs = document.querySelectorAll('input[type="text"]');

addressType.addEventListener('change', function () {
    if (addressType.value === 'other') {
        input.classList.remove('hidden');
    } else {
        input.classList.add('hidden');
    }
}, false);

var state = document.getElementById('state');
var phone = document.getElementById('phone');
var name = document.getElementById('name');
var zip = document.getElementById('zip');
var email = document.getElementById('email');

// NAME VERIFICATION => + check if empty
name.addEventListener('focusout', focus, false);
function focus() {
    if (name.value.match(/^[a-zA-z ]*$/)) {
        name.style.border = 'solid 3px green';
        return true;
    } else {
        name.style.border = 'solid 3px red';
        name.value = '';
    }
}

// ZIP VERIFICATION => + check if empty
zip.addEventListener('focusout', zipF, false);
function zipF() {
    var zipTest = /^([0-9]{5}(?:-[0-9]{4})?)/;
    if (zip.value.match(zipTest)) {
        zip.style.border = 'solid 3px green';
        return true;
    } else {
        zip.style.border = 'solid 3px red';
    }
}

// EMAIL VERIFICATION => + check if empty
email.addEventListener('focusout', emailF, false);
function emailF() {
    var emailTest = /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})*$/;
    if (email.value.match(emailTest)) {
        email.style.border = 'solid 3px green';
        return true;
    } else {
        email.style.border = 'solid 3px red';
    }
}

// STATE VERIFICATION => + check if empty
var state = document.getElementById('state');
state.addEventListener('focusout', stateF, false);
function stateF() {
    var stateTest = /^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY |O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$/;
    if (state.value.match(stateTest)) {
        state.style.border = 'solid 3px green';
        return true;
    } else {
        state.style.border = 'solid 3px red';
        return state.value = '';
    }
}

// PHONE VERIFICATION => add to check if empty
var phone = document.getElementById('phone');
phone.addEventListener('focusout', phoneF, false);
function phoneF() {
    var phoneTest = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (phone.value.match(phoneTest)) {
        phone.style.border = 'solid 3px green';
        return true;
    } else {
        phone.style.border = 'solid 3px red';
        return phone.value = '';
    }
}

function inputsTrue() {
    if (allInputs === true) {
        submit.classList.remove('hidden');
    } else {
        submit.classList.add('hidden');
    }
}

inputsTrue();


问:
Iterate over JSON with PHP
I cannot figure out how to get the following keys/values from the JSON below:

I need to print out in a for loop:

'projects' i.e 'test-project-1'

'datasets' i.e 'dataset1'

'permissions' i.e 'role: WRITER, group: test1@test.com'

```<code>{
   "projects":{
      "test-project-1":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      },
      "test-project-2":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      }
   }
}
</code>```

I tried this but the only thing that prints out is "Array".

Something like this does not work:

```<code>$new_json = {path_to_json};
$new_projects = $new_json['projects'];
foreach ($new_projects as $project) {
    echo $project . "<br>";
    foreach ($new_projects['datasets'] as $datasets){
        echo $datasets . "<br>";
    }
}
</code>```

答:
PHP code demo</p>

```<code>$json='{
   "projects":{
      "test-project-1":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      },
      "test-project-2":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      }
   }
}';
$array=  json_decode($json,true);
foreach($array["projects"] as $projectName => $projects)
{
    echo "Project name ".$projectName."<br/>";
    foreach($projects["datasets"] as $databaseNames => $databaseData)
    {
        echo "  Database name ".$databaseNames."<br/>";
        echo "  Database role ".$databaseData["permissions"]["role"]."<br/>";
        echo "  Database group ".$databaseData["permissions"]["group"]."<br/>";
    }
}
</code>```

Title: Iterate over JSON with PHP

Body:
I cannot figure out how to get the following keys/values from the JSON below:

I need to print out in a for loop:

'projects' i.e 'test-project-1'

'datasets' i.e 'dataset1'

'permissions' i.e 'role: WRITER, group: test1@test.com'

{
   "projects":{
      "test-project-1":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      },
      "test-project-2":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      }
   }
}

I tried this but the only thing that prints out is "Array".

Something like this does not work:

$new_json = {path_to_json};
$new_projects = $new_json['projects'];
foreach ($new_projects as $project) {
    echo $project . "
";
    foreach ($new_projects['datasets'] as $datasets){
        echo $datasets . "
";
    }
}

Body:
PHP code demo

$json='{
   "projects":{
      "test-project-1":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      },
      "test-project-2":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      }
   }
}';
$array=  json_decode($json,true);
foreach($array["projects"] as $projectName => $projects)
{
    echo "Project name ".$projectName."<br/>";
    foreach($projects["datasets"] as $databaseNames => $databaseData)
    {
        echo "  Database name ".$databaseNames."<br/>";
        echo "  Database role ".$databaseData["permissions"]["role"]."<br/>";
        echo "  Database group ".$databaseData["permissions"]["group"]."<br/>";
    }
}


答:
These parameters are passed to JVM via command line: -Xms and -Xmx
For more information run java -X.</p>

Title: Where can I permanently set java heap size on Windows pc?

Body:
I recently downloaded the latest Java 1.6 JDK. I'm using VisualVM which came with the SDK to test/monitor my webapp (using Tomcat server) on my local pc. I'm running Windows XP.

Where are the parameters located for setting the min. and max. java heap size? VisualVM indicates that the max. heap is at about 256mb. I looked in the server.xml file for Tomcat, but didn't find any settings in there.

Thank you


答:
This does what you're asking but it isn't pretty.</p>

```<code>>>> x = '___abc_d__'
>>> on_left = len(x) - len(x.lstrip('_'))
>>> on_right = len(x) - len(x.rstrip('_'))
>>> y = '({0}){1}({2})'.format(on_left, x.strip('_'), on_right)
>>> print(y)
(3)abc_d(2)
</code>```

Title: Trim whitespaces on a String

Body:
This does what you're asking but it isn't pretty.

>>> x = '___abc_d__'
>>> on_left = len(x) - len(x.lstrip('_'))
>>> on_right = len(x) - len(x.rstrip('_'))
>>> y = '({0}){1}({2})'.format(on_left, x.strip('_'), on_right)
>>> print(y)
(3)abc_d(2)


问:
Break a loop inside an animation block
I'm trying to break a for-loop after a completed UIView animation. Here is the following snippet:

```<code>public func greedyColoring() {
    let colors = [UIColor.blue, UIColor.green, UIColor.yellow, UIColor.red, UIColor.cyan, UIColor.orange, UIColor.magenta, UIColor.purple]

    for vertexIndex in 0 ..< self.graph.vertexCount {
        let neighbours = self.graph.neighborsForIndex(vertexIndex)
        let originVertex = vertices[vertexIndex]

        print("Checking now Following neighbours for vertex \(vertexIndex): \(neighbours)")

        var doesNotMatch = false

        while doesNotMatch == false {
            inner: for color in colors{
                UIView.animate(withDuration: 1, delay: 2, options: .curveEaseIn, animations: {
                    originVertex.layer.backgroundColor = color.cgColor
                }, completion: { (complet) in
                    if complet {
                        let matches = neighbours.filter {
                            let vertIdx = Int($0)!

                            print("Neighbour to check: \(vertIdx)")

                            let vertex = self.vertices[vertIdx-1]

                            if vertex.backgroundColor == color{
                                return true
                            }else{
                                return false
                            }
                        }

                        //print("there were \(matches.count) matches")

                        if matches.count == 0 {
                            // do some things
                            originVertex.backgroundColor = color
                            doesNotMatch = true
                            break inner
                        } else {
                            doesNotMatch = false
                        }
                    }
                })
            }
        }
    }
}
</code>```

Basically this method iterate over a Graph and checks every vertex and its neighbours and give the vertex a color that none of its neighbours has. Thats why it has to break the iteration at the first color that hasn't been used. I tried to use Unlabeled loops but it still doesn't compile (break is only allowed inside a loop). The problem is that I would like to visualise which colors have been tested. Thats why I'm using the UIView.animate()

Is there anyway to solve my problem?

答:
```<code>Just modifying your code a little bit. Its a old school recursion but should work. Assuming all the instance variables are available here is a new version.

public func greedyColoring(vertex:Int,colorIndex:Int){
       if  vertexIndex > self.graph.vertexCount { return }

       if colorIndex > color.count {return}

       let neighbours = self.graph.neighborsForIndex(vertexIndex)

       let originVertex = vertices[vertexIndex]

       let color = self.colors[colorIndex]

     UIView.animate(withDuration: 1, delay: 2, options: .curveEaseIn,   animations: {
            originVertex.layer.backgroundColor = color.cgColor
        }, completion: { (complet) in
            if complet {
                let matches = neighbours.filter {
                    let vertIdx = Int($0)!

                    print("Neighbour to check: \(vertIdx)")

                    let vertex = self.vertices[vertIdx-1]

                    //No idea what you are trying to do here. So leaving as it is.
                    if vertex.backgroundColor == color{
                        return true
                    }else{
                        return false
                    }
                }

                //print("there were \(matches.count) matches")

                if matches.count == 0 {
                    // do some things
                    originVertex.backgroundColor = color
                    greedyColoring(vertex: vertex++,colorIndex:0)
                } else {
                    greedyColoring(vertex: vertex,colorIndex: colorIndex++)
                }
            }
        })
    }

Now we can call this function simply

    greedyColor(vertex:0,colorIndex:0)
</code>```

Title: Break a loop inside an animation block

Body:
I'm trying to break a for-loop after a completed UIView animation. Here is the following snippet:

public func greedyColoring() {
    let colors = [UIColor.blue, UIColor.green, UIColor.yellow, UIColor.red, UIColor.cyan, UIColor.orange, UIColor.magenta, UIColor.purple]

    for vertexIndex in 0 ..< self.graph.vertexCount {
        let neighbours = self.graph.neighborsForIndex(vertexIndex)
        let originVertex = vertices[vertexIndex]

        print("Checking now Following neighbours for vertex \(vertexIndex): \(neighbours)")

        var doesNotMatch = false

        while doesNotMatch == false {
            inner: for color in colors{
                UIView.animate(withDuration: 1, delay: 2, options: .curveEaseIn, animations: {
                    originVertex.layer.backgroundColor = color.cgColor
                }, completion: { (complet) in
                    if complet {
                        let matches = neighbours.filter {
                            let vertIdx = Int($0)!

                            print("Neighbour to check: \(vertIdx)")

                            let vertex = self.vertices[vertIdx-1]

                            if vertex.backgroundColor == color{
                                return true
                            }else{
                                return false
                            }
                        }

                        //print("there were \(matches.count) matches")

                        if matches.count == 0 {
                            // do some things
                            originVertex.backgroundColor = color
                            doesNotMatch = true
                            break inner
                        } else {
                            doesNotMatch = false
                        }
                    }
                })
            }
        }
    }
}

Basically this method iterate over a Graph and checks every vertex and its neighbours and give the vertex a color that none of its neighbours has. Thats why it has to break the iteration at the first color that hasn't been used. I tried to use Unlabeled loops but it still doesn't compile (break is only allowed inside a loop). The problem is that I would like to visualise which colors have been tested. Thats why I'm using the UIView.animate()

Is there anyway to solve my problem?


问:
Why do we get error for checking string value in sql
I'm running this piece of code implemented with cursor
but I get if statement error after running it

```<code>declare
  cursor cr is
   select idd,name from tes;
     begin
       for n in cr
         IF n.name = '' THEN
          insert into tes2 values(n.idd,'$$$');
         ELSE
          insert into tes2 values(n.idd,n.name);
         END IF;
    end loop;
    commit;
   end;
</code>```

the error :

Encountered the symbol "IF" when expecting one of the following:

. ( * @ % & - + / at loop mod remainder rem ..     || multiset

The type of my variable are varchar2 and I also tried if n.name is NULL , didn't work.

答:
After for statement, you forgot to add loop. End loop is there but no starting of loop. Try after changing below portion

```<code>for n in cr
   loop
         IF n.name = '' THEN
          insert into tes2 values(n.idd,'$$$');
         ELSE
          insert into tes2 values(n.idd,n.name);
         END IF;
    end loop;
</code>```

Body:
I'm running this piece of code implemented with cursor
but I get if statement error after running it

declare
  cursor cr is
   select idd,name from tes;
     begin
       for n in cr
         IF n.name = '' THEN
          insert into tes2 values(n.idd,'$$$');
         ELSE
          insert into tes2 values(n.idd,n.name);
         END IF;
    end loop;
    commit;
   end;

the error :

Encountered the symbol "IF" when expecting one of the following:

. ( * @ % & - + / at loop mod remainder rem ..     || multiset

The type of my variable are varchar2 and I also tried if n.name is NULL , didn't work.

Body:
After for statement, you forgot to add loop. End loop is there but no starting of loop. Try after changing below portion

for n in cr
   loop
         IF n.name = '' THEN
          insert into tes2 values(n.idd,'$$$');
         ELSE
          insert into tes2 values(n.idd,n.name);
         END IF;
    end loop;