问:
Launching custom Activity when alarm goes off in custom alarm clock app Android
I know there is a lot of discussion about AlarmClock and AlarmManager and how to set alarms, launch apps, etc. However, I am yet to find the perfect answer for the following scenario.

In my Android alarm clock application I'm developing, I want to set an alarm for a specific time, pass in other settings such as what song to play, vibrate, etc.

1) what should I use to do this? AlarmClock or AlarmManager?

2) Now, when the alarm goes off at the specified time, how do I tell it to launch my custom Activity? Again the question of AlarmClock or AlarmManager.

This custom activity would show the time and have buttons saying "Sleep" or "Snooze" which the user can press (pretty much what happens when an alarm in any other alarm clock app goes off). I don't want to launch my alarm app, ONLY that one screen when the alarm goes off. When the user hits a button, I want to close that custom acitvity and for nothing else related to that app to open. I would like it so that the user can go back to doing whatever they were doing.

答:
I think you can do your job with AlarmManager. As you say, if you want to set alarm for a specific time, you should use setRepeating(). If you want to wake up your device when the alarm fires choose RTC_WAKEUP type and if you don't want that RTC type. You define a PendingIntent, whatever you want to do(play sound, light and vibrate), you can do within this activity that attached to this intent. You should design your layout in that(YOUR_ACTIVITY) layout and put buttons to snooze/cancel alarm.

```<code>private AlarmManager alarmMgr;
private PendingIntent alarmIntent;

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, YOUR_ACTIVITY.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
        calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
</code>```

Above code set an alarm for 14:00 and interval of one day which means it will be fired everyday 14:00 and run YOUR_ACTIVITY until you cancel it. this is an example in Google Android Documents.

Body:
I think you can do your job with AlarmManager. As you say, if you want to set alarm for a specific time, you should use setRepeating(). If you want to wake up your device when the alarm fires choose RTC_WAKEUP type and if you don't want that RTC type. You define a PendingIntent, whatever you want to do(play sound, light and vibrate), you can do within this activity that attached to this intent. You should design your layout in that(YOUR_ACTIVITY) layout and put buttons to snooze/cancel alarm.

private AlarmManager alarmMgr;
private PendingIntent alarmIntent;

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, YOUR_ACTIVITY.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
        calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);

Above code set an alarm for 14:00 and interval of one day which means it will be fired everyday 14:00 and run YOUR_ACTIVITY until you cancel it. this is an example in Google Android Documents.


来源: stackexchange

问:
Universal Linking with Firebase and Ionic
Additional Findings (After Initial Post)

I used this site https://limitless-sierra-4673.herokuapp.com/ to validate the link. Got an error about application/pkcs7-mime. Not sure how to change this with Firebase Dynamic Links

Im trying to set up universal linking with Firebase's dynamic links.

1. Firebase Setup

I've set up the app with Firebase and I have the link: https://e2x6f.app.goo.gl.

When I open the link I get a 400 Error but If I go to https://e2x6f.app.goo.gl/apple-app-site-association I get this:

```<code>{"applinks":
    {
        "apps": [],
        "details": [{
           "appID": "8CK4RLPU2T.com.turnmusicapp.15499",
           "paths": ["/*"]
        }]
    }
}
</code>```

So I think its ok. I've checked to make sure all the information is correct.

One problem is, when I use app's link to check search validation it also returns a 400 error - not sure if this is ok or not.

2. Xcode Setup

Anyways, I enabled Associative Domains on my app:

Then under "Info" -> URL Types I added:

3. Ionic Setup

Here is my Ionic info:

```<code>global packages:

@ionic/cli-utils : 1.4.0
Ionic CLI        : 3.4.0

System:

Node       : v8.1.2
OS         : macOS Sierra
Xcode      : Xcode 8.3.3 Build version 8E3004b
ios-deploy : 1.9.1
ios-sim    : not installed
npm        : 5.0.4
</code>```

So I installed the Deeplinks package and have that all setup. I know it's working because I can use links like turn://home in the Safari browser and it will take me to my app. I'm not sure if I need to do anything else here. I've updated the widget field in my config.xml file to this:

```<code><widget id="com.turnmusicapp.15499" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
</code>```

Does the id field need to include my app prefix?

Result

So I'm running my app with ionic cordova run ios --livereload, I type the message into Safari and It takes me to a 400 error page. I've tried sending the link as an iMessage and that does the same thing.

Thanks for the help!

答:
You have a few misconceptions — let's clear them up in order:

The https://limitless-sierra-4673.herokuapp.com/ validator is outdated — application/pkcs7-mime hasn't been required for years. Check Apple's official docs and you'll see application/json has been the requirement since iOS 9. Dynamic Links certainly won't have any configuration issues on the server side so you really don't even need to check this part, but a more updated validator is available here if you want it (yes, https://e2x6f.app.goo.gl validates perfectly).

The URL https://e2x6f.app.goo.gl is not a Dynamic Link; it's simply your link base domain. Real links will look like https://e2x6f.app.goo.gl/A97Q (short version) or https://e2x6f.app.goo.gl/?link=https://example.com/path/to/app/content&ibi=com.turnmusicapp.15499&ius=turnmusicapp&ad=1&isi=1121012049&ifl=https://example.com&apn=com.turnmusicapp.15499&al=https://example.com&at=affiliate_token&ct=campaign_text (full length). While a 400 error for the base domain is lame UX, it's expected. You need to actually create some links.

The Apple tool is the "App Search API Validation Tool", not the "Universal Links Validation Tool" (which doesn't exist from Apple). The results from this tool have no connection to whether Universal Links work — it's checking something completely different.

There is no official Dynamic Links package for Ionic, and the Deeplinks package is not designed to support it. You're off the edge of the map trying to get these working together. You might look at this new community plugin.

Alternatively, take a look at Branch.io (full disclosure: I'm on the Branch team). We do everything Dynamic Links does plus far more, and there is an actively-developed Ionic module that will handle all of this for you.

ContentLicense: CC BY-SA 3.0

Body:
Additional Findings (After Initial Post)

I used this site https://limitless-sierra-4673.herokuapp.com/ to validate the link. Got an error about application/pkcs7-mime. Not sure how to change this with Firebase Dynamic Links

Im trying to set up universal linking with Firebase's dynamic links.

1. Firebase Setup

I've set up the app with Firebase and I have the link: https://e2x6f.app.goo.gl.

When I open the link I get a 400 Error but If I go to https://e2x6f.app.goo.gl/apple-app-site-association I get this:

{"applinks":
    {
        "apps": [],
        "details": [{
           "appID": "8CK4RLPU2T.com.turnmusicapp.15499",
           "paths": ["/*"]
        }]
    }
}

So I think its ok. I've checked to make sure all the information is correct.

One problem is, when I use app's link to check search validation it also returns a 400 error - not sure if this is ok or not.

2. Xcode Setup

Anyways, I enabled Associative Domains on my app:

Then under "Info" -> URL Types I added:

3. Ionic Setup

Here is my Ionic info:

global packages:

@ionic/cli-utils : 1.4.0
Ionic CLI        : 3.4.0

System:

Node       : v8.1.2
OS         : macOS Sierra
Xcode      : Xcode 8.3.3 Build version 8E3004b
ios-deploy : 1.9.1
ios-sim    : not installed
npm        : 5.0.4

So I installed the Deeplinks package and have that all setup. I know it's working because I can use links like turn://home in the Safari browser and it will take me to my app. I'm not sure if I need to do anything else here. I've updated the widget field in my config.xml file to this:

<widget id="com.turnmusicapp.15499" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

Does the id field need to include my app prefix?

Result

So I'm running my app with ionic cordova run ios --livereload, I type the message into Safari and It takes me to a 400 error page. I've tried sending the link as an iMessage and that does the same thing.

Thanks for the help!


问:
Determine port in asp.net core
I want to make some microservices with asp.net core (Web Api)
For service discovery I want use Consul where I must register the services via the HTTP API including IP and port.

My question is:
How can I know which port is used within in a service? Is there a way to determine the used port via code?

答: Yeah, Use HttpContext.Connection.LocalPort to get the local port that the server is listening on.

Title: Determine port in asp.net core


问:
How to close Files.write
I am to attempting to create directory and write data into that file. I am trying to use java nio to write file for more efficiently. My doubt is how to close it after write it below is my code. Please advice me.

And is this correct way to create directory and write large data files [200 kb].

```<code>    java.nio.file.Path path = java.nio.file.Paths.get(filePath);

    try {
        if (!java.nio.file.Files.exists(path)) {
            java.nio.file.Files.createDirectories(path.getParent());
            path = java.nio.file.Files.createFile(path);
            path = java.nio.file.Files.write(path, data.getBytes());
        } else {
            java.nio.file.Files.write(path, data.getBytes("utf-8"),
                    java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
</code>```

答:
The Files.write(...) method "...ensures that the file is closed when all bytes have been written ..", see Java SE 8 Doc

For writing data into a file see Reading, Writing, and Creating Files

ContentLicense: CC BY-SA 4.0

Title: How to close Files.write

Body:
I am to attempting to create directory and write data into that file. I am trying to use java nio to write file for more efficiently. My doubt is how to close it after write it below is my code. Please advice me.

And is this correct way to create directory and write large data files [200 kb].

    java.nio.file.Path path = java.nio.file.Paths.get(filePath);

    try {
        if (!java.nio.file.Files.exists(path)) {
            java.nio.file.Files.createDirectories(path.getParent());
            path = java.nio.file.Files.createFile(path);
            path = java.nio.file.Files.write(path, data.getBytes());
        } else {
            java.nio.file.Files.write(path, data.getBytes("utf-8"),
                    java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }


问:
How can I add methods to a class at runtime in Smalltalk?
I'm building a Smalltalk API to an XML-based web service. The XML service is so regular that, rather than write the methods by hand, I figured I'd just override #doesNotUnderstand: to dynamically add methods via MyApi class>>compile:, then call all the methods once in a workspace, then remove the DNU and have my nice API.

This works great, but passing a giant string to #compile: just feels really wrong to me; in Python and other languages, I'd be able to attach a nicely syntax-checked lambda to a class to achieve a similar effect in a safer manner. E.g.:

```<code>def himaker(name):
    def hello(self, times):
        for x in xrange(times):
            print "Hi, %s!" % name
    return hello
class C(object): pass
C.bob = himaker('Bob')
C.jerry = himaker('Jerry')
a = C()
a.bob(5)
</code>```

versus

```<code>SomeObject>>addHello: name
    | source methodName |
    methodName := 'sayHello', name, 'Times:'.
    source := String streamContents: [ :s |
         s nextPutAll: methodName, ' count'.
         s nextPut: Character cr.
         s nextPut: Character tab.
         s nextPutAll: 'count timesRepeat: [ Transcript show: ''Hi, ', name, '!'' ].' ]
    SomeObject class compile: source
</code>```

Surely there must be something as clean as the Python version?

答:
I would use block:

```<code>himaker := [:name | [:n | n timesRepeat: [Transcript show: 'Hi , ', name, '!']]]
hibob = himaker value: 'bob'.
hialice = himaker value: 'alice'.
hialice value: 2
</code>```

You can still make himaker a method

```<code>himaker: name
    ^[:n | n timesRepeat: [Transcript show: 'Hi, ', name, '!']]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm building a Smalltalk API to an XML-based web service. The XML service is so regular that, rather than write the methods by hand, I figured I'd just override #doesNotUnderstand: to dynamically add methods via MyApi class>>compile:, then call all the methods once in a workspace, then remove the DNU and have my nice API.

This works great, but passing a giant string to #compile: just feels really wrong to me; in Python and other languages, I'd be able to attach a nicely syntax-checked lambda to a class to achieve a similar effect in a safer manner. E.g.:

def himaker(name):
    def hello(self, times):
        for x in xrange(times):
            print "Hi, %s!" % name
    return hello
class C(object): pass
C.bob = himaker('Bob')
C.jerry = himaker('Jerry')
a = C()
a.bob(5)

versus

SomeObject>>addHello: name
    | source methodName |
    methodName := 'sayHello', name, 'Times:'.
    source := String streamContents: [ :s |
         s nextPutAll: methodName, ' count'.
         s nextPut: Character cr.
         s nextPut: Character tab.
         s nextPutAll: 'count timesRepeat: [ Transcript show: ''Hi, ', name, '!'' ].' ]
    SomeObject class compile: source

Surely there must be something as clean as the Python version?

Body:
I would use block:

himaker := [:name | [:n | n timesRepeat: [Transcript show: 'Hi , ', name, '!']]]
hibob = himaker value: 'bob'.
hialice = himaker value: 'alice'.
hialice value: 2

You can still make himaker a method

himaker: name
    ^[:n | n timesRepeat: [Transcript show: 'Hi, ', name, '!']]


问:
can you explain why my class will not return to main program?
so the assignment I have is as follows.

The challenge...
The program is supposed to ask for the number of units sold and compute the total cost of the purchase.
I am also supposed to include a input validation so that the number of units is greater than 0.
Package price is $99, Quantity discounts are:
10-19 20%
20-49 30%
50-99 40%
100 or more 50%

I have my class demo that I have to use to test my code,

```<code>    package Chapter4;
    import java.text.DecimalFormat;
    import java.util.Scanner;
    public class SoftwareSalesDemo {

public static void main(String[] args) {
    int units; // To hold units sold

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Get the units sold.
    System.out.print("Enter the units sold: ");
    units = keyboard.nextInt();

    // Create a SoftwareSales object.
    SoftwareSales sales = new SoftwareSales(units);

    // Display purchase info.
    DecimalFormat dollar = new DecimalFormat("#,##0.00");
    System.out.println("Units sold: " + sales.getUnitsSold());
    System.out.println("Discount: $" + dollar.format(sales.getDiscount()));
    System.out.println("Cost: $" + dollar.format(sales.getCost()));

}

}
</code>```

The following is the class that I wrote this is what I need help with.

```<code>package Chapter4;

/*
 * Software sales class
 *
 * Eric Goldberg
 *
 * Calculate the total cost of units sold */

public class SoftwareSales {

//fields
private int UnitsSold;
private double Discount;
private double Cost;
private double UnitCost=99.00;

public SoftwareSales (int uni)
{
    UnitsSold = uni;

}

public Discount(double dis)
{
    Discount = dis;

    if(UnitsSold >=10 && UnitsSold<=19) {
        Discount = .20;
    }

    if(UnitsSold >= 20 && UnitsSold<=49) {
        Discount = .30;
    }

    if (UnitsSold >= 50 && UnitsSold <= 99) {
        Discount = .40;
    }

    if (UnitsSold >= 100) {
        Discount = .50;
    }

} //end of discount

public double UnitCost() {
    return UnitCost=99.00;
}

public  void setCost(double cost) {
    Cost = Discount*UnitsSold;
}

//return the discount amount.
public double getDiscount()
{
    return Discount;
}

//return unitssold.
public int getUnitsSold() {
    return UnitsSold;
}

//return cost
public double getCost() {
    return Cost;
}

}
</code>```

答:
You need to correct the cost and discount calculation. I am assuming you need total cost and total discount. You can make input (no of units) validation as fancy as you want. (like read string and then parseInt). For now, i am assuming that input will be an integer and until user enters integer >0, i keep on asking.

SoftwareSalesDemo.java

```<code>package Chapter4;

import java.text.DecimalFormat;
import java.util.Scanner;

public class SoftwareSalesDemo {

    public static void main(String[] args) {
        // To hold units sold
        int units;

        // Display purchase info.
        DecimalFormat dollar = new DecimalFormat("#,##0.00");

        // Get the units sold.
        System.out.print("Enter the units sold: ");

        // Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(System.in);
        units = keyboard.nextInt();

        while (units <= 0) {
            System.out.println("Please enter valid no. of units (>0)");
            units = keyboard.nextInt();
        }
        // Create a SoftwareSales object.
        SoftwareSales sales = new SoftwareSales(units);
        System.out.println("Units sold     : " + sales.getUnitsSold());
        System.out.println("Total Discount : $" + dollar.format(sales.getDiscount()));
        System.out.println("Total Cost     : $" + dollar.format(sales.getCost()));

    }
}
</code>```

SoftwareSales.java

```<code>package Chapter4;

/*
 * Software sales class
 *
 * Eric Goldberg
 *
 * Calculate the total cost of units sold */

public class SoftwareSales {

    // fields
    private int unitsSold;
    private double discount;
    private double cost;
    private double unitCost = 99.00;

    public SoftwareSales(int units) {
        this.unitsSold = units;
        setDiscount();
        setCost();
    }

    // set discount based on no. of units sold
    private void setDiscount() {
        if (unitsSold >= 10 && unitsSold <= 19) {
            discount = .20;
        }

        if (unitsSold >= 20 && unitsSold <= 49) {
            discount = .30;
        }

        if (unitsSold >= 50 && unitsSold <= 99) {
            discount = .40;
        }

        if (unitsSold >= 100) {
            discount = .50;
        }
    } // end of discount

    // return per unit cost
    private double getUnitCost() {
        return unitCost;
    }

    // calculate total cost
    private void setCost() {
        cost = unitsSold * (getUnitCost() * (1 - discount));
    }

    // return the discount amount.
    public double getDiscount() {
        return ((discount * getUnitCost()) * unitsSold);
    }

    // return unitsSold.
    public int getUnitsSold() {
        return unitsSold;
    }

    // return total cost
    public double getCost() {
        return cost;
    }
}
</code>```

Sample Runs

```<code>Enter the units sold: 10
Units sold     : 10
Total Discount : $198.00
Total Cost     : $792.00

Enter the units sold: 50
Units sold     : 50
Total Discount : $1,980.00
Total Cost     : $2,970.00

Enter the units sold: 100
Units sold     : 100
Total Discount : $4,950.00
Total Cost     : $4,950.00
</code>```

Body:
so the assignment I have is as follows.

The challenge...
The program is supposed to ask for the number of units sold and compute the total cost of the purchase.
I am also supposed to include a input validation so that the number of units is greater than 0.
Package price is $99, Quantity discounts are:
10-19 20%
20-49 30%
50-99 40%
100 or more 50%

I have my class demo that I have to use to test my code,

    package Chapter4;
    import java.text.DecimalFormat;
    import java.util.Scanner;
    public class SoftwareSalesDemo {

public static void main(String[] args) {
    int units; // To hold units sold

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Get the units sold.
    System.out.print("Enter the units sold: ");
    units = keyboard.nextInt();

    // Create a SoftwareSales object.
    SoftwareSales sales = new SoftwareSales(units);

    // Display purchase info.
    DecimalFormat dollar = new DecimalFormat("#,##0.00");
    System.out.println("Units sold: " + sales.getUnitsSold());
    System.out.println("Discount: $" + dollar.format(sales.getDiscount()));
    System.out.println("Cost: $" + dollar.format(sales.getCost()));

}

}

The following is the class that I wrote this is what I need help with.

package Chapter4;

/*
 * Software sales class
 *
 * Eric Goldberg
 *
 * Calculate the total cost of units sold */

public class SoftwareSales {

//fields
private int UnitsSold;
private double Discount;
private double Cost;
private double UnitCost=99.00;

public SoftwareSales (int uni)
{
    UnitsSold = uni;

}

public Discount(double dis)
{
    Discount = dis;

    if(UnitsSold >=10 && UnitsSold<=19) {
        Discount = .20;
    }

    if(UnitsSold >= 20 && UnitsSold<=49) {
        Discount = .30;
    }

    if (UnitsSold >= 50 && UnitsSold <= 99) {
        Discount = .40;
    }

    if (UnitsSold >= 100) {
        Discount = .50;
    }

} //end of discount

public double UnitCost() {
    return UnitCost=99.00;
}

public  void setCost(double cost) {
    Cost = Discount*UnitsSold;
}

//return the discount amount.
public double getDiscount()
{
    return Discount;
}

//return unitssold.
public int getUnitsSold() {
    return UnitsSold;
}

//return cost
public double getCost() {
    return Cost;
}

}

Body:
You need to correct the cost and discount calculation. I am assuming you need total cost and total discount. You can make input (no of units) validation as fancy as you want. (like read string and then parseInt). For now, i am assuming that input will be an integer and until user enters integer >0, i keep on asking.

SoftwareSalesDemo.java

package Chapter4;

import java.text.DecimalFormat;
import java.util.Scanner;

public class SoftwareSalesDemo {

    public static void main(String[] args) {
        // To hold units sold
        int units;

        // Display purchase info.
        DecimalFormat dollar = new DecimalFormat("#,##0.00");

        // Get the units sold.
        System.out.print("Enter the units sold: ");

        // Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(System.in);
        units = keyboard.nextInt();

        while (units <= 0) {
            System.out.println("Please enter valid no. of units (>0)");
            units = keyboard.nextInt();
        }
        // Create a SoftwareSales object.
        SoftwareSales sales = new SoftwareSales(units);
        System.out.println("Units sold     : " + sales.getUnitsSold());
        System.out.println("Total Discount : $" + dollar.format(sales.getDiscount()));
        System.out.println("Total Cost     : $" + dollar.format(sales.getCost()));

    }
}

SoftwareSales.java

package Chapter4;

/*
 * Software sales class
 *
 * Eric Goldberg
 *
 * Calculate the total cost of units sold */

public class SoftwareSales {

    // fields
    private int unitsSold;
    private double discount;
    private double cost;
    private double unitCost = 99.00;

    public SoftwareSales(int units) {
        this.unitsSold = units;
        setDiscount();
        setCost();
    }

    // set discount based on no. of units sold
    private void setDiscount() {
        if (unitsSold >= 10 && unitsSold <= 19) {
            discount = .20;
        }

        if (unitsSold >= 20 && unitsSold <= 49) {
            discount = .30;
        }

        if (unitsSold >= 50 && unitsSold <= 99) {
            discount = .40;
        }

        if (unitsSold >= 100) {
            discount = .50;
        }
    } // end of discount

    // return per unit cost
    private double getUnitCost() {
        return unitCost;
    }

    // calculate total cost
    private void setCost() {
        cost = unitsSold * (getUnitCost() * (1 - discount));
    }

    // return the discount amount.
    public double getDiscount() {
        return ((discount * getUnitCost()) * unitsSold);
    }

    // return unitsSold.
    public int getUnitsSold() {
        return unitsSold;
    }

    // return total cost
    public double getCost() {
        return cost;
    }
}

Sample Runs

Enter the units sold: 10
Units sold     : 10
Total Discount : $198.00
Total Cost     : $792.00

Enter the units sold: 50
Units sold     : 50
Total Discount : $1,980.00
Total Cost     : $2,970.00

Enter the units sold: 100
Units sold     : 100
Total Discount : $4,950.00
Total Cost     : $4,950.00


问:
'.' is not recognized as an internal or external command for relay full stack
I am trying to use relay full stack.

https://github.com/lvarayut/relay-fullstack

But I am getting an error like

```<code>'.' is not recognized as an internal or external command,
operable program or batch file
</code>```

Here is my package.json file

```<code>{
  "name": "relay-fullstack",
  "version": "1.0.0",
  "description": "Relay Fullstack, Powered by Relay Fullstack",
  "scripts": {
    "start": "nodemon --watch server/data/**/*.js --exec \"npm run update && ./node_modules/.bin/babel-node server/index.js\"",
    "update": "./node_modules/.bin/babel-node server/utils/updateSchema.js",
    "deploy": "npm run clean && cross-env NODE_ENV=production webpack --config webpack.config.js && npm run update && npm run build-server && cross-env NODE_ENV=production node ./build/index.js",
    "build-server": "cross-env NODE_ENV=production ./node_modules/.bin/babel ./server --out-dir ./build",
    "lint": "eslint --ignore-path .gitignore client server",
    "heroku-postbuild": "cross-env NODE_ENV=production webpack --config webpack.config.js && cross-env NODE_ENV=production ./node_modules/.bin/babel ./server --out-dir ./lib",
    "clean": "rm -rf build && mkdir build"
  },
  "pre-commit": "lint",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/lvarayut/relay-fullstack.git"
  },
  "engines": {
    "node": "6.6.0",
    "npm": "3.10.8"
  },
  "keywords": [
    "react",
    "relay",
    "graphql",
    "express",
    "es6",
    "es7",
    "jsx",
    "webpack",
    "babel",
    "material design lite",
    "postcss",
    "scaffolding",
    "fullstack"
  ],
  "author": "Varayut Lerdkanlayanawat",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/lvarayut/relay-fullstack/issues"
  },
  "homepage": "https://github.com/lvarayut/relay-fullstack",
  "devDependencies": {
    "eslint": "^3.8.0",
    "eslint-config-airbnb": "^12.0.0",
    "eslint-plugin-import": "^2.0.1",
    "eslint-plugin-jsx-a11y": "^2.2.3",
    "eslint-plugin-react": "^6.4.1",
    "nodemon": "^1.11.0",
    "pre-commit": "^1.1.3",
    "react-transform-catch-errors": "^1.0.2",
    "react-transform-hmr": "^1.0.4",
    "redbox-react": "^1.3.2"
  },
  "dependencies": {
    "autoprefixer": "^6.5.1",
    "babel-cli": "^6.16.0",
    "babel-core": "^6.17.0",
    "babel-eslint": "^7.0.0",
    "babel-loader": "^6.2.5",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "babel-relay-plugin": "^0.9.3",
    "chalk": "^1.1.3",
    "connect-history-api-fallback": "^1.3.0",
    "cross-env": "^3.1.3",
    "css-loader": "^0.25.0",
    "express": "^4.14.0",
    "express-graphql": "^0.5.4",
    "favicons-webpack-plugin": "0.0.7",
    "file-loader": "^0.9.0",
    "graphql": "^0.7.2",
    "graphql-relay": "^0.4.3",
    "html-webpack-plugin": "^2.22.0",
    "lodash": "^4.16.4",
    "normalize.css": "^5.0.0",
    "postcss-loader": "^1.0.0",
    "precss": "^1.4.0",
    "react": "^15.3.2",
    "react-dom": "^15.3.2",
    "react-dropdown": "^1.1.0",
    "react-mdl": "^1.7.2",
    "react-relay": "^0.9.3",
    "react-router": "^2.8.1",
    "react-router-relay": "^0.13.5",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.16.2"
  }
}
</code>```

server/utils/updateSchema.js file

```<code>/* eslint-disable no-console */
import path from 'path';
import fs from 'fs';
import { graphql } from 'graphql';
import chalk from 'chalk';
import { introspectionQuery, printSchema } from 'graphql/utilities';
import schema from '../data/schema';

const jsonFile = path.join(__dirname, '../data/schema.json');
const graphQLFile = path.join(__dirname, '../data/schema.graphql');

async function updateSchema() {
  try {
    const json = await graphql(schema, introspectionQuery);
    fs.writeFileSync(jsonFile, JSON.stringify(json, null, 2));
    fs.writeFileSync(graphQLFile, printSchema(schema));
    console.log(chalk.green('Schema has been regenerated'));
  } catch (err) {
    console.error(chalk.red(err.stack));
  }
}

// Run the function directly, if it's called from the command line
if (!module.parent) updateSchema();

export default updateSchema;
</code>```

What should I do to get relay-fullstack running?
Thanks.

答:
Error resides between:

"scripts": { "start": "nodemon --watch server/data/**/*.js --exec \"npm run update && ./node_modules/.bin/babel-node server/index.js\"", "update": "./node_modules/.bin/babel-node server/utils/updateSchema.js", "deploy": "npm run clean && cross-env NODE_ENV=production webpack --config webpack.config.js && npm run update && npm run build-server && cross-env NODE_ENV=production node ./build/index.js", "build-server": "cross-env NODE_ENV=production ./node_modules/.bin/babel ./server --out-dir ./build", "lint": "eslint --ignore-path .gitignore client server", "heroku-postbuild": "cross-env NODE_ENV=production webpack --config webpack.config.js && cross-env NODE_ENV=production ./node_modules/.bin/babel ./server --out-dir ./lib", "clean": "rm -rf build && mkdir build" }

I think you should focus on update command used in script tag( package. json)

Body:
I am trying to use relay full stack.

https://github.com/lvarayut/relay-fullstack

But I am getting an error like

'.' is not recognized as an internal or external command,
operable program or batch file

Here is my package.json file

{
  "name": "relay-fullstack",
  "version": "1.0.0",
  "description": "Relay Fullstack, Powered by Relay Fullstack",
  "scripts": {
    "start": "nodemon --watch server/data/**/*.js --exec \"npm run update && ./node_modules/.bin/babel-node server/index.js\"",
    "update": "./node_modules/.bin/babel-node server/utils/updateSchema.js",
    "deploy": "npm run clean && cross-env NODE_ENV=production webpack --config webpack.config.js && npm run update && npm run build-server && cross-env NODE_ENV=production node ./build/index.js",
    "build-server": "cross-env NODE_ENV=production ./node_modules/.bin/babel ./server --out-dir ./build",
    "lint": "eslint --ignore-path .gitignore client server",
    "heroku-postbuild": "cross-env NODE_ENV=production webpack --config webpack.config.js && cross-env NODE_ENV=production ./node_modules/.bin/babel ./server --out-dir ./lib",
    "clean": "rm -rf build && mkdir build"
  },
  "pre-commit": "lint",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/lvarayut/relay-fullstack.git"
  },
  "engines": {
    "node": "6.6.0",
    "npm": "3.10.8"
  },
  "keywords": [
    "react",
    "relay",
    "graphql",
    "express",
    "es6",
    "es7",
    "jsx",
    "webpack",
    "babel",
    "material design lite",
    "postcss",
    "scaffolding",
    "fullstack"
  ],
  "author": "Varayut Lerdkanlayanawat",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/lvarayut/relay-fullstack/issues"
  },
  "homepage": "https://github.com/lvarayut/relay-fullstack",
  "devDependencies": {
    "eslint": "^3.8.0",
    "eslint-config-airbnb": "^12.0.0",
    "eslint-plugin-import": "^2.0.1",
    "eslint-plugin-jsx-a11y": "^2.2.3",
    "eslint-plugin-react": "^6.4.1",
    "nodemon": "^1.11.0",
    "pre-commit": "^1.1.3",
    "react-transform-catch-errors": "^1.0.2",
    "react-transform-hmr": "^1.0.4",
    "redbox-react": "^1.3.2"
  },
  "dependencies": {
    "autoprefixer": "^6.5.1",
    "babel-cli": "^6.16.0",
    "babel-core": "^6.17.0",
    "babel-eslint": "^7.0.0",
    "babel-loader": "^6.2.5",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "babel-relay-plugin": "^0.9.3",
    "chalk": "^1.1.3",
    "connect-history-api-fallback": "^1.3.0",
    "cross-env": "^3.1.3",
    "css-loader": "^0.25.0",
    "express": "^4.14.0",
    "express-graphql": "^0.5.4",
    "favicons-webpack-plugin": "0.0.7",
    "file-loader": "^0.9.0",
    "graphql": "^0.7.2",
    "graphql-relay": "^0.4.3",
    "html-webpack-plugin": "^2.22.0",
    "lodash": "^4.16.4",
    "normalize.css": "^5.0.0",
    "postcss-loader": "^1.0.0",
    "precss": "^1.4.0",
    "react": "^15.3.2",
    "react-dom": "^15.3.2",
    "react-dropdown": "^1.1.0",
    "react-mdl": "^1.7.2",
    "react-relay": "^0.9.3",
    "react-router": "^2.8.1",
    "react-router-relay": "^0.13.5",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.16.2"
  }
}

server/utils/updateSchema.js file

/* eslint-disable no-console */
import path from 'path';
import fs from 'fs';
import { graphql } from 'graphql';
import chalk from 'chalk';
import { introspectionQuery, printSchema } from 'graphql/utilities';
import schema from '../data/schema';

const jsonFile = path.join(__dirname, '../data/schema.json');
const graphQLFile = path.join(__dirname, '../data/schema.graphql');

async function updateSchema() {
  try {
    const json = await graphql(schema, introspectionQuery);
    fs.writeFileSync(jsonFile, JSON.stringify(json, null, 2));
    fs.writeFileSync(graphQLFile, printSchema(schema));
    console.log(chalk.green('Schema has been regenerated'));
  } catch (err) {
    console.error(chalk.red(err.stack));
  }
}

// Run the function directly, if it's called from the command line
if (!module.parent) updateSchema();

export default updateSchema;

What should I do to get relay-fullstack running?
Thanks.


问:
Javascript clone node is not copying all values from cloned to new object
```<code><div class="container">
  <select class="btn" name="item">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">
</div>
</code>```

In this example, element selected by default in the "select" dropdown is "Alpha". I want to clone the complete node with values. If i select a different value in the dropdown and enter some text in the input box, and then clone the node, only the text box value is cloned. The value of "select" dropdown in the new object remains the default (Alpha).

Why is the behavior of cloning different for "select" vs "input"?

```<code>var parent = document.querySelector(".container");
var button = parent.querySelector(".btn");
var textbox = parent.querySelector(".desc");

  > textbox.value
  < "some random text"
  > button.value
  < "Gamma"

var cloned = parent.cloneNode(true);
var childButton = cloned.querySelector(".btn");
var childTextbox = cloned.querySelector(".desc");

  > childTextbox.value
  < "some random text"
  > childButton.value
  < "Alpha"
</code>```

答:
Cloning a <select> does not copy the value= property on <option>s.

This happens because changing the attribute changes the state of the form control, but does not change the value of the HTML selected attribute of the element.

You can read more about it in W3 specs.

In your example, if you check the value of the parent node you will see that only that element will have the correct selected value and none of its clones.

Body:
  <select class="btn" name="item">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">

In this example, element selected by default in the "select" dropdown is "Alpha". I want to clone the complete node with values. If i select a different value in the dropdown and enter some text in the input box, and then clone the node, only the text box value is cloned. The value of "select" dropdown in the new object remains the default (Alpha).

Why is the behavior of cloning different for "select" vs "input"?

var parent = document.querySelector(".container");
var button = parent.querySelector(".btn");
var textbox = parent.querySelector(".desc");

  > textbox.value
  < "some random text"
  > button.value
  < "Gamma"

var cloned = parent.cloneNode(true);
var childButton = cloned.querySelector(".btn");
var childTextbox = cloned.querySelector(".desc");

  > childTextbox.value
  < "some random text"
  > childButton.value
  < "Alpha"


问:
CASE, WHEN, THEN on UPDATE
I have this issue where if there is no record in copy_on_write.id then the UPDATE listings SET images = (SELECT images FROM new_vals) runs and wipes out listings.images with nothing.

So, I am trying to use a condition to only run the UPDATE listings if copy_on_write.images exist.

right now I get:

```<code>psql:queries/copy-to-source.sh:20: ERROR:  syntax error at or near "CASE"
LINE 10:       CASE WHEN images <>
</code>```

```<code>WITH
  new_vals AS (
    SELECT *
    FROM copy_on_write
    WHERE copy_on_write.posted_by = 102550922::text
      AND copy_on_write.id = 4
  ),

  updates AS (
    SELECT images FROM new_vals,
      CASE WHEN images <> ''
        THEN UPDATE listings SET images = (SELECT images FROM new_vals)
      END
  )
SELECT internal_id FROM new_vals
</code>```

答:
You can use updates CTE like this:

```<code>...
updates AS (
    UPDATE listings SET
    images = new_vals.images
    FROM new_vals
    WHERE new_vals.images <> ''
)
....
</code>```

Note, that:

Your new_vals CTE  should always return maximum one record, otherwise this won't works correct.

Also this not updates listings table, if  new_vals returns images column, but it is empty string (or null). If in such cases you need run update anyway, then remove WHERE new_vals.images <> '' at all.

And also, this statement will update all listings.images records. Do you really want this?

Title: CASE, WHEN, THEN on UPDATE

Body:
I have this issue where if there is no record in copy_on_write.id then the UPDATE listings SET images = (SELECT images FROM new_vals) runs and wipes out listings.images with nothing.

So, I am trying to use a condition to only run the UPDATE listings if copy_on_write.images exist.

right now I get:

psql:queries/copy-to-source.sh:20: ERROR:  syntax error at or near "CASE"
LINE 10:       CASE WHEN images <>

WITH
  new_vals AS (
    SELECT *
    FROM copy_on_write
    WHERE copy_on_write.posted_by = 102550922::text
      AND copy_on_write.id = 4
  ),

  updates AS (
    SELECT images FROM new_vals,
      CASE WHEN images <> ''
        THEN UPDATE listings SET images = (SELECT images FROM new_vals)
      END
  )
SELECT internal_id FROM new_vals

Body:
You can use updates CTE like this:

...
updates AS (
    UPDATE listings SET
    images = new_vals.images
    FROM new_vals
    WHERE new_vals.images <> ''
)
....

Note, that:

Your new_vals CTE  should always return maximum one record, otherwise this won't works correct.

Also this not updates listings table, if  new_vals returns images column, but it is empty string (or null). If in such cases you need run update anyway, then remove WHERE new_vals.images <> '' at all.

And also, this statement will update all listings.images records. Do you really want this?


问:
How is one byte read and returned as an int by read function in InputStream in java?
The read() function reads one byte at a time and the return type of this function is int. I want to know what happens under the hood so that byte is returned as an int. I have no knowledge of bitwise operators so can anyone answer in a way that i grasp it readily.</p>

答:
Under the hood, if the end of stream is reached, read() returns -1. Otherwise, it returns the byte value as an int (the value is thus between 0 and 255).

After you've verified that the result is not -1, you can get the signed byte value using

```<code>byte b = (byte) intValue;
</code>```

That will just keep the 8 rightmost bits of the int, and the 8th bit from the right is used as the sign bit, thus leading to a signed value, between -128 and 127.

If the method returned a byte, there would be no way, other than throwing an exception, to signal that the end of the stream has been reached.

Body:
Under the hood, if the end of stream is reached, read() returns -1. Otherwise, it returns the byte value as an int (the value is thus between 0 and 255).

After you've verified that the result is not -1, you can get the signed byte value using

byte b = (byte) intValue;

That will just keep the 8 rightmost bits of the int, and the 8th bit from the right is used as the sign bit, thus leading to a signed value, between -128 and 127.

If the method returned a byte, there would be no way, other than throwing an exception, to signal that the end of the stream has been reached.


问:
trouble creating table using foreign key
```<code>create table department
(
dept_name varchar(20),
building varchar(20),
budget numeric(12, 2),
primary key(dept_name)
);
</code>```

This is table that i created before...

now i am writing this:

```<code>create table course
(
course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2, 0),
primary key(course_id),
foreign key (dept_name) references department
);
</code>```

an it shows :

ERROR 1005 (HY000): Can't create table 'satyarth.course' (errno: 150)

答:
Add the reference table field name PFB</p>

```<code>create table course(course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2, 0),
primary key(course_id),
FOREIGN KEY (`dept_name`) REFERENCES `department` (`dept_name`)
);
</code>```

Body:
create table department
(
dept_name varchar(20),
building varchar(20),
budget numeric(12, 2),
primary key(dept_name)
);

This is table that i created before...

now i am writing this:

create table course
(
course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2, 0),
primary key(course_id),
foreign key (dept_name) references department
);

an it shows :

ERROR 1005 (HY000): Can't create table 'satyarth.course' (errno: 150)

Body:
Add the reference table field name PFB

create table course(course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2, 0),
primary key(course_id),
FOREIGN KEY (`dept_name`) REFERENCES `department` (`dept_name`)
);


问:
WordPress Site Having Fatal Error in Root View
I have running WordPress Site but now a error occurs when I login to Admin Panel of WordPress and site is also not live now. A 'Fatal Error' is showing:

```<code>Fatal error: Cannot redeclare class WP_Theme_Handler_Checker in /home/niteshvyas84/public_html/shreejeeexcellency.restaurant/wp-content/themes/resca/inc/theme-checker.php on line 4
</code>```

Does anyone know how to fix this or do I have to uninstall WordPress and start from scratch?

答:
Try opening theme-checker.php file and then wrap the class declaration code with the class_exists() function, something like:

```<code>if ( !class_exists( 'WP_Theme_Handler_Checker' ) {
//The existing class declaration
}
</code>```

Body:
I have running WordPress Site but now a error occurs when I login to Admin Panel of WordPress and site is also not live now. A 'Fatal Error' is showing:

Fatal error: Cannot redeclare class WP_Theme_Handler_Checker in /home/niteshvyas84/public_html/shreejeeexcellency.restaurant/wp-content/themes/resca/inc/theme-checker.php on line 4

Does anyone know how to fix this or do I have to uninstall WordPress and start from scratch?

Body:
Try opening theme-checker.php file and then wrap the class declaration code with the class_exists() function, something like:

if ( !class_exists( 'WP_Theme_Handler_Checker' ) {
//The existing class declaration
}


问:
Swiperefreshlayout not refreshing for layouts
swiperefreshlayout not working with diffrent view. I have created main layout and included a layout in it as shown in code.</p>

```<code> <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/toolbar">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_post_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                >

            </android.support.v7.widget.RecyclerView>

            <include layout="@layout/layout_util" />
        </RelativeLayout>
    </android.support.v4.widget.SwipeRefreshLayout>
</code>```

答:
SwipeRefreshLayout only supports a single ListView or GridView child. Official src

So you can try SwipeRefreshMultipleViews

Edited:

First create on Custom Class for MultiSwipeRefreshLayout

```<code>public class MultiSwipeRefreshLayout extends SwipeRefreshLayout {

    private View[] mSwipeableChildren;

    public MultiSwipeRefreshLayout(Context context) {
        super(context);
    }

    public MultiSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Set the children which can trigger a refresh by swiping down when they are visible. These
     * views need to be a descendant of this view.
     */
    public void setSwipeableChildren(final int... ids) {
        assert ids != null;

        // Iterate through the ids and find the Views
        mSwipeableChildren = new View[ids.length];
        for (int i = 0; i < ids.length; i++) {
            mSwipeableChildren[i] = findViewById(ids[i]);
        }
    }

    // BEGIN_INCLUDE(can_child_scroll_up)

    /**
     * This method controls when the swipe-to-refresh gesture is triggered. By returning false here
     * we are signifying that the view is in a state where a refresh gesture can start.
     * <p>
     * <p>As {@link SwipeRefreshLayout} only supports one direct child by
     * default, we need to manually iterate through our swipeable children to see if any are in a
     * state to trigger the gesture. If so we return false to start the gesture.
     */
    @Override
    public boolean canChildScrollUp() {
        if (mSwipeableChildren != null && mSwipeableChildren.length > 0) {
            // Iterate through the scrollable children and check if any of them can not scroll up
            for (View view : mSwipeableChildren) {
                if (view != null && view.isShown() && !canViewScrollUp(view)) {
                    // If the view is shown, and can not scroll upwards, return false and start the
                    // gesture.
                    return false;
                }
            }
        }
        return true;
    }
    // END_INCLUDE(can_child_scroll_up)

    // BEGIN_INCLUDE(can_view_scroll_up)

    /**
     * Utility method to check whether a {@link View} can scroll up from it's current position.
     * Handles platform version differences, providing backwards compatible functionality where
     * needed.
     */
    private static boolean canViewScrollUp(View view) {
        if (android.os.Build.VERSION.SDK_INT >= 14) {
            // For ICS and above we can call canScrollVertically() to determine this
            return ViewCompat.canScrollVertically(view, -1);
        } else {
            if (view instanceof AbsListView) {
                // Pre-ICS we need to manually check the first visible item and the child view's top
                // value
                final AbsListView listView = (AbsListView) view;
                return listView.getChildCount() > 0 &&
                        (listView.getFirstVisiblePosition() > 0
                                || listView.getChildAt(0).getTop() < listView.getPaddingTop());
            } else {
                // For all other view types we just check the getScrollY() value
                return view.getScrollY() > 0;
            }
        }
    }
    // END_INCLUDE(can_view_scroll_up)
}
</code>```

then change your layout like this,

```<code><?xml version="1.0" encoding="utf-8"?>
<in.muthu.stackoverflow.ui.widget.MultiSwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swiperefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <GridView
                android:id="@+id/contact_screen_list"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:numColumns="2" />

            <TextView
                android:id="@android:id/empty"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/empty_text"
                android:layout_gravity="center"/>

        </FrameLayout>

    </FrameLayout>
</in.muthu.stackoverflow.ui.widget.MultiSwipeRefreshLayout>
</code>```

Note: change in.muthu.stackoverflow.ui.widget with your
  MultiSwipeRefreshLayout with your package

And in your java code you should do this,

```<code>mSwipeRefreshLayout = (MultiSwipeRefreshLayout) view.findViewById(R.id.swiperefresh);

mSwipeRefreshLayout.setSwipeableChildren(R.id.contact_screen_list);
</code>```

Body:
swiperefreshlayout not working with diffrent view. I have created main layout and included a layout in it as shown in code.

 <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/toolbar">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/rv_post_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                >

            </android.support.v7.widget.RecyclerView>

            <include layout="@layout/layout_util" />
        </RelativeLayout>
    </android.support.v4.widget.SwipeRefreshLayout>

Body:
SwipeRefreshLayout only supports a single ListView or GridView child. Official src

So you can try SwipeRefreshMultipleViews

Edited:

First create on Custom Class for MultiSwipeRefreshLayout

public class MultiSwipeRefreshLayout extends SwipeRefreshLayout {

    private View[] mSwipeableChildren;

    public MultiSwipeRefreshLayout(Context context) {
        super(context);
    }

    public MultiSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Set the children which can trigger a refresh by swiping down when they are visible. These
     * views need to be a descendant of this view.
     */
    public void setSwipeableChildren(final int... ids) {
        assert ids != null;

        // Iterate through the ids and find the Views
        mSwipeableChildren = new View[ids.length];
        for (int i = 0; i < ids.length; i++) {
            mSwipeableChildren[i] = findViewById(ids[i]);
        }
    }

    // BEGIN_INCLUDE(can_child_scroll_up)

    /**
     * This method controls when the swipe-to-refresh gesture is triggered. By returning false here
     * we are signifying that the view is in a state where a refresh gesture can start.
     * <p>
     * <p>As {@link SwipeRefreshLayout} only supports one direct child by
     * default, we need to manually iterate through our swipeable children to see if any are in a
     * state to trigger the gesture. If so we return false to start the gesture.
     */
    @Override
    public boolean canChildScrollUp() {
        if (mSwipeableChildren != null && mSwipeableChildren.length > 0) {
            // Iterate through the scrollable children and check if any of them can not scroll up
            for (View view : mSwipeableChildren) {
                if (view != null && view.isShown() && !canViewScrollUp(view)) {
                    // If the view is shown, and can not scroll upwards, return false and start the
                    // gesture.
                    return false;
                }
            }
        }
        return true;
    }
    // END_INCLUDE(can_child_scroll_up)

    // BEGIN_INCLUDE(can_view_scroll_up)

    /**
     * Utility method to check whether a {@link View} can scroll up from it's current position.
     * Handles platform version differences, providing backwards compatible functionality where
     * needed.
     */
    private static boolean canViewScrollUp(View view) {
        if (android.os.Build.VERSION.SDK_INT >= 14) {
            // For ICS and above we can call canScrollVertically() to determine this
            return ViewCompat.canScrollVertically(view, -1);
        } else {
            if (view instanceof AbsListView) {
                // Pre-ICS we need to manually check the first visible item and the child view's top
                // value
                final AbsListView listView = (AbsListView) view;
                return listView.getChildCount() > 0 &&
                        (listView.getFirstVisiblePosition() > 0
                                || listView.getChildAt(0).getTop() < listView.getPaddingTop());
            } else {
                // For all other view types we just check the getScrollY() value
                return view.getScrollY() > 0;
            }
        }
    }
    // END_INCLUDE(can_view_scroll_up)
}

then change your layout like this,

<?xml version="1.0" encoding="utf-8"?>
<in.muthu.stackoverflow.ui.widget.MultiSwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swiperefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <GridView
                android:id="@+id/contact_screen_list"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:numColumns="2" />

            <TextView
                android:id="@android:id/empty"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/empty_text"
                android:layout_gravity="center"/>

        </FrameLayout>

    </FrameLayout>
</in.muthu.stackoverflow.ui.widget.MultiSwipeRefreshLayout>

Note: change in.muthu.stackoverflow.ui.widget with your
  MultiSwipeRefreshLayout with your package

And in your java code you should do this,

mSwipeRefreshLayout = (MultiSwipeRefreshLayout) view.findViewById(R.id.swiperefresh);

mSwipeRefreshLayout.setSwipeableChildren(R.id.contact_screen_list);


问:
Unable to Restore Graph
Problem:

Attempting to restore meta_graph via tf.train.import_meta_graph("saved_models/model.meta") gives the following error:

```<code>InvalidArgumentError (see above for traceback): Shape [-1] has negative dimensions
     [[Node: Placeholder_2 = Placeholder[dtype=DT_INT32, shape=[?], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

The shapes of placeholder and the data passed are as follows:
    placeholder: (?, ?, 50)
    data: (1, 2, 50)

Code Involved:

Placeholder involved: self.x_placeholder_input = tf.placeholder(tf.float32, shape=[None, None, n_inputs])

The other placeholder (label): self.y_placeholder_label = tf.placeholder(tf.int32, shape=[None, self.num_of_classes])

Predict method:

```<code>def predict(self):
    with tf.name_scope("predict"):
        with tf.Session(graph=tf.Graph()) as sess:
            saver = tf.train.import_meta_graph("saved_models/model.meta")
            saver.restore(sess, "saved_models/model")

            graph = tf.get_default_graph()
            output = graph.get_tensor_by_name("optimize/cal_loss/model_network/model_network_NN_network/output/BiasAdd:0")
            x_placeholder = graph.get_tensor_by_name("Placeholder:0")
            print x_placeholder.shape
            print np.array(self.data_x).shape
            print sess.run(output, feed_dict={x_placeholder: self.data_x})
</code>```

Train Method:

```<code> def train(self):
        writer = writer = tf.summary.FileWriter("mygraph/logs", tf.get_default_graph())

        num_of_epoch = 10
        with tf.Session() as sess:
            for epoch in range(num_of_epoch):
                # initialise all variables
                optimize = self.optimize
                sess.run(tf.global_variables_initializer())

                sess.run(optimize,
                         feed_dict={self.x_placeholder_input: np.array(self.data_x),
                                    self.y_placeholder_label: np.array(self.data_y),
                                    self.sq_placeholder_seq_length: np.array(self.seq_length)})

                if num_of_epoch % 10 == 0:
                    # Create Saver to save model
                    print "Cycle " + str(epoch) + " out of " + str(num_of_epoch) + " done"
                    saver = tf.train.Saver()
                    location = saver.save(sess, "saved_models/model")
                    print "Model saved to : " + str(location)
</code>```

Question: Is the problem due to placeholder having two None when defining it's shape? It is fine when training though.

**Full Code (if it helps): **
(https://gist.github.com/duemaster/660208e6cd7856af2522c2efa67911da)

答: In my experience you are getting this error because you are not feeding the value of that placeholder in the restored model. You'd normally expect to get the error "you must feed the value for placeholder XX" when you forget to feed it, but I've noticed that when placeholders have None in their shape vector (with restored models), the error would be the one you are getting about negative dimensions. I've got this error even with 1 None in the placeholder shape, and properly feeding its value solved the problem.

Title: Unable to Restore Graph

Body:
Problem:

Attempting to restore meta_graph via tf.train.import_meta_graph("saved_models/model.meta") gives the following error:

InvalidArgumentError (see above for traceback): Shape [-1] has negative dimensions
     [[Node: Placeholder_2 = Placeholder[dtype=DT_INT32, shape=[?], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

The shapes of placeholder and the data passed are as follows:
    placeholder: (?, ?, 50)
    data: (1, 2, 50)

Code Involved:

Placeholder involved: self.x_placeholder_input = tf.placeholder(tf.float32, shape=[None, None, n_inputs])

The other placeholder (label): self.y_placeholder_label = tf.placeholder(tf.int32, shape=[None, self.num_of_classes])

Predict method:

def predict(self):
    with tf.name_scope("predict"):
        with tf.Session(graph=tf.Graph()) as sess:
            saver = tf.train.import_meta_graph("saved_models/model.meta")
            saver.restore(sess, "saved_models/model")

            graph = tf.get_default_graph()
            output = graph.get_tensor_by_name("optimize/cal_loss/model_network/model_network_NN_network/output/BiasAdd:0")
            x_placeholder = graph.get_tensor_by_name("Placeholder:0")
            print x_placeholder.shape
            print np.array(self.data_x).shape
            print sess.run(output, feed_dict={x_placeholder: self.data_x})

Train Method:

 def train(self):
        writer = writer = tf.summary.FileWriter("mygraph/logs", tf.get_default_graph())

        num_of_epoch = 10
        with tf.Session() as sess:
            for epoch in range(num_of_epoch):
                # initialise all variables
                optimize = self.optimize
                sess.run(tf.global_variables_initializer())

                sess.run(optimize,
                         feed_dict={self.x_placeholder_input: np.array(self.data_x),
                                    self.y_placeholder_label: np.array(self.data_y),
                                    self.sq_placeholder_seq_length: np.array(self.seq_length)})

                if num_of_epoch % 10 == 0:
                    # Create Saver to save model
                    print "Cycle " + str(epoch) + " out of " + str(num_of_epoch) + " done"
                    saver = tf.train.Saver()
                    location = saver.save(sess, "saved_models/model")
                    print "Model saved to : " + str(location)

Question: Is the problem due to placeholder having two None when defining it's shape? It is fine when training though.

**Full Code (if it helps): **
(https://gist.github.com/duemaster/660208e6cd7856af2522c2efa67911da)


答:
It depends on the stream implementation.  In some cases the method implementation is in native code.  In others, the logic is simple; for example, in ByteArrayInputStream the read() method does this:

```<code>public class ByteArrayInputStream extends InputStream {
    protected byte buf[];
    protected int count;
    protected int pos;

    ...

    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }
}
</code>```

In other words, the bytes are converted into integers in the range 0 to 255, like the javadoc states, and -1 is returned at the logical end-of-stream.

The logic of buf[pos++] & 0xff is as follows:

buf[pos++] is converted to an int

& 0xff converts the signed integer (-128 to +127) into an "unsigned" byte (0 to 255) represented as an integer.

Title: How is one byte read and returned as an int by read function in InputStream in java?

Body: The read() function reads one byte at a time and the return type of this function is int. I want to know what happens under the hood so that byte is returned as an int. I have no knowledge of bitwise operators so can anyone answer in a way that i grasp it readily.

Body:
It depends on the stream implementation.  In some cases the method implementation is in native code.  In others, the logic is simple; for example, in ByteArrayInputStream the read() method does this:

public class ByteArrayInputStream extends InputStream {
    protected byte buf[];
    protected int count;
    protected int pos;

    ...

    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }
}

In other words, the bytes are converted into integers in the range 0 to 255, like the javadoc states, and -1 is returned at the logical end-of-stream.

The logic of buf[pos++] & 0xff is as follows:

buf[pos++] is converted to an int

& 0xff converts the signed integer (-128 to +127) into an "unsigned" byte (0 to 255) represented as an integer.


问:
Why Am I Getting a Validation Failed Error When Setting Up a Cloud Storage Container Oracle Database Cloud Service?
I just signed up for a trial of Oracle Cloud, and am going through the tutorial for the Java Service, but to do that I have to set up the DB Cloud service. However, when I set up the Cloud Service Container I get the following error.

```<code>Error: Creation of cloud storage container, https://us1.storage.oraclecloud.com/v1/Storage–Blanks/myFirstContainer, failed: [ERROR] InvalidStorageConnection: cannot authenticate:
</code>```

I saw that some people got post it by setting a replication policy within Cloud Storage. I tried that, and it did not work.

答:
To setup the database as a service, one needs to provide a valid Oracle Storage service container, your error indicates that the container connection information is not set correctly. You may want to check whether:

the provided container path complies to the required format;

you provided the correct username/password. To verify, either use the same credentials to login to the My Services page; or construct an AUTH call to storage to see if it returns the auth token, see details here.

Body:
I just signed up for a trial of Oracle Cloud, and am going through the tutorial for the Java Service, but to do that I have to set up the DB Cloud service. However, when I set up the Cloud Service Container I get the following error.

Error: Creation of cloud storage container, https://us1.storage.oraclecloud.com/v1/Storage–Blanks/myFirstContainer, failed: [ERROR] InvalidStorageConnection: cannot authenticate:

I saw that some people got post it by setting a replication policy within Cloud Storage. I tried that, and it did not work.


问:
How to prevent more than one click on an Anchor tag button
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

```<code>$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });
</code>```

答:
you can write a function like this:

```<code>function clickOnce (element ,listener){
    element.addEventListener("click", function (event){
        listener(event);
        element.removeEventListener("click", arguments.callee);
    });
}
</code>```

jsfiddle

Body:
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });

Body:
you can write a function like this:

function clickOnce (element ,listener){
    element.addEventListener("click", function (event){
        listener(event);
        element.removeEventListener("click", arguments.callee);
    });
}

jsfiddle


问:
PHP CodeIgniter translating special characters
Is there any Helper class available for codeigniter to translate german characters to pass thme in URL?

for example

ä = ae, ü = ue, ß=ss, ö=oe

Thanks in advance.

答:
Use something like this as a helper (rough code):</p>

```<code>if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('test_method'))
{
    function test_method($var = '')
    {
        $var = str_replace('ä', 'ae', $var);
        $var = str_replace('ü', 'ue', $var);
        $var = str_replace('ß', 'ss', $var);
        $var = str_replace('ö', 'oe', $var);
        return $var;
    }
}
</code>```

Body:
Use something like this as a helper (rough code):

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('test_method'))
{
    function test_method($var = '')
    {
        $var = str_replace('ä', 'ae', $var);
        $var = str_replace('ü', 'ue', $var);
        $var = str_replace('ß', 'ss', $var);
        $var = str_replace('ö', 'oe', $var);
        return $var;
    }
}


问:
How to update-alternatives to Python 3 without breaking apt?
The other day I decided that I wanted the command python to default to firing up python3 instead of python2.

So I did this:

```<code>$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 2

$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.5 3

$ sudo update-alternatives --config python

$ sudo update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0
</code>```

And that all worked. Great! :)

```<code>$ python -V
Python 3.5.2
</code>```

But it wasn't long before I realised I had broken apt/aptitude when it comes to installing and removing python packages because apt was expecting python2 it transpired.

This is what happened.

```<code>$ sudo apt remove  python-samba
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  samba-libs
Use 'sudo apt autoremove' to remove it.
The following packages will be REMOVED:
  python-samba
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
After this operation, 5,790 kB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 187285 files and directories currently installed.)
Removing python-samba (2:4.3.11+dfsg-0ubuntu0.16.04.5) ...
  File "/usr/bin/pyclean", line 63
    except (IOError, OSError), e:
                             ^
SyntaxError: invalid syntax
dpkg: error processing package python-samba (--remove):
 subprocess installed pre-removal script returned error exit status 1
Traceback (most recent call last):
  File "/usr/bin/pycompile", line 35, in <module>
    from debpython.version import SUPPORTED, debsorted, vrepr, \
  File "/usr/share/python/debpython/version.py", line 24, in <module>
    from ConfigParser import SafeConfigParser
ImportError: No module named 'ConfigParser'
dpkg: error while cleaning up:
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 python-samba
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

Eventually I guessed it wanted python2 as the default, so I undid my changes as follows:

```<code>$ sudo update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode

Press <enter> to keep the current choice[*], or type selection number: 1

$ python -V
Python 2.7.12
</code>```

And then apt worked again

```<code>$ sudo apt remove  python-samba
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  samba-libs
Use 'sudo apt autoremove' to remove it.
The following packages will be REMOVED:
  python-samba
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 5,790 kB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 187285 files and directories currently installed.)
Removing python-samba (2:4.3.11+dfsg-0ubuntu0.16.04.5) ...
</code>```

So I have had to leave it as defaulting to python 2 but I develop in python 3 and so would like my system to default to python 3 for when I run python and idle.

Can anyone tell me how I can achieve this without breaking apt?

My system is a Raspberry Pi 3B running Ubuntu:

```<code>Linux mymachine 4.4.38-v7+ #938 SMP Thu Dec 15 15:22:21 GMT 2016 armv7l armv7l armv7l GNU/Linux
</code>```

(It's actually an arm v8)

```<code>$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.2 LTS"
</code>```

答:
Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:</p>

```<code>root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode

root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0

root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.
</code>```

Body:
The other day I decided that I wanted the command python to default to firing up python3 instead of python2.

So I did this:

$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 2

$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.5 3

$ sudo update-alternatives --config python

$ sudo update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0

And that all worked. Great! :)

$ python -V
Python 3.5.2

But it wasn't long before I realised I had broken apt/aptitude when it comes to installing and removing python packages because apt was expecting python2 it transpired.

This is what happened.

$ sudo apt remove  python-samba
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  samba-libs
Use 'sudo apt autoremove' to remove it.
The following packages will be REMOVED:
  python-samba
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
After this operation, 5,790 kB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 187285 files and directories currently installed.)
Removing python-samba (2:4.3.11+dfsg-0ubuntu0.16.04.5) ...
  File "/usr/bin/pyclean", line 63
    except (IOError, OSError), e:
                             ^
SyntaxError: invalid syntax
dpkg: error processing package python-samba (--remove):
 subprocess installed pre-removal script returned error exit status 1
Traceback (most recent call last):
  File "/usr/bin/pycompile", line 35, in <module>
    from debpython.version import SUPPORTED, debsorted, vrepr, \
  File "/usr/share/python/debpython/version.py", line 24, in <module>
    from ConfigParser import SafeConfigParser
ImportError: No module named 'ConfigParser'
dpkg: error while cleaning up:
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 python-samba
E: Sub-process /usr/bin/dpkg returned an error code (1)

Eventually I guessed it wanted python2 as the default, so I undid my changes as follows:

$ sudo update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode

Press <enter> to keep the current choice[*], or type selection number: 1

$ python -V
Python 2.7.12

And then apt worked again

$ sudo apt remove  python-samba
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  samba-libs
Use 'sudo apt autoremove' to remove it.
The following packages will be REMOVED:
  python-samba
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 5,790 kB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 187285 files and directories currently installed.)
Removing python-samba (2:4.3.11+dfsg-0ubuntu0.16.04.5) ...

So I have had to leave it as defaulting to python 2 but I develop in python 3 and so would like my system to default to python 3 for when I run python and idle.

Can anyone tell me how I can achieve this without breaking apt?

My system is a Raspberry Pi 3B running Ubuntu:

Linux mymachine 4.4.38-v7+ #938 SMP Thu Dec 15 15:22:21 GMT 2016 armv7l armv7l armv7l GNU/Linux

(It's actually an arm v8)

$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.2 LTS"

Body:
Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:

root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode

root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0

root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.


问:
PHP and MySQL Ranking
I have this table in MySQL:

```<code>id | name  | points
1  | John  | 9
2  | Bart  | 7
3  | Billy | 14
</code>```

I would like to have a table in HTML / PHP where he prints this:

```<code>Name   Points
Billy  14
John   9
Bart   7
</code>```

How can I do?

答:
Try a query like :  </p>

```<code>SELECT name, points FROM your_table ORDER BY points DESC
</code>```

Title: PHP and MySQL Ranking

Body:
I have this table in MySQL:

id | name  | points
1  | John  | 9
2  | Bart  | 7
3  | Billy | 14

I would like to have a table in HTML / PHP where he prints this:

Name   Points
Billy  14
John   9
Bart   7

How can I do?

Body:
Try a query like :

SELECT name, points FROM your_table ORDER BY points DESC


问:
Servlet not working
i wrote a basic java servlet code which is not working.
Iam using oracle12c release 2 and apache tomcat 9.0.
The below doesnot show any error but after clicking submit in html pae it loads into an empty page

MY html file is

<form method="get" action="srv" align="center">

UName	 <input type="text" name="nm">

Password	<input type="password" name="pd">

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

</form>

```
</div>
</div>
</p>

<p>MY servlet file is</p>

```import java.io.*;
 import javax.servlet.*;
import java.sql.*;
  public class select extends GenericServlet
{
Connection con;
PreparedStatement ps;
public void init() throws ServletException
{
    try

    {
    Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","C##
 1","Oracle_12");
    ps=con.prepareStatement("select * from emp where name=?");}
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
public void service(ServletRequest req,ServletResponse res) throws
  ServletException,IOException
  {
    try
    {
        String name=req.getParameter("nm");
        //String pwd=req.getParameter("pd");
        ps.setString(1,name);
        //ps.setString(2,pwd);
        ResultSet rs=ps.executeQuery();
        res.setContentType("text/html");
        PrintWriter pw=res.getWriter();
        if(rs.next())
        {
            String name1=rs.getString(1);
            String email1=rs.getString(2);
            String pws=rs.getString(3);
            pw.println(""+
            "
Hello

"+
            "

Name	Password	Email
"+
            "
"+name1+"	"+pws+"	"+email1+"

");
        }
        else
        {
            pw.println("
Try again!
   ");
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
public void destroy()
{
    try

    {con.commit();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
}
```

<p>My XML file is</p>

```  <web-app>
   <servlet>
  <servlet-name>s1</servlet-name>
  <servlet-class>select</servlet-class>
  </servlet>
  <servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/srv</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
 </web-app>
```

EDIT:This is solved by adding the OJDBC.jar file in the servlets lib folder.It has nothing to do with the errors in the program.

答:
Have you added the oracle jdbc driver in the classpath? It would be helpful if you can provide tomcat logs (or Eclipse console logs if you are running from Eclipse IDE).
It works when I ran, so no issues with the code. Check if you have added the OJDBC driver jar to your classpath..</p>

Title: Servlet not working

Body:
i wrote a basic java servlet code which is not working.
Iam using oracle12c release 2 and apache tomcat 9.0.
The below doesnot show any error but after clicking submit in html pae it loads into an empty page

MY html file is

<form method="get" action="srv" align="center">

UName	 <input type="text" name="nm">

Password	<input type="password" name="pd">

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

</form>

MY servlet file is

import java.io.*;
 import javax.servlet.*;
import java.sql.*;
  public class select extends GenericServlet
{
Connection con;
PreparedStatement ps;
public void init() throws ServletException
{
    try

    {
    Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","C##
 1","Oracle_12");
    ps=con.prepareStatement("select * from emp where name=?");}
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
public void service(ServletRequest req,ServletResponse res) throws
  ServletException,IOException
  {
    try
    {
        String name=req.getParameter("nm");
        //String pwd=req.getParameter("pd");
        ps.setString(1,name);
        //ps.setString(2,pwd);
        ResultSet rs=ps.executeQuery();
        res.setContentType("text/html");
        PrintWriter pw=res.getWriter();
        if(rs.next())
        {
            String name1=rs.getString(1);
            String email1=rs.getString(2);
            String pws=rs.getString(3);
            pw.println(""+
            "
Hello

"+
            "

Name	Password	Email
"+
            "
"+name1+"	"+pws+"	"+email1+"

");
        }
        else
        {
            pw.println("
Try again!
   ");
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
public void destroy()
{
    try

    {con.commit();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
}

My XML file is

  <web-app>
   <servlet>
  <servlet-name>s1</servlet-name>
  <servlet-class>select</servlet-class>
  </servlet>
  <servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/srv</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
 </web-app>

EDIT:This is solved by adding the OJDBC.jar file in the servlets lib folder.It has nothing to do with the errors in the program.


问:
Convert php array_sum to java
```<code>$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";  //==20
</code>```

how i can do this in java?

答: Google search says, "No". Is it not possible to loop through the array and find the sum?</p>

Title: Convert php array_sum to java

Body:
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";  //==20

how i can do this in java?


问:
Apart from maps and vectors are there any other uses of get in Clojure?
The uses that I know so far are on vectors:

```<code>(get [1 2 3 4] 2) ; => 3
</code>```

and on maps:

```<code>(get {:a "a" :b "B" :c "c"} :c) ; => "c"
</code>```

From documentation it says:

clojure.core/get ([map key] [map key not-found])

Returns the value mapped to key, not-found or nil if key not present.

答:
Apart from maps and vectors, a common use for get is on strings:

```<code>(get "Cthulhu" 2) ;; => \h
</code>```

get also works on sets and native Java(Script) arrays. One possible use in ClojureScript and JavaScript inter-op:

```<code>(def js-array (-> (js/Array 10) ;Create and fill native JS array
                  (.fill "a")
                  (.map (fn [_ i] i))))
(get js-array 3) ; => 3
</code>```

As another example, get works for looking up by item in a set:

```<code>(get #{:b :c :a} :c) ;;=> :c
</code>```

Note that it does not work with a (sorted) set and index, for example:

```<code>(get (sorted-set :b :a :c) 1) ;; throws exception
</code>```

Further, maps, vectors, and sets act as functions of their members, so you can often avoid using get altogether:

```<code>(#{:a :b :c} :b) ; => :b
({:a 1 :b 2 :c 3} :b) ; => 2
([:a :b :c] 1) ; => :b
</code>```

The advantage of using get with them is that you can provide a default value:

```<code>(get {:a :b :c} :d) ; => nil
(get {:a :b :c} :d :not-found) ; => :not-found
</code>```

See also @Thumbnail's answer to understand how get works under the hood.

Body:
The uses that I know so far are on vectors:

(get [1 2 3 4] 2) ; => 3

and on maps:

(get {:a "a" :b "B" :c "c"} :c) ; => "c"

From documentation it says:

clojure.core/get ([map key] [map key not-found])

Returns the value mapped to key, not-found or nil if key not present.

Body:
Apart from maps and vectors, a common use for get is on strings:

(get "Cthulhu" 2) ;; => \h

get also works on sets and native Java(Script) arrays. One possible use in ClojureScript and JavaScript inter-op:

(def js-array (-> (js/Array 10) ;Create and fill native JS array
                  (.fill "a")
                  (.map (fn [_ i] i))))
(get js-array 3) ; => 3

As another example, get works for looking up by item in a set:

(get #{:b :c :a} :c) ;;=> :c

Note that it does not work with a (sorted) set and index, for example:

(get (sorted-set :b :a :c) 1) ;; throws exception

Further, maps, vectors, and sets act as functions of their members, so you can often avoid using get altogether:

(#{:a :b :c} :b) ; => :b
({:a 1 :b 2 :c 3} :b) ; => 2
([:a :b :c] 1) ; => :b

The advantage of using get with them is that you can provide a default value:

(get {:a :b :c} :d) ; => nil
(get {:a :b :c} :d :not-found) ; => :not-found

See also @Thumbnail's answer to understand how get works under the hood.


问:
How can I test network errors in fetch api?
I have been successfully able to test a resolved promise on a simple application I have been working on to learn ES6 but been having issues testing the case where there may be network errors.

I wrote this test case:

```<code>import {Weather} from '../js/weather';

import chai from 'chai';
import sinon from 'sinon';
import * as chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

let assert = chai.assert;
let should = chai.should;

describe('weatherbot-1', function () {
    beforeEach(function () {
        sinon.stub(window, 'fetch');

        let data = '{"cod": "400", "message": "Nothing to geocode"}';
        let res = new window.Response(data, {
            ok: false,
            status: 400,
            headers: {
                'Content-type': 'application/json'
            }
        });

        window.fetch.returns(Promise.reject(res));
    });

    afterEach(function () {
       window.fetch.restore();
    });

    it('should ensure that promise is rejected', function () {
        let weather = new Weather(0, 0);

        return assert.isRejected(weather.getWeather(), 'Rejected');
    });
});
</code>```

The method in question is:

```<code>getWeather() {
        let headers = new Headers();

        let init = {
            method: 'GET',
            headers: headers,
            cache: 'default'
        };

        let url = 'http://localhost:8080/weather?lat=' + '' + '&lon=' + this.longitude;

        return fetch(url, init).then(function (response) {
            return response.json();
        }).catch((error) => {
            return error;
        });
}
</code>```

For testing the promise, I am using chai-as-promised & chai with mocha & sinon to stub the fetch api.

Whenever I run the test I get this error:

```<code>AssertionError: expected promise to be rejected with an error including 'Rejected' but it was fulfilled with { type: 'default',
      url: '',
      redirected: false,
      status: 400,
      ok: false,
      statusText: 'OK',
      headers:
       { append: [Function: append],
         delete: [Function: delete],
         get: [Function: get],
         getAll: [Function: getAll],
         has: [Function: has],
         set: [Function: set],
         keys: [Function: keys],
         values: [Function: values],
         entries: [Function: entries],
         forEach: [Function: forEach] },
      body: {},
      bodyUsed: false,
      clone: [Function: clone],
      arrayBuffer: [Function: arrayBuffer],
      blob: [Function: blob],
      json: [Function: json],
      text: [Function: text] }
</code>```

From what it looks like, the Promise.reject() may not be working properly. Is there any other way I could test network errors?

答: The catch clause in the getWeather function returns a new, fulfilled promise. Basically, catch takes away your ability to test for rejection. What you can do, is use a spy for the rejection handler, and then test it is called.

Body:
I have been successfully able to test a resolved promise on a simple application I have been working on to learn ES6 but been having issues testing the case where there may be network errors.

I wrote this test case:

import {Weather} from '../js/weather';

import chai from 'chai';
import sinon from 'sinon';
import * as chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

let assert = chai.assert;
let should = chai.should;

describe('weatherbot-1', function () {
    beforeEach(function () {
        sinon.stub(window, 'fetch');

        let data = '{"cod": "400", "message": "Nothing to geocode"}';
        let res = new window.Response(data, {
            ok: false,
            status: 400,
            headers: {
                'Content-type': 'application/json'
            }
        });

        window.fetch.returns(Promise.reject(res));
    });

    afterEach(function () {
       window.fetch.restore();
    });

    it('should ensure that promise is rejected', function () {
        let weather = new Weather(0, 0);

        return assert.isRejected(weather.getWeather(), 'Rejected');
    });
});

The method in question is:

getWeather() {
        let headers = new Headers();

        let init = {
            method: 'GET',
            headers: headers,
            cache: 'default'
        };

        let url = 'http://localhost:8080/weather?lat=' + '' + '&lon=' + this.longitude;

        return fetch(url, init).then(function (response) {
            return response.json();
        }).catch((error) => {
            return error;
        });
}

For testing the promise, I am using chai-as-promised & chai with mocha & sinon to stub the fetch api.

Whenever I run the test I get this error:

AssertionError: expected promise to be rejected with an error including 'Rejected' but it was fulfilled with { type: 'default',
      url: '',
      redirected: false,
      status: 400,
      ok: false,
      statusText: 'OK',
      headers:
       { append: [Function: append],
         delete: [Function: delete],
         get: [Function: get],
         getAll: [Function: getAll],
         has: [Function: has],
         set: [Function: set],
         keys: [Function: keys],
         values: [Function: values],
         entries: [Function: entries],
         forEach: [Function: forEach] },
      body: {},
      bodyUsed: false,
      clone: [Function: clone],
      arrayBuffer: [Function: arrayBuffer],
      blob: [Function: blob],
      json: [Function: json],
      text: [Function: text] }

From what it looks like, the Promise.reject() may not be working properly. Is there any other way I could test network errors?