问:
How to send command to serial port (JAVA + RXTX)
I have a problem with sending data input to a weight balance. I need to send a ESC P CR LF command. I use the RXTX lib. I dont know why it does not work.

Here is the code:

```<code>public static class SerialWriter implements Runnable {
    OutputStream out;

    public SerialWriter ( OutputStream out ) {
        this.out = out;
    }

    public void run () {
        try {
            while (true) {
               this.out.write(new byte[]{0x1B, 0x50, 0x0D, 0x0A});
                Thread.sleep(1000);
            }
        } catch ( IOException | InterruptedException e ) {
            e.printStackTrace();
        }
    }
}
</code>```

I tried with flush but nothing happened.

I attached the full (modified) code below.

```<code>package model;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FirstSteps {
    public FirstSteps() {
        super();
    }

    void connect (String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            System.out.println("Connect 1/2");
            CommPort commPort = portIdentifier.open(this.getClass().getName(),6000);
            if (commPort instanceof SerialPort) {
                System.out.println("Connect 2/2");
                SerialPort serialPort = (SerialPort) commPort;
                System.out.println("BaudRate: " + serialPort.getBaudRate());
                System.out.println("DataBIts: " + serialPort.getDataBits());
                System.out.println("StopBits: " + serialPort.getStopBits());
                System.out.println("Parity: " + serialPort.getParity());
                System.out.println("FlowControl: " + serialPort.getFlowControlMode());
                serialPort.setSerialPortParams(4800,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_ODD);
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
                System.out.println("BaudRate: " + serialPort.getBaudRate());
                System.out.println("DataBIts: " + serialPort.getDataBits());
                System.out.println("StopBits: " + serialPort.getStopBits());
                System.out.println("Parity: " + serialPort.getParity());
                System.out.println("FlowControl: " + serialPort.getFlowControlMode());
                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();
            } else {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    public static class SerialReader implements Runnable {
        InputStream in;

        public SerialReader(InputStream in) {
            this.in = in;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int len = -1;
            try {
                while ((len = this.in.read(buffer)) > -1) {
                    //System.out.println("Received a signal.");
                    System.out.print(new String(buffer,0,len));
                }
            } catch ( IOException e ) {
                e.printStackTrace();
            }
        }
    }

    public static class SerialWriter implements Runnable {
        OutputStream out;

        public SerialWriter(OutputStream out) {
            this.out = out;
        }

        public void run() {
            try {
                byte[] array = {0x1B, 0x50, 0x0D, 0x0A};
                while (true) {
                    this.out.write(new byte[]{0x1B, 0x50, 0x0D, 0x0A});
                    this.out.flush();
                    Thread.sleep(1000);
                }
            } catch ( IOException | InterruptedException e ) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            (new FirstSteps()).connect("COM7");
        } catch ( Exception e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

答:
Adding this line:</p>

```<code>serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
</code>```

Body:
I have a problem with sending data input to a weight balance. I need to send a ESC P CR LF command. I use the RXTX lib. I dont know why it does not work.

Here is the code:

public static class SerialWriter implements Runnable {
    OutputStream out;

    public SerialWriter ( OutputStream out ) {
        this.out = out;
    }

    public void run () {
        try {
            while (true) {
               this.out.write(new byte[]{0x1B, 0x50, 0x0D, 0x0A});
                Thread.sleep(1000);
            }
        } catch ( IOException | InterruptedException e ) {
            e.printStackTrace();
        }
    }
}

I tried with flush but nothing happened.

I attached the full (modified) code below.

package model;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FirstSteps {
    public FirstSteps() {
        super();
    }

    void connect (String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            System.out.println("Connect 1/2");
            CommPort commPort = portIdentifier.open(this.getClass().getName(),6000);
            if (commPort instanceof SerialPort) {
                System.out.println("Connect 2/2");
                SerialPort serialPort = (SerialPort) commPort;
                System.out.println("BaudRate: " + serialPort.getBaudRate());
                System.out.println("DataBIts: " + serialPort.getDataBits());
                System.out.println("StopBits: " + serialPort.getStopBits());
                System.out.println("Parity: " + serialPort.getParity());
                System.out.println("FlowControl: " + serialPort.getFlowControlMode());
                serialPort.setSerialPortParams(4800,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_ODD);
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
                System.out.println("BaudRate: " + serialPort.getBaudRate());
                System.out.println("DataBIts: " + serialPort.getDataBits());
                System.out.println("StopBits: " + serialPort.getStopBits());
                System.out.println("Parity: " + serialPort.getParity());
                System.out.println("FlowControl: " + serialPort.getFlowControlMode());
                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();
            } else {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    public static class SerialReader implements Runnable {
        InputStream in;

        public SerialReader(InputStream in) {
            this.in = in;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int len = -1;
            try {
                while ((len = this.in.read(buffer)) > -1) {
                    //System.out.println("Received a signal.");
                    System.out.print(new String(buffer,0,len));
                }
            } catch ( IOException e ) {
                e.printStackTrace();
            }
        }
    }

    public static class SerialWriter implements Runnable {
        OutputStream out;

        public SerialWriter(OutputStream out) {
            this.out = out;
        }

        public void run() {
            try {
                byte[] array = {0x1B, 0x50, 0x0D, 0x0A};
                while (true) {
                    this.out.write(new byte[]{0x1B, 0x50, 0x0D, 0x0A});
                    this.out.flush();
                    Thread.sleep(1000);
                }
            } catch ( IOException | InterruptedException e ) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            (new FirstSteps()).connect("COM7");
        } catch ( Exception e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Body:
Adding this line:

serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);


来源: stackexchange

问:
How can I get a list of all timezone IDs in Java 8?
In the java.time package I do not see a function to get a list of available timezone IDs. I am able to call the getAvailableIDs() in java.util.TimeZonelibrary. However, I want to use Java 8 instead.

Is there a way to do this?

答:
ZoneId.getAvailableZoneIds()

ZoneId exists in the java.time package.

ZoneId.getAvailableZoneIds() ➙ Set<String>

This set includes the string form of all available region-based IDs.
  Offset-based zone IDs are not included in the returned set. The ID can
  be passed to of(String) to create a ZoneId.

The set of zone IDs can increase over time, although in a typical
  application the set of IDs is fixed. Each call to this method is
  thread-safe.

ContentLicense: CC BY-SA 4.0


问:
Version numbers with caret and tilde in composer.json
I wonder what is the difference between caret and tilde in composer.json. Can I say it like this: caret (^) lock the first and the second version number (the 1.2 in 1.2.3) and tilde(~) lock only the first version number (the 1 in 1.2.3)?

https://getcomposer.org/doc/articles/versions.md#next-significant-release-operators

答:
From the documentation you linked:

~1.2 is equivalent to >=1.2 <2.0.0, while ~1.2.3 is equivalent to >=1.2.3 <1.3.0

^1.2.3 is equivalent to >=1.2.3 <2.0.0

The tilde depends on how many digits in the version number are given. The last digit given can vary.

The caret is almost always the better choice because it acts similarly enough to be a direct replacement (~1.2 is the same as ^1.2 or ^1.2.0), but offer better flexibility when addressing non-zero patch versions (^1.2.3 is NOT the same as ~1.2.3, because the tilde version only allows updates below 1.3.0, the caret allows updates below 2.0.0).

The only reason why one would use the tilde as version requirement is if you have to deal with "zero" versions that get compatible updates. The tilde does not differ between ~0.1 and ~1.1, in both cases it will allow updates up to the next major version number (below 1.0 or 2.0 respectively). The caret operator will disallow minor updates in this range: ^0.1 does not allow updates to 0.2, because in semantic versioning a zero-dot-something version may introduce incompatible changes when going to zero-dot-something+1.

Summary:

Prefer the caret operator - it's the easiest way to force minimum patch versions.

Prefer versions above 0.x (start with 1.0.0) and use semantic versioning for your own code.

For the development phase, you can use alpha, beta or rc stability together with the intended final version, i.e. 1.0.0-alpha1 would be a rough outline of what 1.0.0 will be in the future.

ContentLicense: CC BY-SA 3.0


问:
Uploading Separate APKs for ARM-v7 and x86 to Google Play
I have made an Android game in Unity3D. I have published the game on Google Play.

The APK I'm currently serving is for both ARM-v7 and x86 native platforms. I want to upload a separate APK file for each to make them take up less storage space. The APK with both platforms is 27MB and the separate APKs are each around 19MB. The installed sizes are 56MB and 43MB, respectively. That's a significant difference.
The only information on this I have found relates to the APK tab in Google Play Developer Console, which is now deprecated.
Also, I have tried to upload separate APK files under the same version code and I got an error saying that two APKs can't have the same version code.
And when I tried to upload them under different version codes I got an error saying that the lower version APK is fully shadowed by the newer version.

How can I upload separate APK files for different native platforms?

Thank you for your help.

答:
With the new 'Manage Releases' system, you create a release and add both apks, with different version codes, to the same release. You must limit the native platform in each one with something like this in your build.gradle:

```<code>splits {
        abi {
            enable true
            reset()
            include 'armeabi-v7a', 'x86'
            universalApk false
        }
</code>```

The x86 version should have a higher version code, otherwise x86 devices will get the armv7a version since they are almost always compatible with that architecture as well.

Body:
With the new 'Manage Releases' system, you create a release and add both apks, with different version codes, to the same release. You must limit the native platform in each one with something like this in your build.gradle:

splits {
        abi {
            enable true
            reset()
            include 'armeabi-v7a', 'x86'
            universalApk false
        }

The x86 version should have a higher version code, otherwise x86 devices will get the armv7a version since they are almost always compatible with that architecture as well.


问:
Promise and Arrow Function in Angular2
I am new to angular and it may sound silly but I didn't get how this code works

```<code>this.ms.getList().then((hl) => { this.HeroesList = hl; });
</code>```

I called the service method, on success what it returns ?

Secondly, how this arrow function got the array of heroes that my service has to return and then assigning the array to my component variable ,

My Component Code :

```<code>constructor(private ms: myService) {
  }
  ngOnInit() {
    this.ms.getList().then((hl) => { this.HeroesList = hl; });
  }
</code>```

And here is the service :

```<code>import { Injectable } from '@angular/core'
import { Hero } from './hero'
import { HeroesList } from './heroesList'
@Injectable()
export class myService {
    heroes: Hero[];
    getList(): Promise<Hero[]> {
        return Promise.resolve(HeroesList);//when success, return the list
    }

}
</code>```

答: When the promise resolves.. it is returning the heroeslist which is the h1 in the component then function.</p>

Title: Promise and Arrow Function in Angular2

Body:
I am new to angular and it may sound silly but I didn't get how this code works

this.ms.getList().then((hl) => { this.HeroesList = hl; });

I called the service method, on success what it returns ?

Secondly, how this arrow function got the array of heroes that my service has to return and then assigning the array to my component variable ,

My Component Code :

constructor(private ms: myService) {
  }
  ngOnInit() {
    this.ms.getList().then((hl) => { this.HeroesList = hl; });
  }

And here is the service :

import { Injectable } from '@angular/core'
import { Hero } from './hero'
import { HeroesList } from './heroesList'
@Injectable()
export class myService {
    heroes: Hero[];
    getList(): Promise<Hero[]> {
        return Promise.resolve(HeroesList);//when success, return the list
    }

}


问:
Image file compression options with ggplot2
Is it possible to compress the file size of a figure using ggsave?  I have tried using the compression = "lzw" argument, but the file size remains the same. (Using R studio .98.501 OS-X Yosemite)

My code:

```<code>ggsave("Figure1.tiff", width = 14, height = 8, dpi=600, compression = "lzw")
</code>```

Is it possible to add a compression argument with ggsave?

答:
I would suggest to use tiff directly, like </p>

```<code>tiff("my_graph.tif", units="in", width=13.3, height=6.6, res=800, compression = "lzw")

my_graph <- ggplot(....)

dev.off()
</code>```

Body:
Is it possible to compress the file size of a figure using ggsave?  I have tried using the compression = "lzw" argument, but the file size remains the same. (Using R studio .98.501 OS-X Yosemite)

My code:

ggsave("Figure1.tiff", width = 14, height = 8, dpi=600, compression = "lzw")

Is it possible to add a compression argument with ggsave?

Body:
I would suggest to use tiff directly, like

tiff("my_graph.tif", units="in", width=13.3, height=6.6, res=800, compression = "lzw")

my_graph <- ggplot(....)

dev.off()


问:
Get Values to the Array Angular 2
I have Admin.ts Class

```<code>export class AdminValues{

    nameAd:String;
    email_addr:String;
    passwrd:String;

    constructor(adminName:String,adminEmail:String,adminPassword:String){

        this.nameAd=adminName;
        this.email_addr=adminEmail;
        this.passwrd=adminPassword;
    }

}
</code>```

I am completely new to Angular 2. I have created an admin form (AdminForm Component) to get input. I want create an Angular 2 service to add new admins to the Admin Type Array. How should I do that?

答:
This is a pretty broad questions, since there are an infinite number of ways to do this. This article will give you a pretty good overview on getting started.

Most simply, you need to make a new file, with this content in it:

```<code>@Injectable()
export class AdminService {
  getArray() {
    return ['my array'];
  }
}
</code>```

You will need to include this service in your app modules in the providers section, and import it into your AdminForm component. Something along the lines of import { AdminService } from './AdminService'; should do the job.

You then should change your constructor to this:

```<code>constructor(private adminService: AdminService, adminName:String,adminEmail:String,adminPassword:String){

    this.nameAd=adminName;
    this.email_addr=adminEmail;
    this.passwrd=adminPassword;
}
</code>```

Which will then give you access to your admin service and you can get your array.

```<code>myArray;

constructor(private adminService: AdminService, adminName:String,adminEmail:String,adminPassword:String){

    this.nameAd=adminName;
    this.email_addr=adminEmail;
    this.passwrd=adminPassword;
    this.myArray = adminService.getArray();
}
</code>```

This answer should get you started, but if you need more in-depth information about services, the link at the top of this answer should have all the information you need to get going.

Title: Get Values to the Array Angular 2

Body:
I have Admin.ts Class

export class AdminValues{

    nameAd:String;
    email_addr:String;
    passwrd:String;

    constructor(adminName:String,adminEmail:String,adminPassword:String){

        this.nameAd=adminName;
        this.email_addr=adminEmail;
        this.passwrd=adminPassword;
    }

}

I am completely new to Angular 2. I have created an admin form (AdminForm Component) to get input. I want create an Angular 2 service to add new admins to the Admin Type Array. How should I do that?

Body:
This is a pretty broad questions, since there are an infinite number of ways to do this. This article will give you a pretty good overview on getting started.

Most simply, you need to make a new file, with this content in it:

@Injectable()
export class AdminService {
  getArray() {
    return ['my array'];
  }
}

You will need to include this service in your app modules in the providers section, and import it into your AdminForm component. Something along the lines of import { AdminService } from './AdminService'; should do the job.

You then should change your constructor to this:

constructor(private adminService: AdminService, adminName:String,adminEmail:String,adminPassword:String){

    this.nameAd=adminName;
    this.email_addr=adminEmail;
    this.passwrd=adminPassword;
}

Which will then give you access to your admin service and you can get your array.

myArray;

constructor(private adminService: AdminService, adminName:String,adminEmail:String,adminPassword:String){

    this.nameAd=adminName;
    this.email_addr=adminEmail;
    this.passwrd=adminPassword;
    this.myArray = adminService.getArray();
}

This answer should get you started, but if you need more in-depth information about services, the link at the top of this answer should have all the information you need to get going.


答:
It might be easier to understand if you look at how the TypeScript is transpiled to JavaScript (ES5).

Your TypeScript:

```<code>this.ms.getList().then((hl) => { this.HeroesList = hl; });
</code>```

Transpiled to JavaScript:

```<code>this.ms.getList().then(function(hl) {
    this.HeroesList = hl;
});
</code>```

The Promise .then() function accepts two callback functions, one for a success callback and one for an error callback. You're only using the success callback. Therefore, when .then() is executed on your Promise, if your Promise is successful, it will callback to your defined success function. Your defined success function then sets your service variable to the resolved result of your Promise.

Title: Promise and Arrow Function in Angular2

Body:
It might be easier to understand if you look at how the TypeScript is transpiled to JavaScript (ES5).

Your TypeScript:

this.ms.getList().then((hl) => { this.HeroesList = hl; });

Transpiled to JavaScript:

this.ms.getList().then(function(hl) {
    this.HeroesList = hl;
});

The Promise .then() function accepts two callback functions, one for a success callback and one for an error callback. You're only using the success callback. Therefore, when .then() is executed on your Promise, if your Promise is successful, it will callback to your defined success function. Your defined success function then sets your service variable to the resolved result of your Promise.


问:
Matching Cursor Results to EditText Input
messing around with Android Studio, not used it much, so a lot of the basic features I'm still trying to get my head around.

I've made a local database to store users' registering information, got it working no problem. Got an ID/Name/Email/Password fields.

Now I'm trying to sort out the login function, which is where I'm struggling, since it's my first time using cursors. Simply it needs to cycle through the Email and Password fields, find a match and log the user in. Here's what I currently have in my DatabaseHelperClass for it;

```<code>public boolean passwordOk(String Editemail, String Editpassword) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from " +  TABLE_NAME + " where " + COL_3 + "="+ Editemail + " and " + COL_4 + "=" + Editpassword + "'", null );

        return (res.getCount() == 1);

    }
</code>```

And here's what I have in my MainActivity to use it;

```<code> public void passwordOK(){

        loginB.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                   boolean isInsert = myD.passwordOk(editEmail.getText().toString(), editPassword.getText().toString());
                        if (isInsert == true)
                            Toast.makeText(MainActivity.this, "You Have Successfully Logged in", Toast.LENGTH_LONG).show();
                 else  Toast.makeText(MainActivity.this, "Oops! Try Again", Toast.LENGTH_LONG).show();

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

Here's the errors it's throwing at me, it closes the application.

03-31 16:11:37.351 26018-26018/com.example.onein.jobgosite
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.onein.jobgosite, PID: 26018
                                                                               android.database.sqlite.SQLiteException: unrecognized token: "'" (code
  1): , while compiling: select * from user_Info where EMAIL=do and
  PASSWORD=doh'
                                                                                at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
                                                                                at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                                                at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                                                at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
                                                                                at
  android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                                at
  com.example.onein.jobgosite.DatabaseHelperClass.passwordOk(DatabaseHelperClass.java:62)
                                                                                at
  com.example.onein.jobgosite.MainActivity$2.onClick(MainActivity.java:67)
                                                                                at android.view.View.performClick(View.java:5198)
                                                                                at android.view.View$PerformClick.run(View.java:21147)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

All help appreciated, it's probably something stupid and something simple to make it work, but for some reason I'm struggling visualising how cursors work and how to get it working. Thanks!

答:
Use this character ' in your parameters, something like this:

```<code>Cursor res = db.rawQuery( "SELECT * from " + "\'"+TABLE_NAME+"\'"+ " where " + "\'"+COL_3+"\'" + "="+"\'"+ Editemail +"\'"+ " and " +"\'"+ COL_4 +"\'"+ "=" + "\'"+Editpassword +"\'"+ "", null );
</code>```

But a better practice is to use the ? operand.

I realized you check for this:

```<code>res.getCount() == 1
</code>```

change this to:

```<code>res != null
</code>```

also, there is an extra character here "'", should be like this:

```<code>Editpassword + ""
</code>```

Body:
messing around with Android Studio, not used it much, so a lot of the basic features I'm still trying to get my head around.

I've made a local database to store users' registering information, got it working no problem. Got an ID/Name/Email/Password fields.

Now I'm trying to sort out the login function, which is where I'm struggling, since it's my first time using cursors. Simply it needs to cycle through the Email and Password fields, find a match and log the user in. Here's what I currently have in my DatabaseHelperClass for it;

public boolean passwordOk(String Editemail, String Editpassword) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from " +  TABLE_NAME + " where " + COL_3 + "="+ Editemail + " and " + COL_4 + "=" + Editpassword + "'", null );

        return (res.getCount() == 1);

    }

And here's what I have in my MainActivity to use it;

 public void passwordOK(){

        loginB.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                   boolean isInsert = myD.passwordOk(editEmail.getText().toString(), editPassword.getText().toString());
                        if (isInsert == true)
                            Toast.makeText(MainActivity.this, "You Have Successfully Logged in", Toast.LENGTH_LONG).show();
                 else  Toast.makeText(MainActivity.this, "Oops! Try Again", Toast.LENGTH_LONG).show();

                    }
                }
        );
    }

Here's the errors it's throwing at me, it closes the application.

03-31 16:11:37.351 26018-26018/com.example.onein.jobgosite
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.onein.jobgosite, PID: 26018
                                                                               android.database.sqlite.SQLiteException: unrecognized token: "'" (code
  1): , while compiling: select * from user_Info where EMAIL=do and
  PASSWORD=doh'
                                                                                at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
                                                                                at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                                                at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                                                at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
                                                                                at
  android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                                at
  com.example.onein.jobgosite.DatabaseHelperClass.passwordOk(DatabaseHelperClass.java:62)
                                                                                at
  com.example.onein.jobgosite.MainActivity$2.onClick(MainActivity.java:67)
                                                                                at android.view.View.performClick(View.java:5198)
                                                                                at android.view.View$PerformClick.run(View.java:21147)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

All help appreciated, it's probably something stupid and something simple to make it work, but for some reason I'm struggling visualising how cursors work and how to get it working. Thanks!

Body:
Use this character ' in your parameters, something like this:

Cursor res = db.rawQuery( "SELECT * from " + "\'"+TABLE_NAME+"\'"+ " where " + "\'"+COL_3+"\'" + "="+"\'"+ Editemail +"\'"+ " and " +"\'"+ COL_4 +"\'"+ "=" + "\'"+Editpassword +"\'"+ "", null );

But a better practice is to use the ? operand.

I realized you check for this:

res.getCount() == 1

change this to:

res != null

also, there is an extra character here "'", should be like this:

Editpassword + ""


问:
Why Extra Padding on top of ThumbnailView?
I am using Three20's TTThumbViewController. Everything works fine except for a padding on top of the thumbnail table which appears to be reserved for the navigation header, except that it takes the place right below the header. How can I get rid of this white space?

答:
I dont know why this works for sure, but I faced the same problem and found this solution at google group.

Override updateTableLayout in your TTThumbsViewController

```<code>- (void)updateTableLayout
{
    self.tableView.contentInset = UIEdgeInsetsMake(4, 0, 0, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I dont know why this works for sure, but I faced the same problem and found this solution at google group.

Override updateTableLayout in your TTThumbsViewController

- (void)updateTableLayout
{
    self.tableView.contentInset = UIEdgeInsetsMake(4, 0, 0, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}


问:
Find All Records from Customer where ALL their records have NULL value in Price Field
Hopefully I can describe this simply if not I'll try to make a table for it: say I have a table that tracks all visits to my store by customer name. I log their Name and Purchase Amount (if any). I want to get a list of visitors who never buy anything.  So if I have

VisitorName   PurchaseAmount

Bob           10

Bob           NULL

Mary          NULL

Mary          NULL

I want a query that returns Mary since all of her records have NULL in the PurchaseAmount

答:
Create table/insert data

```<code>CREATE TABLE visits
    (`VisitorName` VARCHAR(4), `PurchaseAmount` VARCHAR(4))
;

INSERT INTO visits
    (`VisitorName`, `PurchaseAmount`)
VALUES
    ('Bob', '10'),
    ('Bob', NULL),
    ('Mary', NULL),
    ('Mary', NULL)
;
</code>```

Query

Just GROUP BY on VisitorName.
And a HAVING what checks if all records are NULL's

```<code>SELECT
 visits.VisitorName
FROM
 visits
GROUP BY
  visits.VisitorName
HAVING
 SUM(CASE
       WHEN visits.PurchaseAmount IS NULL
       THEN 1
    END
 ) = COUNT(*)
</code>```

Result

```<code>VisitorName
-------------
Mary
</code>```

Body:
Create table/insert data

CREATE TABLE visits
    (`VisitorName` VARCHAR(4), `PurchaseAmount` VARCHAR(4))
;

INSERT INTO visits
    (`VisitorName`, `PurchaseAmount`)
VALUES
    ('Bob', '10'),
    ('Bob', NULL),
    ('Mary', NULL),
    ('Mary', NULL)
;

Query

Just GROUP BY on VisitorName.
And a HAVING what checks if all records are NULL's

SELECT
 visits.VisitorName
FROM
 visits
GROUP BY
  visits.VisitorName
HAVING
 SUM(CASE
       WHEN visits.PurchaseAmount IS NULL
       THEN 1
    END
 ) = COUNT(*)

Result

VisitorName
-------------
Mary


问:
open and write on file
I created a code which ask a user to enter a list of position on a plain text file, save the position the user entered in the text file as list than ask the user to enter the word each position represent (the same order as the list of position) end re-create the sentence.
However im not sure on thow things:

1) how can i make the plain text document pop out only when the previous one was closed (so only when the file:list_of_numbers has been closed, the other file list_of_words will popup).

2) How to write the output on a plain text file.

here is the code:

```<code>import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as pos_file:
    positions = pos_file.read().spllit()

subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as sentence_file:
    words = sentence_file.read().split()

mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]

print(' '.join(output))
</code>```

答:
Im not sure what you are trying to do exactly, but this should help. You do not need to use subprocess, and in fact it is probably overcomplicating some things...

Input:

```<code>Enter a number. (Leave blank to continue): 1
Enter a number. (Leave blank to continue): 2
Enter a number. (Leave blank to continue): 3
Enter a number. (Leave blank to continue):

Enter a word. (Leave blank to continue): a
Enter a word. (Leave blank to continue): b
Enter a word. (Leave blank to continue): c
Enter a word. (Leave blank to continue):
</code>```

Output (console and to output.txt):

```<code>1, a

2, b

3, c
</code>```

Code:

```<code>#!/usr/bin/env python

while True:

    positions = []
    words = []

    while True:
        number = raw_input("Enter a number. (Leave blank to continue): ")
        if not number:
            break

        try:
            positions.append(int(number))
        except TypeError:
            print("Invalid number provided. Try again.")

    print("\n")

    while True:
        word = raw_input("Enter a word. (Leave blank to continue): ")
        if not word:
            break

        words.append(word)

    if len(positions) != len(words):
        print("You did not enter the same number of words and positions..")
        print("Clearing previous inputs..")
    else:
        break

with open("output.txt", 'a') as output_file:
    for x in xrange(0, len(positions)):
        line = "{0}, {1}\n".format(positions[x], words[x])
        output_file.write(line)
        print(line)
</code>```

Title: open and write on file

Body:
I created a code which ask a user to enter a list of position on a plain text file, save the position the user entered in the text file as list than ask the user to enter the word each position represent (the same order as the list of position) end re-create the sentence.
However im not sure on thow things:

1) how can i make the plain text document pop out only when the previous one was closed (so only when the file:list_of_numbers has been closed, the other file list_of_words will popup).

2) How to write the output on a plain text file.

here is the code:

import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as pos_file:
    positions = pos_file.read().spllit()

subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as sentence_file:
    words = sentence_file.read().split()

mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]

print(' '.join(output))

Body:
Im not sure what you are trying to do exactly, but this should help. You do not need to use subprocess, and in fact it is probably overcomplicating some things...

Input:

Enter a number. (Leave blank to continue): 1
Enter a number. (Leave blank to continue): 2
Enter a number. (Leave blank to continue): 3
Enter a number. (Leave blank to continue):

Enter a word. (Leave blank to continue): a
Enter a word. (Leave blank to continue): b
Enter a word. (Leave blank to continue): c
Enter a word. (Leave blank to continue):

Output (console and to output.txt):

1, a

2, b

3, c

Code:

#!/usr/bin/env python

while True:

    positions = []
    words = []

    while True:
        number = raw_input("Enter a number. (Leave blank to continue): ")
        if not number:
            break

        try:
            positions.append(int(number))
        except TypeError:
            print("Invalid number provided. Try again.")

    print("\n")

    while True:
        word = raw_input("Enter a word. (Leave blank to continue): ")
        if not word:
            break

        words.append(word)

    if len(positions) != len(words):
        print("You did not enter the same number of words and positions..")
        print("Clearing previous inputs..")
    else:
        break

with open("output.txt", 'a') as output_file:
    for x in xrange(0, len(positions)):
        line = "{0}, {1}\n".format(positions[x], words[x])
        output_file.write(line)
        print(line)


问:
Is it safe to run two instances of `stack` at the same time?
See title.

It would be nice if I could run multiple instances of stack at the same time. It would allow for some nice parallelisation.
I do not know which commands I want to run beforehand, so I can not just merge the commands and have stack figure out how to do it in parallel.

If this is not possible. Is it in the scope of Stack?

答:
Running multiple instances of stack concurrently is supposed to be possible and safe.

I know that parts of ~/.stack are protected by file locks – the project state in my-proj/.stack-work should get that in the future.


问:
Tcl how I could display a name in this script?
Im use tcl but  i dont know how display a string alphanumeric with this script code

#!/usr/bin/wish

wm title . "Feet to Meters"
grid [ttk::frame .c -padding "3 3 12 12"] -column 0 -row 0 -sticky nwes
grid columnconfigure . 0 -weight 1; grid rowconfigure . 0 -weight 1

grid [ttk::entry .c.feet -width 7 -textvariable feet] -column 2 -row 1 -sticky we
grid [ttk::label .c.meters -textvariable meters] -column 2 -row 2 -sticky we
grid [ttk::label .c.meter2s -textvariable meters2] -column 6 -row 2 -sticky we
grid [ttk::button .c.calc -text "Calculate" -command calculate] -column 3 -row 3 -sticky w
grid [ttk::entry .c.feet2 -width 7 -textvariable feet2] -column 7 -row 1 -sticky we

grid [ttk::label .c.flbl -text "feet"] -column 3 -row 1 -sticky w
grid [ttk::label .c.flbl2 -text "feet2"] -column 6 -row 1 -sticky w
grid [ttk::label .c.islbl -text "is equivalent to"] -column 1 -row 2 -sticky e
grid [ttk::label .c.mlbl -text "meters"] -column 3 -row 2 -sticky w
grid [ttk::label .c.mlbl2 -text "meters2"] -column 4 -row 2 -sticky w

foreach w [winfo children .c] {grid configure $w -padx 5 -pady 5}
focus .c.feet
bind . <Return> {calculate}

proc calculate {} {
   if {[catch {
       set ::meters [expr {round($::feet*0.3048*10000.0)/10000.0}]
       set ::meters2 [ feet2 ]
   }]!=0} {
       set ::meters ""
   }
}```
</div>
</div>
</p>

<p>in this part the script fails</p>

```in this part the script fails

   set ::meters2 [ feet2 ]
```

I want to display the feet2 value when write a text and press calculate

Please help me

答:
Like this?</p>

```<code>proc calculate {} {
   if {[catch {
       set ::meters [expr {round($::feet*0.3048*10000.0)/10000.0}]
       set ::meters2 $::feet2
   }]!=0} {
       set ::meters error
       set ::meters2 error2
   }
}
</code>```

Body:
Im use tcl but  i dont know how display a string alphanumeric with this script code

#!/usr/bin/wish

wm title . "Feet to Meters"
grid [ttk::frame .c -padding "3 3 12 12"] -column 0 -row 0 -sticky nwes
grid columnconfigure . 0 -weight 1; grid rowconfigure . 0 -weight 1

grid [ttk::entry .c.feet -width 7 -textvariable feet] -column 2 -row 1 -sticky we
grid [ttk::label .c.meters -textvariable meters] -column 2 -row 2 -sticky we
grid [ttk::label .c.meter2s -textvariable meters2] -column 6 -row 2 -sticky we
grid [ttk::button .c.calc -text "Calculate" -command calculate] -column 3 -row 3 -sticky w
grid [ttk::entry .c.feet2 -width 7 -textvariable feet2] -column 7 -row 1 -sticky we

grid [ttk::label .c.flbl -text "feet"] -column 3 -row 1 -sticky w
grid [ttk::label .c.flbl2 -text "feet2"] -column 6 -row 1 -sticky w
grid [ttk::label .c.islbl -text "is equivalent to"] -column 1 -row 2 -sticky e
grid [ttk::label .c.mlbl -text "meters"] -column 3 -row 2 -sticky w
grid [ttk::label .c.mlbl2 -text "meters2"] -column 4 -row 2 -sticky w

foreach w [winfo children .c] {grid configure $w -padx 5 -pady 5}
focus .c.feet
bind . <Return> {calculate}

proc calculate {} {
   if {[catch {
       set ::meters [expr {round($::feet*0.3048*10000.0)/10000.0}]
       set ::meters2 [ feet2 ]
   }]!=0} {
       set ::meters ""
   }
}

in this part the script fails

in this part the script fails

   set ::meters2 [ feet2 ]

I want to display the feet2 value when write a text and press calculate

Please help me

Body:
Like this?

proc calculate {} {
   if {[catch {
       set ::meters [expr {round($::feet*0.3048*10000.0)/10000.0}]
       set ::meters2 $::feet2
   }]!=0} {
       set ::meters error
       set ::meters2 error2
   }
}


问:
How to recursively copy specific file and keep name of parent directory
I have a multiple folders with different names: folderA, FolderB etc.
Within each of these folders are multiple files: fileA, fileB, fileC etc.

I want to search through all these folders and copy only specific files to a new location but with the same parent folder name: e.g. I want to generate:

```<code>new_location/folderA/fileA
new_location/folderA/fileC
new_location/folderB/fileA
new_location/folderB/fileC
</code>```

Could anyone suggest the unix commands that would accomplish this?

Thanks

Rob

答:
This depends somewhat, on how you can or do specify your specific files.

find folderA folderB folderC -type d -exec mkdir -p new_location/{} \;
will should make the proper subdirectories

find folderA folderB folderB -name somepattern -exec cp {} new_location/{} \;

may or may not need to worry about an extra "/" depending on directory names, etc

Body:
I have a multiple folders with different names: folderA, FolderB etc.
Within each of these folders are multiple files: fileA, fileB, fileC etc.

I want to search through all these folders and copy only specific files to a new location but with the same parent folder name: e.g. I want to generate:

new_location/folderA/fileA
new_location/folderA/fileC
new_location/folderB/fileA
new_location/folderB/fileC

Could anyone suggest the unix commands that would accomplish this?

Thanks

Rob


问:
Android Flash support
Can Android applications can use flash content in them?</p>

答:
Don't forget that AIR is supported by Android now too.

http://blogs.adobe.com/air/2010/04/adobe_air_applications_for_and.html

Title: Android Flash support


问:
R - Manually Change the Column Number Positions
This is a bit of an odd request, but I have a specific need that I am try to solve.

Lets pretend I have a dataframe with 50 columns. The column number (or index) of each column will be 1:50 respectively. Is there a way that I can assign new column numbers to each of the 50? Lets say that I want the first column to have a column number that is 187. Is this possible?

I have a predictive model that when built memorizes the column positions of each variable that was used to build the model, instead of the variable names. In my original dataset, I had 1,559 variables to build the model, but only 50 were selected as part of the final model. The model remembers each variable position as a function of the 1,559 however, so when I go to score new data it is looking for 1559 variables instead of just the 50 I have brought into my scoring universe.

I have saved the original position numbers of each variable, so I was hoping I could just assign column numbers to a dataset with only 50 variables. I have a workaround where I build a big empty dataframe with 1559 columns, and then put the data into the correct column # and then score the data, but in this case I have 3 million records to score, and I dont have enough RAM to build a 3M row, 1559 column dataframe.

答:
You can change the column position directly via data[,c(ORDER YOU WANT THEM TO BE IN)]

For instance:

head(cars)

vs.

head(cars[,c(2,1)])


问:
Histogram subplot for mathematical analysis of Chutes and Ladders
Hi I've created a very simple snakes and ladders program that I want to complete numerical analysis on. I want to find the mean number of rolls it takes to win a game of chutes and laddders.

I have the data, and it works if I choose just one histogram to plot but when I try to change the number of iterations of the game Python doesn't like it and I'm not sure what I've done wrong.

```<code>import numpy as np
import numpy as np #importing numpy
get_ipython().magic('matplotlib inline')
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt # importing matplotlib.pyplot
import statistics
#totalNumberOfGames = int(input("PLease enter the number of games you want to run to run:",))
numberOfGames = 1
player1Wins = 0
player2Wins = 0
player1Moves = 0
player2Moves = 0
numberOfDiceRolls = 0
gameNumberList = list()
player1MovesInEachGame = list()
player2MovesInEachGame = list()
winner = list()

while(numberOfGames <= totalNumberOfGames):

    player1 = 0
    player2 = 0

    a = range(1,11);b = range(11,21)[::-1];c = range(21,31);d = range(31,41)[::-1];e = range(41,51);f = range(51,61)[::-1];g = range(61,71);
    h = range(71,81)[::-1];i = range(81,91);j = range(91,101)[::-1]
    #print ("Snakes and Ladders game")
    #print (j,'\n',i,'\n',h,'\n',g,'\n',f,'\n',e,'\n',d,'\n',c,'\n',b,'\n',a)

    def check_for_snakes_and_ladders(n):
        #This method checks for the presence of snakes or ladders on the board
        ladders = {1:26,5:15,11:36,21:42,28:84,36:44,51:67,71:91,80:100}
        snakes = {98:78,95:75,93:73,87:24,64:60,62:19,56:53,49:11,48:26,16:6}
        if n in ladders:
            #print("Its a ladder,Climb up")
            n = ladders[n]
        elif n in snakes:
            #print("Its a snake!!,Come down")
            n = snakes[n]
        return n

    def roll_dice(r,numberOfDiceRolls):
        #This method takes input from each of the players, #prints the current position of the players and checks for the winner of the game
        d = np.random.randint(1,7)
        #print('you have rolled', d)
        d = r + d
        numberOfDiceRolls += 1
        return d

    while (player1 < 100 or player2 < 100):
        #print ("Its turn of player1\n")
        player1 = roll_dice(player1,numberOfDiceRolls)
        player1Moves += 1
        player1 = check_for_snakes_and_ladders(player1)
        #print ("Current status of Player1:",player1,"and Player2:",player2)
        #print ('Player 1 moves', player1Moves)
        #print ('Player 2 moves', player2Moves)
        if (player1 > 99):
            winner.append(1)
            #print ("Winner of the game is player1")
            break

        #print ("Its turn of player2\n")
        player2 = roll_dice(player2,numberOfDiceRolls)
        player2Moves += 1
        player2 = check_for_snakes_and_ladders(player2)
        #print ("Current status of Player1:",player1," and Player2:",player2)

        if (player2 > 99):
            winner.append(1)
            #print ("Winner of the game is player2")
            break
    gameNumberList.append(numberOfGames)
    numberOfGames += 1
    ##print ('Player 1 moves', player1Moves)
    ##print ('Player 2 moves', player2Moves)
    #print(winner)
    #print("-"*50)

    player1MovesInEachGame.append(player1Moves)
    player2MovesInEachGame.append(player2Moves)
    player1Moves = 0
    player2Moves = 0

##print("-"*20," Data Analysis ","-"*20)
for n in winner:
    if (n == 1):
        player1Wins += 1
    elif (n == 2):
        player2Wins += 1
print("Player 1 won",player1Wins,"times")
#print("Player 2 won",player2Wins,"times")
#print(gameNumberList)

#

# In[30]:

num_bins = 100
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2 = axes.flatten()

def hist0(totalNumberOfGames):
    totalNumberOfGames = 100
    mu0 = statistics.mean(player1MovesInEachGame)
    print("Mean amount of rolls is: ",mu0,)
    sigma0 = statistics.stdev(player1MovesInEachGame)
    print("The standard deviation of this data set is: ",sigma0,)

# the histogram of the data
    n, bins, patches = ax0.hist(player1MovesInEachGame, num_bins, normed=1,
                           stacked = True, color = 'red', label = 'Turns to Win')

# add a 'best fit' line
    y = mlab.normpdf(bins, mu0, sigma0)
    ax0.plot(bins, y, '-', color = 'y', label = 'Standard Deviation of Turns')
    ax0.set_xlim(5,120)
    ax0.set_xlabel('Turns')
    ax0.set_ylabel('Probability density')
    ax0.set_title('Percentage of Finished Games in n-turns')
    ax0.legend(prop={'size': 10})

def hist1(totalNumberOfGames):
    totalNumberOfGames = 500
    mu1 = statistics.mean(player1MovesInEachGame)
    print("Mean amount of rolls is: ",mu1,)
    sigma1 = statistics.stdev(player1MovesInEachGame)
    print("The standard deviation of this data set is: ",sigma1,)

# the histogram of the data
    n, bins, patches = ax1.hist(player1MovesInEachGame, num_bins, normed=1,
                           stacked = True, color = 'red', label = 'Turns to Win')

# add a 'best fit' line
    y = mlab.normpdf(bins, mu1, sigma1)
    ax1.plot(bins, y, '-', color = 'y', label = 'Standard Deviation of Turns')
    ax1.set_xlim(5,120)
    ax1.set_xlabel('Turns')
    ax1.set_ylabel('Probability density')
    ax1.set_title('Percentage of Finished Games in n-turns')
    ax1.legend(prop={'size': 10})

def hist2(totalNumberOfGames):
    totalNumberOfGames = 500
    mu2 = statistics.mean(player1MovesInEachGame)
    print("Mean amount of rolls is: ",mu2,)
    sigma2 = statistics.stdev(player1MovesInEachGame)
    print("The standard deviation of this data set is: ",sigma2,)

# the histogram of the data
    n, bins, patches = ax2.hist(player1MovesInEachGame, num_bins, normed=1,
                           stacked = True, color = 'red', label = 'Turns to Win')

# add a 'best fit' line
    y = mlab.normpdf(bins, mu2, sigma2)
    ax2.plot(bins, y, '-', color = 'y', label = 'Standard Deviation of Turns')
    ax2.set_xlim(5,120)
    ax2.set_xlabel('Turns')
    ax2.set_ylabel('Probability density')
    ax2.set_title('Percentage of Finished Games in n-turns')
    ax2.legend(prop={'size': 10})
# Tweak spacing to prevent clipping of ylabel
    fig.tight_layout()
plt.show()

def main():
    hist0(totalNumberOfGames)
    hist1(totalNumberOfGames)
    hist2(totalNumberOfGames)
if __name__ == "__main__":
    main()
</code>```

Error

Traceback (most recent call last):

File "", line 106, in
      ax0, ax1, ax2 = axes.flatten()

ValueError: too many values to unpack (expected 3)

答:
You're creating a subplot grid with 2 rows and 2 columns. 2 times 2 gives 4.

Now using ax0, ax1, ax2 = axes.flatten() you're trying to assing 4 values to 3 variables.

Use

```<code>fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, forgottenaxes = axes.flatten()
</code>```

or directly

```<code>fig, (ax0, ax1, ax2, forgottenaxes) = plt.subplots(nrows=2, ncols=2)
</code>```

Body:
Hi I've created a very simple snakes and ladders program that I want to complete numerical analysis on. I want to find the mean number of rolls it takes to win a game of chutes and laddders.

I have the data, and it works if I choose just one histogram to plot but when I try to change the number of iterations of the game Python doesn't like it and I'm not sure what I've done wrong.

import numpy as np
import numpy as np #importing numpy
get_ipython().magic('matplotlib inline')
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt # importing matplotlib.pyplot
import statistics
#totalNumberOfGames = int(input("PLease enter the number of games you want to run to run:",))
numberOfGames = 1
player1Wins = 0
player2Wins = 0
player1Moves = 0
player2Moves = 0
numberOfDiceRolls = 0
gameNumberList = list()
player1MovesInEachGame = list()
player2MovesInEachGame = list()
winner = list()

while(numberOfGames <= totalNumberOfGames):

    player1 = 0
    player2 = 0

    a = range(1,11);b = range(11,21)[::-1];c = range(21,31);d = range(31,41)[::-1];e = range(41,51);f = range(51,61)[::-1];g = range(61,71);
    h = range(71,81)[::-1];i = range(81,91);j = range(91,101)[::-1]
    #print ("Snakes and Ladders game")
    #print (j,'\n',i,'\n',h,'\n',g,'\n',f,'\n',e,'\n',d,'\n',c,'\n',b,'\n',a)

    def check_for_snakes_and_ladders(n):
        #This method checks for the presence of snakes or ladders on the board
        ladders = {1:26,5:15,11:36,21:42,28:84,36:44,51:67,71:91,80:100}
        snakes = {98:78,95:75,93:73,87:24,64:60,62:19,56:53,49:11,48:26,16:6}
        if n in ladders:
            #print("Its a ladder,Climb up")
            n = ladders[n]
        elif n in snakes:
            #print("Its a snake!!,Come down")
            n = snakes[n]
        return n

    def roll_dice(r,numberOfDiceRolls):
        #This method takes input from each of the players, #prints the current position of the players and checks for the winner of the game
        d = np.random.randint(1,7)
        #print('you have rolled', d)
        d = r + d
        numberOfDiceRolls += 1
        return d

    while (player1 < 100 or player2 < 100):
        #print ("Its turn of player1\n")
        player1 = roll_dice(player1,numberOfDiceRolls)
        player1Moves += 1
        player1 = check_for_snakes_and_ladders(player1)
        #print ("Current status of Player1:",player1,"and Player2:",player2)
        #print ('Player 1 moves', player1Moves)
        #print ('Player 2 moves', player2Moves)
        if (player1 > 99):
            winner.append(1)
            #print ("Winner of the game is player1")
            break

        #print ("Its turn of player2\n")
        player2 = roll_dice(player2,numberOfDiceRolls)
        player2Moves += 1
        player2 = check_for_snakes_and_ladders(player2)
        #print ("Current status of Player1:",player1," and Player2:",player2)

        if (player2 > 99):
            winner.append(1)
            #print ("Winner of the game is player2")
            break
    gameNumberList.append(numberOfGames)
    numberOfGames += 1
    ##print ('Player 1 moves', player1Moves)
    ##print ('Player 2 moves', player2Moves)
    #print(winner)
    #print("-"*50)

    player1MovesInEachGame.append(player1Moves)
    player2MovesInEachGame.append(player2Moves)
    player1Moves = 0
    player2Moves = 0

##print("-"*20," Data Analysis ","-"*20)
for n in winner:
    if (n == 1):
        player1Wins += 1
    elif (n == 2):
        player2Wins += 1
print("Player 1 won",player1Wins,"times")
#print("Player 2 won",player2Wins,"times")
#print(gameNumberList)

#

# In[30]:

num_bins = 100
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2 = axes.flatten()

def hist0(totalNumberOfGames):
    totalNumberOfGames = 100
    mu0 = statistics.mean(player1MovesInEachGame)
    print("Mean amount of rolls is: ",mu0,)
    sigma0 = statistics.stdev(player1MovesInEachGame)
    print("The standard deviation of this data set is: ",sigma0,)

# the histogram of the data
    n, bins, patches = ax0.hist(player1MovesInEachGame, num_bins, normed=1,
                           stacked = True, color = 'red', label = 'Turns to Win')

# add a 'best fit' line
    y = mlab.normpdf(bins, mu0, sigma0)
    ax0.plot(bins, y, '-', color = 'y', label = 'Standard Deviation of Turns')
    ax0.set_xlim(5,120)
    ax0.set_xlabel('Turns')
    ax0.set_ylabel('Probability density')
    ax0.set_title('Percentage of Finished Games in n-turns')
    ax0.legend(prop={'size': 10})

def hist1(totalNumberOfGames):
    totalNumberOfGames = 500
    mu1 = statistics.mean(player1MovesInEachGame)
    print("Mean amount of rolls is: ",mu1,)
    sigma1 = statistics.stdev(player1MovesInEachGame)
    print("The standard deviation of this data set is: ",sigma1,)

# the histogram of the data
    n, bins, patches = ax1.hist(player1MovesInEachGame, num_bins, normed=1,
                           stacked = True, color = 'red', label = 'Turns to Win')

# add a 'best fit' line
    y = mlab.normpdf(bins, mu1, sigma1)
    ax1.plot(bins, y, '-', color = 'y', label = 'Standard Deviation of Turns')
    ax1.set_xlim(5,120)
    ax1.set_xlabel('Turns')
    ax1.set_ylabel('Probability density')
    ax1.set_title('Percentage of Finished Games in n-turns')
    ax1.legend(prop={'size': 10})

def hist2(totalNumberOfGames):
    totalNumberOfGames = 500
    mu2 = statistics.mean(player1MovesInEachGame)
    print("Mean amount of rolls is: ",mu2,)
    sigma2 = statistics.stdev(player1MovesInEachGame)
    print("The standard deviation of this data set is: ",sigma2,)

# the histogram of the data
    n, bins, patches = ax2.hist(player1MovesInEachGame, num_bins, normed=1,
                           stacked = True, color = 'red', label = 'Turns to Win')

# add a 'best fit' line
    y = mlab.normpdf(bins, mu2, sigma2)
    ax2.plot(bins, y, '-', color = 'y', label = 'Standard Deviation of Turns')
    ax2.set_xlim(5,120)
    ax2.set_xlabel('Turns')
    ax2.set_ylabel('Probability density')
    ax2.set_title('Percentage of Finished Games in n-turns')
    ax2.legend(prop={'size': 10})
# Tweak spacing to prevent clipping of ylabel
    fig.tight_layout()
plt.show()

def main():
    hist0(totalNumberOfGames)
    hist1(totalNumberOfGames)
    hist2(totalNumberOfGames)
if __name__ == "__main__":
    main()

Error

Traceback (most recent call last):

File "", line 106, in
      ax0, ax1, ax2 = axes.flatten()

ValueError: too many values to unpack (expected 3)

Body:
You're creating a subplot grid with 2 rows and 2 columns. 2 times 2 gives 4.

Now using ax0, ax1, ax2 = axes.flatten() you're trying to assing 4 values to 3 variables.

Use

fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, forgottenaxes = axes.flatten()

or directly

fig, (ax0, ax1, ax2, forgottenaxes) = plt.subplots(nrows=2, ncols=2)


问:
Angular Route No Errors but Not Woking
It's just simple but I don't know what's wrong. I have the following example, making a simple web template with angular ui-router and angular 1.2.16.

```<code>     <script type='text/javascript' src='angular.js'></script>
     <script type='text/javascript' src='angular-ui-router.js'></script>
     <script type='text/javascript' src='js/me/app.js'></script>
</code>```

I've written the app.js and index.html something like this

app.js

```<code>angular.module('app',[
    'ui.router'

])
.config(['$urlRouterProvider','$stateProvider'],function($urlRouterProvider,$stateProvider){
    $urlRouterProvider.otherwise('/');

    //console.log($urlRouterProvider);

    $stateProvider
    .state('home',{
        url:'/',
        templateUrl:'home.html'
    })
})
</code>```

and the index.html is

```<code>    <body ng-app="app">
           <header ng-include="'header.html'"></header>
            <!-- End of Header -->
           <div ui-view="''"></div>
           <footer ng-include="'footer.html'"></footer></body>
</code>```

My header and footer work properly. That is a good first step.  But when I try routes, nothing happens.

In my console there are no errors at all.. I don't understand, what is the matter?  I think it's quite simple.  Maybe because I'm very new to angular.  So, if you can suggest solutions out there, please help.

答:
My issue was a bad path in my url:

Check the URL! http://example.com/#/ is not registered and $stateProvider won't tell you it's wrong.

I simply had to remove "/#/" from my URL.

I suppose a hash got added on somewhere, but I had the same problem as OP: header and footer were fine, but nothing inside <ui-view></ui-view>

No idea why the devs would make it so that when you go to an unregistered path it gives no errors or indication of any kind that something bad happened, but there you go...

How to permanently fix this issue:

$stateProvider overrides $urlProvider, so .otherwise won't work.

Add an otherwise state:

```<code>/// OP's code ///
$stateProvider
  .state('home',{
    url:'/',
    templateUrl:'home.html'
  })

                              // Just add a new state
  .state('otherwise',{
    url:'*path',              // uses regex, and doesn't mess up preceding state urls
    templateUrl: 'home.html'  // sends the user back home if a bad url happens
  })
</code>```

In response to using $rootScope

While @GlenFilson's answer did not provide any indication the path was incorrect, I was able to figure out where his answer should go:

```<code>var app = angular.module(...); // can't inject $rootScope here except through providers (e.g., $httpProvider)
app.config(...);               // nor here

// define app.run() after configuration

app.run(function($rootScope){
    $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
      $dialogs.error("Something went wrong!", error);
      console.error("$stateChangeError: ", toState, error);
    });
})
</code>```

Title: Angular Route No Errors but Not Woking

Body:
It's just simple but I don't know what's wrong. I have the following example, making a simple web template with angular ui-router and angular 1.2.16.

I've written the app.js and index.html something like this

app.js

angular.module('app',[
    'ui.router'

])
.config(['$urlRouterProvider','$stateProvider'],function($urlRouterProvider,$stateProvider){
    $urlRouterProvider.otherwise('/');

    //console.log($urlRouterProvider);

    $stateProvider
    .state('home',{
        url:'/',
        templateUrl:'home.html'
    })
})

and the index.html is

My header and footer work properly. That is a good first step.  But when I try routes, nothing happens.

In my console there are no errors at all.. I don't understand, what is the matter?  I think it's quite simple.  Maybe because I'm very new to angular.  So, if you can suggest solutions out there, please help.

Body:
My issue was a bad path in my url:

Check the URL! http://example.com/#/ is not registered and $stateProvider won't tell you it's wrong.

I simply had to remove "/#/" from my URL.

I suppose a hash got added on somewhere, but I had the same problem as OP: header and footer were fine, but nothing inside <ui-view></ui-view>

No idea why the devs would make it so that when you go to an unregistered path it gives no errors or indication of any kind that something bad happened, but there you go...

How to permanently fix this issue:

$stateProvider overrides $urlProvider, so .otherwise won't work.

Add an otherwise state:

/// OP's code ///
$stateProvider
  .state('home',{
    url:'/',
    templateUrl:'home.html'
  })

                              // Just add a new state
  .state('otherwise',{
    url:'*path',              // uses regex, and doesn't mess up preceding state urls
    templateUrl: 'home.html'  // sends the user back home if a bad url happens
  })

In response to using $rootScope

While @GlenFilson's answer did not provide any indication the path was incorrect, I was able to figure out where his answer should go:

var app = angular.module(...); // can't inject $rootScope here except through providers (e.g., $httpProvider)
app.config(...);               // nor here

// define app.run() after configuration

app.run(function($rootScope){
    $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
      $dialogs.error("Something went wrong!", error);
      console.error("$stateChangeError: ", toState, error);
    });
})


问:
Can't access enum within struct
I have the following struct defined

Header File:

```<code>struct SDK {
   enum {
       HEADER0 = 0,
       HEADER1,
       LINGO,
       COMMAND,
       LENGTH,
       ACK_CMD,
       ACK_STATUS
   }commandFormat;
}mySDK;
</code>```

and I want to use it like this:

main.c

```<code>switch (rxData[mySDK.commandFormat.LINGO]) {
   default:
      break;
}
</code>```

I am getting the error: request for member 'LINGO' in something not a structure or union

I know I'm probably doing something stupid, but I can't figure out what exactly. Thank you.

答:
```<code>struct SDK {
   enum {
       HEADER0 = 0,
       HEADER1,
       LINGO,
       COMMAND,
       LENGTH,
       ACK_CMD,
       ACK_STATUS
   }commandFormat;
}mySDK;
</code>```

creates integer constants

```<code>   HEADER0,
   HEADER1,
   LINGO,
   COMMAND,
   LENGTH,
   ACK_CMD,
   ACK_STATUS
</code>```

in the global scope.

It also defines

```<code>struct SDK {
   enum <anonymous> commandFormat;
};
</code>```

where the debugger will interpret the values of commandFormat as one the above integer constants,
and it defines an instance of that struct named mySDK.

mySDK.commandFormat is an integer (enum).
It doesn't make sense to apply . to it.

Title: Can't access enum within struct

Body:
I have the following struct defined

Header File:

struct SDK {
   enum {
       HEADER0 = 0,
       HEADER1,
       LINGO,
       COMMAND,
       LENGTH,
       ACK_CMD,
       ACK_STATUS
   }commandFormat;
}mySDK;

and I want to use it like this:

main.c

switch (rxData[mySDK.commandFormat.LINGO]) {
   default:
      break;
}

I am getting the error: request for member 'LINGO' in something not a structure or union

I know I'm probably doing something stupid, but I can't figure out what exactly. Thank you.

Body:
struct SDK {
   enum {
       HEADER0 = 0,
       HEADER1,
       LINGO,
       COMMAND,
       LENGTH,
       ACK_CMD,
       ACK_STATUS
   }commandFormat;
}mySDK;

creates integer constants

   HEADER0,
   HEADER1,
   LINGO,
   COMMAND,
   LENGTH,
   ACK_CMD,
   ACK_STATUS

in the global scope.

It also defines

struct SDK {
   enum <anonymous> commandFormat;
};

where the debugger will interpret the values of commandFormat as one the above integer constants,
and it defines an instance of that struct named mySDK.

mySDK.commandFormat is an integer (enum).
It doesn't make sense to apply . to it.


问:
How to deploy web app directly from Visual Studio 2008?
I used to use discountasp.net and I can use Visual Studio 2008 to "publish" the website directly to the web host. I am using a dedicated server now (well, to be exact, Amazon EC2 Windows), how should I setup the web server so I can deploy the website directly from VS 2008? I tried to setup a FTP server but couldn't get it working.

Thanks!

答:
Some basics first -

Have you verified that you can connect to the FTP account on the EC2 server using a standard FTP client?

What FTP server are you using on the server?

Did you check to see what connection types are supported on the FTP server, Active or Passive (or both). I think the publish web site wizard will use whatever connection type is specified in your IE browser FTP settings (Tools - Advanced - Use Passive FTP), the default is to use passive FTP.

Updated: Also see bold text in @Splattne's answer about opening ports 20/21 on the ec2 firewall.

LastEditorDisplayName: splattne

OwnerDisplayName: Kev

LastEditorDisplayName: Kev


问:
Error while updating business network in CLI tutorial
I am following along the Getting Started with Fabric Command Line and have run into a error I don't understand how to resolve.  Any ideas?

In the section entitled "Update the deployed business network" an exception is thrown.  The terminal output is below.  The command used:

```<code>composer network update --archiveFile digitalproperty-network@0.0.7.bna  --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d
</code>```

Note that the id is different from the tutorial as the 0.0.7 id was reported during the previous step while creating.  The output continued...

```<code>Deploying business network from archive digitalproperty-network@0.0.7.bna
Business network definition:
    Identifier: digitalproperty-network@0.0.7
    Description: Digital Property Network
events.js:160
      throw er; // Unhandled 'error' event
      ^
Error
    at ClientDuplexStream._emitStatusIfDone (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:189:19)
    at ClientDuplexStream._readsDone (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:158:8)
    at readCallback (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:217:12)
</code>```

I've struggled to get the versions to match the tutorials - they seem inconsistent.  Notably, the node (v6.9.5) and nodejs (v6.10.1) versions differ even though node is a symbolic link to nodejs and I notice 6.9.5 is in the stack trace.  I'm not sure that difference is relevant to the problem.

Other version information:

Ubuntu 14.04.5

Docker version 17.03.1-ce, build c6d412e (manually installed as auto
install was down level)

docker-compose version 1.12.0-rc2, build 08dc2a4

答: I've seen exactly that error when Hyperledger Fabric isn't running. If docker ps doesn't show anything, run npm run startHLF in the sample-applications/packages/getting-started directory before trying again.

Body:
I am following along the Getting Started with Fabric Command Line and have run into a error I don't understand how to resolve.  Any ideas?

In the section entitled "Update the deployed business network" an exception is thrown.  The terminal output is below.  The command used:

composer network update --archiveFile digitalproperty-network@0.0.7.bna  --enrollId WebAppAdmin --enrollSecret DJY27pEnl16d

Note that the id is different from the tutorial as the 0.0.7 id was reported during the previous step while creating.  The output continued...

Deploying business network from archive digitalproperty-network@0.0.7.bna
Business network definition:
    Identifier: digitalproperty-network@0.0.7
    Description: Digital Property Network
events.js:160
      throw er; // Unhandled 'error' event
      ^
Error
    at ClientDuplexStream._emitStatusIfDone (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:189:19)
    at ClientDuplexStream._readsDone (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:158:8)
    at readCallback (/home/mnjacobs/.nvm/versions/node/v6.9.5/lib/node_modules/composer-cli/node_modules/grpc/src/node/src/client.js:217:12)

I've struggled to get the versions to match the tutorials - they seem inconsistent.  Notably, the node (v6.9.5) and nodejs (v6.10.1) versions differ even though node is a symbolic link to nodejs and I notice 6.9.5 is in the stack trace.  I'm not sure that difference is relevant to the problem.

Other version information:

Ubuntu 14.04.5

Docker version 17.03.1-ce, build c6d412e (manually installed as auto
install was down level)

docker-compose version 1.12.0-rc2, build 08dc2a4


问:
combinations of each string of a column with each string of another column in R
This is the table with many rows, but for simplicity of the problem...

```<code>dt1 <-data.frame(col1=c("C,Y,M","B,C,M,A"),col2=c("B,E,M","B,A,G"),col3=c("2","10"))

     col1          col2         col3
1    C,Y,M         B,E,M        2
2    B,C,M,A       B,F,G        10
</code>```

So what I am trying to do is

1. every string of each column should be paired, but if there is a common string ignore that, for example C with B, C with E but not C with M because M is there in both the columns of that row and similarly Y with B, Y with E again not with M.

2. Their corresponding values as col3

the output table

```<code>dt2 <- data.frame(col1 =c("C","C","Y","Y","C","C","M","M","A","A"),col2 = c("B","E","B","E","F","G","F","G","F","G"),col3=c("2","2","2","2","10","10","10","10","10","10"))

  col1      col2       col3
1    C         B          2
2    C         E          2
3    Y         B          2
4    Y         E          2
5    C         F         10
6    C         G         10
7    M         F         10
8    M         G         10
9    A         F         10
10   A         G         10
</code>```

答:
Perhaps you can try something like this (note that there's a mistake in your sample data....):</p>

```<code>dt1 <- data.frame(col1 = c("C,Y,M","B,C,M,A"),
                  col2 = c("B,E,M","B,F,G"),
                  col3 = c("2","10"))

x <- lapply(dt1, function(x) strsplit(as.character(x), ",", TRUE))

myFun <- function(x, y, z) {
  drop <- intersect(x, y)
  expand.grid(x[!x %in% drop], y[!y %in% drop], z)
}

do.call(rbind, Map(myFun, x[[1]], x[[2]], x[[3]]))
#    Var1 Var2 Var3
# 1     C    B    2
# 2     Y    B    2
# 3     C    E    2
# 4     Y    E    2
# 5     C    F   10
# 6     M    F   10
# 7     A    F   10
# 8     C    G   10
# 9     M    G   10
# 10    A    G   10
</code>```

Body:
This is the table with many rows, but for simplicity of the problem...

dt1 <-data.frame(col1=c("C,Y,M","B,C,M,A"),col2=c("B,E,M","B,A,G"),col3=c("2","10"))

     col1          col2         col3
1    C,Y,M         B,E,M        2
2    B,C,M,A       B,F,G        10

So what I am trying to do is

1. every string of each column should be paired, but if there is a common string ignore that, for example C with B, C with E but not C with M because M is there in both the columns of that row and similarly Y with B, Y with E again not with M.

2. Their corresponding values as col3

the output table

dt2 <- data.frame(col1 =c("C","C","Y","Y","C","C","M","M","A","A"),col2 = c("B","E","B","E","F","G","F","G","F","G"),col3=c("2","2","2","2","10","10","10","10","10","10"))

  col1      col2       col3
1    C         B          2
2    C         E          2
3    Y         B          2
4    Y         E          2
5    C         F         10
6    C         G         10
7    M         F         10
8    M         G         10
9    A         F         10
10   A         G         10

Body:
Perhaps you can try something like this (note that there's a mistake in your sample data....):

dt1 <- data.frame(col1 = c("C,Y,M","B,C,M,A"),
                  col2 = c("B,E,M","B,F,G"),
                  col3 = c("2","10"))

x <- lapply(dt1, function(x) strsplit(as.character(x), ",", TRUE))

myFun <- function(x, y, z) {
  drop <- intersect(x, y)
  expand.grid(x[!x %in% drop], y[!y %in% drop], z)
}

do.call(rbind, Map(myFun, x[[1]], x[[2]], x[[3]]))
#    Var1 Var2 Var3
# 1     C    B    2
# 2     Y    B    2
# 3     C    E    2
# 4     Y    E    2
# 5     C    F   10
# 6     M    F   10
# 7     A    F   10
# 8     C    G   10
# 9     M    G   10
# 10    A    G   10


问:
send email alert through excel
I am trying to send an email alert from Excel, if the date mentioned in Column F is older than 2 years from the current date.
I am getting error Runtime 462 in the following command
.send
Please suggest.</p>

```<code>Sub send_files()

        Dim OutMail As Object
        Dim sh As Worksheet
        Dim cell As Range
        Dim FileCell As Range
        Dim bottomA As Integer
        Dim x As Integer
        Dim mydate1 As Date
        Dim mydate2 As Long
        Dim datetoday1 As Date
        Dim datetoday2 As Long
        Dim outlookapp As Object

        Set sh = ThisWorkbook.Sheets("Sheet1")

        bottomA = sh.Range("F" & Rows.Count).End(xlUp).Row

        For x = 2 To bottomA

        mydate1 = Cells(x, 6).Value

        mydate2 = mydate1

    Cells(x, 13).Value = mydate2

    datetoday1 = Date

    datetoday2 = datetoday1

    Cells(x, 14).Value = datetoday2

    If datetoday2 - mydate2 >= 730 Then

    Set outlookapp = CreateObject("Outlook.Application")

    Set OutMail = outlookapp.CreateItem(0)

    With OutMail
        .to = Cells(2, 17).Value

        .Subject = "Folder Expiration Alert"

        .Body = "Hi"

        .send

        End With

        End If

        Next

     Set outlookapp = Nothing

    Set OutMail = Nothing

End Sub
</code>```

答:
Run macro when you manual change a cell

To run a macro automatic when you manual change a specific cell you can use the Change event in a worksheet module.The example on this page use Cell A1 and will run the macro if the cell value >200.

1) Right click on a sheet tab and choose view code
2) Paste the event below in the sheet module.
3) Alt-q to go back to Excel

Note: Change YourMacroName to the name of your macro in the code.
If you want the code to work for another cell or more cells you can change the range in the event.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("A1"), Target) Is Nothing Then
        If IsNumeric(Target.Value) And Target.Value > 200 Then
            Call YourMacroName
        End If
    End If
End Sub
</code>```

Example mail macro

Test this example macro to create/display a Outlook mail with a small text message.
You must copy this macro in a standard module and not in the worksheet module, see this page how.

Note: I use .Display in the code to display the mail, you can change that to .Send

Do not forget to change Call YourMacroName to Call Mail_small_Text_Outlook in the Change event.

```<code>Sub Mail_small_Text_Outlook()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Working in Excel 2000-2016
    Dim OutApp As Object
    Dim OutMail As Object
    Dim strbody As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    strbody = "Hi there" & vbNewLine & vbNewLine & _
              "Cell A1 is changed" & vbNewLine & _
              "This is line 2" & vbNewLine & _
              "This is line 3" & vbNewLine & _
              "This is line 4"

    On Error Resume Next
    With OutMail
        .To = "ron@debruin.nl"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = strbody
        'You can add a file like this
        '.Attachments.Add ("C:\test.txt")
        .Display   'or use .Send
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub
</code>```

https://www.rondebruin.nl/win/s1/outlook/bmail9.htm

Title: send email alert through excel

Body:
I am trying to send an email alert from Excel, if the date mentioned in Column F is older than 2 years from the current date.
I am getting error Runtime 462 in the following command
.send
Please suggest.

Sub send_files()

        Dim OutMail As Object
        Dim sh As Worksheet
        Dim cell As Range
        Dim FileCell As Range
        Dim bottomA As Integer
        Dim x As Integer
        Dim mydate1 As Date
        Dim mydate2 As Long
        Dim datetoday1 As Date
        Dim datetoday2 As Long
        Dim outlookapp As Object

        Set sh = ThisWorkbook.Sheets("Sheet1")

        bottomA = sh.Range("F" & Rows.Count).End(xlUp).Row

        For x = 2 To bottomA

        mydate1 = Cells(x, 6).Value

        mydate2 = mydate1

    Cells(x, 13).Value = mydate2

    datetoday1 = Date

    datetoday2 = datetoday1

    Cells(x, 14).Value = datetoday2

    If datetoday2 - mydate2 >= 730 Then

    Set outlookapp = CreateObject("Outlook.Application")

    Set OutMail = outlookapp.CreateItem(0)

    With OutMail
        .to = Cells(2, 17).Value

        .Subject = "Folder Expiration Alert"

        .Body = "Hi"

        .send

        End With

        End If

        Next

     Set outlookapp = Nothing

    Set OutMail = Nothing

End Sub

Body:
Run macro when you manual change a cell

To run a macro automatic when you manual change a specific cell you can use the Change event in a worksheet module.The example on this page use Cell A1 and will run the macro if the cell value >200.

1) Right click on a sheet tab and choose view code
2) Paste the event below in the sheet module.
3) Alt-q to go back to Excel

Note: Change YourMacroName to the name of your macro in the code.
If you want the code to work for another cell or more cells you can change the range in the event.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("A1"), Target) Is Nothing Then
        If IsNumeric(Target.Value) And Target.Value > 200 Then
            Call YourMacroName
        End If
    End If
End Sub

Example mail macro

Test this example macro to create/display a Outlook mail with a small text message.
You must copy this macro in a standard module and not in the worksheet module, see this page how.

Note: I use .Display in the code to display the mail, you can change that to .Send

Do not forget to change Call YourMacroName to Call Mail_small_Text_Outlook in the Change event.

Sub Mail_small_Text_Outlook()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Working in Excel 2000-2016
    Dim OutApp As Object
    Dim OutMail As Object
    Dim strbody As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    strbody = "Hi there" & vbNewLine & vbNewLine & _
              "Cell A1 is changed" & vbNewLine & _
              "This is line 2" & vbNewLine & _
              "This is line 3" & vbNewLine & _
              "This is line 4"

    On Error Resume Next
    With OutMail
        .To = "ron@debruin.nl"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = strbody
        'You can add a file like this
        '.Attachments.Add ("C:\test.txt")
        .Display   'or use .Send
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

https://www.rondebruin.nl/win/s1/outlook/bmail9.htm


问:
MySQL update from select
Having trouble with this query:

```<code>UPDATE table1 t1 SET t1.custom_id=(SELECT t2.custom_id
FROM table2 t2 WHERE LOWER(t1.first_name)=LOWER(t2.first_name)
AND LOWER(t1.last_name)=LOWER(t2.last_name)
AND (t2.zip1 LIKE CONCAT('%',t1.zip,'%')
OR t2.zip2 LIKE CONCAT('%',t1.zip,'%')) LIMIT 1)
</code>```

I triple-checked that php variables match the field names. When I split it into multiple queries update works fine.

答:
You could have tried searching StackOIverflow for an answer first, but in your case something like this should work:</p>

```<code> UPDATE table1 t1
 join table2 t2 on
 LOWER (t1.first_name) = LOWER (t2.first_name)
        AND LOWER (t1.last_name) = LOWER (t2.last_name)
         AND (   t2.zip1 LIKE CONCAT ('%', t1.zip, '%')
             OR t2.zip2 LIKE CONCAT ('%', t1.zip, '%')) LIMIT 1)
 SET custom_id = t2.custom_id
</code>```

Title: MySQL update from select

Body:
Having trouble with this query:

UPDATE table1 t1 SET t1.custom_id=(SELECT t2.custom_id
FROM table2 t2 WHERE LOWER(t1.first_name)=LOWER(t2.first_name)
AND LOWER(t1.last_name)=LOWER(t2.last_name)
AND (t2.zip1 LIKE CONCAT('%',t1.zip,'%')
OR t2.zip2 LIKE CONCAT('%',t1.zip,'%')) LIMIT 1)

I triple-checked that php variables match the field names. When I split it into multiple queries update works fine.

Body:
You could have tried searching StackOIverflow for an answer first, but in your case something like this should work:

 UPDATE table1 t1
 join table2 t2 on
 LOWER (t1.first_name) = LOWER (t2.first_name)
        AND LOWER (t1.last_name) = LOWER (t2.last_name)
         AND (   t2.zip1 LIKE CONCAT ('%', t1.zip, '%')
             OR t2.zip2 LIKE CONCAT ('%', t1.zip, '%')) LIMIT 1)
 SET custom_id = t2.custom_id


问:
Big-Oh ascending order of some functions f(n)
Put these function in the ascending order of their growth in terms of n:
 2^((log n)^0.5), 2^n, 2^(n/2), n^(4/3), n(log n)^3, n^(log n), 2^(n^2), n!</p>

答:
The way you solve this problem is by seeing which function approaches infinity fastest as n approaches infinity. Suppose you have some functions:

```<code>f(n) = n!
g(n) = n
h(n) = 3^n
</code>```

You can compare any two functions by evaluating their ratio as n approaches infinity. For example:

```<code>Lim      f(n) /
n->∞         / g(n)
</code>```

If the result is greater than 1, then f(n) is asymptotically greater than g(n). If the result is 1, then they are asymptotically the same. If the result is less than one, then f(n) is asymptotically less than g(n).

You may find that some are easy to solve, like f(n) and g(n), and you can simplify the expression to get a definite value at the limit.

```<code>    f(n) /       = n! /    = n (n-1)! /   = (n-1)!
        / g(n)       / n             / n
</code>```

The limit as n goes to infinity of this expression is infinity, which means that f(n) is asymptotically greater than g(n).

Other expressions are not as simple. If evaluating the limit gives you an indeterminite form, you need to use L'Hôpital's rule.

```<code>Lim      g(n) /        =  Lim    n /     =  ∞ /
n->∞         / h(n)       n->∞    / 3^n      / ∞
</code>```

According to L'Hôpital's rule, we can evaluate a limit by substituting g'(n) and h'(n).

```<code>Lim      g'(n) /         =  Lim    1 /           =  1 /
n->∞          / h'(n)       n->∞    / 3^n ln(3)      / ∞
</code>```

This limit is clearly less than 1, so we can say that g(n) is asymptotically less than h(n).

Body:
The way you solve this problem is by seeing which function approaches infinity fastest as n approaches infinity. Suppose you have some functions:

f(n) = n!
g(n) = n
h(n) = 3^n

You can compare any two functions by evaluating their ratio as n approaches infinity. For example:

Lim      f(n) /
n->∞         / g(n)

If the result is greater than 1, then f(n) is asymptotically greater than g(n). If the result is 1, then they are asymptotically the same. If the result is less than one, then f(n) is asymptotically less than g(n).

You may find that some are easy to solve, like f(n) and g(n), and you can simplify the expression to get a definite value at the limit.

    f(n) /       = n! /    = n (n-1)! /   = (n-1)!
        / g(n)       / n             / n

The limit as n goes to infinity of this expression is infinity, which means that f(n) is asymptotically greater than g(n).

Other expressions are not as simple. If evaluating the limit gives you an indeterminite form, you need to use L'Hôpital's rule.

Lim      g(n) /        =  Lim    n /     =  ∞ /
n->∞         / h(n)       n->∞    / 3^n      / ∞

According to L'Hôpital's rule, we can evaluate a limit by substituting g'(n) and h'(n).

Lim      g'(n) /         =  Lim    1 /           =  1 /
n->∞          / h'(n)       n->∞    / 3^n ln(3)      / ∞

This limit is clearly less than 1, so we can say that g(n) is asymptotically less than h(n).


问:
Print a string (up to 10 chars) as a diamond
I need to print a string (up to 10 chars) as a diamond.

Well, I tried for almost 2-3 hours now to solve it and I'm still having many problems.

Here's the code: it works for outputs 'a', 'abc', 'abcde'. which means only works for strings with length of 1,3,5. and also, it only prints the first half of the diamond.

Any help is highly appreciated.

import java.util.Scanner;

```<code>public class MyFirstClass1
{
    public static void main(String[] args)
    {
        int halfSize;
        int p = 0;
        String message;
        System.out.println("Please enter a string: ");
        Scanner input = new Scanner(System.in);

        message = input.nextLine();
        //System.out.println((int)Math.ceil(message.length() / 2) + 1);
        halfSize = message.length() / 2;
         for (int i = 1; i <= message.length(); i++) {
             //Print spaces
              for (int k = 0; k < halfSize; k++)
                System.out.print(" ");
              halfSize--;

              System.out.print("\n");

              if((int)Math.ceil((float)message.length() / 2) + 1 >= p)
              {
              for (int j = 0; j < p + 1; j++)
                  System.out.print(message.charAt(j));
              }
              p+=2;
           }

    }
}
</code>```

答:
There were lot of logical errors. I have fixed them. This is working code:</p>

```<code>import java.util.Scanner;
public class HelloWorld{

 public static void main(String []args){
    System.out.println("Hello World");
    int halfSize;
    int p = 0;
    String message;
    System.out.println("Please enter a string: ");
    Scanner input = new Scanner(System.in);

    message = input.nextLine();
    halfSize = 2 * message.length() - 1;

     for (int i = 1; i <= message.length(); i++) {
         int pre_post_blank = (2 * halfSize) - ( 2 * i -1);

          for (int k = 0; k < pre_post_blank / 2; k++)
            System.out.print(" ");

          for(int j = 0; j < i;j++ )
          {
              System.out.print(message.charAt(j));
              System.out.print(" ");
          }

          for (int k = 0; k < pre_post_blank / 2; k++)
            System.out.print(" ");

          System.out.print("\n");
       }
       for (int i = message.length(); i >= 1; i--) {
         int pre_post_blank = (2 * halfSize) - ( 2 * i -1);

          for (int k = 0; k < pre_post_blank / 2; k++)
            System.out.print(" ");

          for(int j = 0; j < i;j++ )
          {
              System.out.print(message.charAt(j));
              System.out.print(" ");
          }

          for (int k = 0; k < pre_post_blank / 2; k++)
            System.out.print(" ");

          System.out.print("\n");
       }

   }
 }
</code>```

Body:
I need to print a string (up to 10 chars) as a diamond.

Well, I tried for almost 2-3 hours now to solve it and I'm still having many problems.

Here's the code: it works for outputs 'a', 'abc', 'abcde'. which means only works for strings with length of 1,3,5. and also, it only prints the first half of the diamond.

Any help is highly appreciated.

import java.util.Scanner;

public class MyFirstClass1
{
    public static void main(String[] args)
    {
        int halfSize;
        int p = 0;
        String message;
        System.out.println("Please enter a string: ");
        Scanner input = new Scanner(System.in);

        message = input.nextLine();
        //System.out.println((int)Math.ceil(message.length() / 2) + 1);
        halfSize = message.length() / 2;
         for (int i = 1; i <= message.length(); i++) {
             //Print spaces
              for (int k = 0; k < halfSize; k++)
                System.out.print(" ");
              halfSize--;

              System.out.print("\n");

              if((int)Math.ceil((float)message.length() / 2) + 1 >= p)
              {
              for (int j = 0; j < p + 1; j++)
                  System.out.print(message.charAt(j));
              }
              p+=2;
           }

    }
}

Body:
There were lot of logical errors. I have fixed them. This is working code:

import java.util.Scanner;
public class HelloWorld{

 public static void main(String []args){
    System.out.println("Hello World");
    int halfSize;
    int p = 0;
    String message;
    System.out.println("Please enter a string: ");
    Scanner input = new Scanner(System.in);

    message = input.nextLine();
    halfSize = 2 * message.length() - 1;

     for (int i = 1; i <= message.length(); i++) {
         int pre_post_blank = (2 * halfSize) - ( 2 * i -1);

          for (int k = 0; k < pre_post_blank / 2; k++)
            System.out.print(" ");

          for(int j = 0; j < i;j++ )
          {
              System.out.print(message.charAt(j));
              System.out.print(" ");
          }

          for (int k = 0; k < pre_post_blank / 2; k++)
            System.out.print(" ");

          System.out.print("\n");
       }
       for (int i = message.length(); i >= 1; i--) {
         int pre_post_blank = (2 * halfSize) - ( 2 * i -1);

          for (int k = 0; k < pre_post_blank / 2; k++)
            System.out.print(" ");

          for(int j = 0; j < i;j++ )
          {
              System.out.print(message.charAt(j));
              System.out.print(" ");
          }

          for (int k = 0; k < pre_post_blank / 2; k++)
            System.out.print(" ");

          System.out.print("\n");
       }

   }
 }


问:
Kentico 9 BizForm validation/visiblity rules
I'm building out a custom page type. I have two fields, Name and File,  and i'm hoping to accomplish the following:

File is not visible or active until Name is filled out.

If Name has a value, then File is required.

I don't see an option to make a field required if another field has a value.

答:
To make the File field appear when the Name field is set:

On Name  field, check has depending fields.

On the File field

check depends on another field.

set visibility condition, to Name.Value != ""

You can't check required on File, but you can set a validation rule that checks if it is null, that validation only runs if the field is visible.

See Field editor reference scroll down to Field advanced settings for more details on the Visibility condition.


问:
ASP.NET - Array from Checkbox Post
I'm trying to parse posted checkbox's into an array variable in csharp. Example:

 <input type="checkbox" name="ID[]" value="1" />
 <input type="checkbox" name="ID[]" value="2" />
 <input type="checkbox" name="ID[]" value="3" />
 <input type="checkbox" name="ID[]" value="4" />```
</div>
</div>
</p>

<p>That will be parsed from Request into something like this: </p>

```int[] IDs = new int[] { 1, 2, 3, 4 };
```

答:
What I was seeking:  </p>

```<code>string[] ids = Request.Form.GetValues("id[]");
</code>```

Title: ASP.NET - Array from Checkbox Post

Body:
I'm trying to parse posted checkbox's into an array variable in csharp. Example:

 <input type="checkbox" name="ID[]" value="1" />
 <input type="checkbox" name="ID[]" value="2" />
 <input type="checkbox" name="ID[]" value="3" />
 <input type="checkbox" name="ID[]" value="4" />

That will be parsed from Request into something like this:

int[] IDs = new int[] { 1, 2, 3, 4 };

Body:
What I was seeking:

string[] ids = Request.Form.GetValues("id[]");