问:
How to call a parent class method using child class reference using super keyword for object creation?
ClassA :

```<code>package assignment;

public class A {
public static void m1() {
    System.out.println("m1 method");
}
public void m2() {
    System.out.println("m2 method");
}

}
</code>```

class B:

```<code>package assignment;

public class B extends A{
public static void m1() {
System.out.println("B class m1 method");
}
public void m2() {
System.out.println("B class m2 method");}}
</code>```

How to use class A static method using class B?Is there any possible solution if any please suggest few ways.

答:
To call the method of the super class, the object should be of Super class. As :

```<code>A parent=new A();
parent.m1();
</code>```

Or

Or you can override the super class function and call the Super.Function()

```<code>@Override
public void m1() {
    super.m1();

}
</code>```

Body:
ClassA :

package assignment;

public class A {
public static void m1() {
    System.out.println("m1 method");
}
public void m2() {
    System.out.println("m2 method");
}

}

class B:

package assignment;

public class B extends A{
public static void m1() {
System.out.println("B class m1 method");
}
public void m2() {
System.out.println("B class m2 method");}}

How to use class A static method using class B?Is there any possible solution if any please suggest few ways.

Body:
To call the method of the super class, the object should be of Super class. As :

A parent=new A();
parent.m1();

Or

Or you can override the super class function and call the Super.Function()

@Override
public void m1() {
    super.m1();

}


来源: stackexchange

问:
Using .write() in Python only writes a single line
So, as an assignment from Thenewboston, I'm trying to grab a block of code from his site and write it to a file. The code grabbing part works just fine, but the writing part doesn't work:</p>

```<code>import requests
from bs4 import BeautifulSoup

def crawler(url):
    source = requests.get(url)
    source_text = source.text
    soup_obj = BeautifulSoup(source_text, "html.parser")
    for code in soup_obj.find('code'):
        codes = str(code)
        final_code = codes.replace('<br/>', '').replace('Â', '')
        print(final_code)
        fx = open('crawler_code.txt', 'w')
        fx.write(final_code)
        fx.close()

crawler('https://thenewboston.com/forum/topic.php?id=1610')
</code>```

答:
You did not really mentioned what was the issue, but I think as you open the file for each line you're grabbing (therefore erasing the content with 'w' mode), you only have one line written in the file at the end. Is it your problem ?

If so, try to open the file before your loop, at the beginning of the crawl method.

ContentLicense: CC BY-SA 3.0

Body:
So, as an assignment from Thenewboston, I'm trying to grab a block of code from his site and write it to a file. The code grabbing part works just fine, but the writing part doesn't work:

import requests
from bs4 import BeautifulSoup

def crawler(url):
    source = requests.get(url)
    source_text = source.text
    soup_obj = BeautifulSoup(source_text, "html.parser")
    for code in soup_obj.find('code'):
        codes = str(code)
        final_code = codes.replace('
', '').replace('Â', '')
        print(final_code)
        fx = open('crawler_code.txt', 'w')
        fx.write(final_code)
        fx.close()

crawler('https://thenewboston.com/forum/topic.php?id=1610')


问:
Split string and number and store on key-value pair
I'm trying to scrap a bunch of similar HTML pages and the tags are a nightmare IMHO.
I found that using,

```<code>IList<IWebElement> all = driver.FindElements(By.TagName("p"));
</code>```

brought quite goood results. Here's the different strings I can get using it:

```<code>1 txt 2 txt txt txt, 3 txt txt.
4 txt
5 txt 6 txt
7 txt

"txt
txt
txt"

8 txt.
</code>```

I basically want to separate numbers and text preserving their relation.
Essentially, each line is a different string (which is a different p element), including the empty ones.
The best way I could think was to generate a key value pair, but I was not able to extract numbers and text and preserve their relation.
I'm trying to do it with using the Split method

```<code>Regex.Split(input, pattern);
</code>```

which I think won't work very well on these strings. Any thoughts? The desired result would be a list like:

```<code>1: [1, txt]
2: [2, txt txt txt,]
3: [3, txt.]
4: [4, txt]
5: [5, txt]
6: [6, txt]
7: [7, txt "txt txt txt"]
8: [8, txt.]
</code>```

答:
Try this,

```<code>Dictionary<int, string> dict = new Dictionary<int, string>();
int key = -100; string value = "";
foreach(IWebElement element in all)
{
        foreach (var str in element.Text.Split(' '))
        {
            int new_key;

            if (int.TryParse(str.Trim(), out new_key))
            {
                if (value == "")
                    key = new_key;
                else
                {
                    dict[key] = value.Trim();
                    value = "";
                    key = new_key;
                }
            }
            else
            {
                value += str + " ";
            }

        }
        dict[key] = value.Trim();
}
</code>```

my code does assume that there will be no integer words in the text like "1 txt txt txt 3 txt" where 3 is part of text not key. Whenever there is an integer, this code will assume it to be a key for the dictionary.

Body:
I'm trying to scrap a bunch of similar HTML pages and the tags are a nightmare IMHO.
I found that using,

IList<IWebElement> all = driver.FindElements(By.TagName("p"));

brought quite goood results. Here's the different strings I can get using it:

1 txt 2 txt txt txt, 3 txt txt.
4 txt
5 txt 6 txt
7 txt

"txt
txt
txt"

8 txt.

I basically want to separate numbers and text preserving their relation.
Essentially, each line is a different string (which is a different p element), including the empty ones.
The best way I could think was to generate a key value pair, but I was not able to extract numbers and text and preserve their relation.
I'm trying to do it with using the Split method

Regex.Split(input, pattern);

which I think won't work very well on these strings. Any thoughts? The desired result would be a list like:

1: [1, txt]
2: [2, txt txt txt,]
3: [3, txt.]
4: [4, txt]
5: [5, txt]
6: [6, txt]
7: [7, txt "txt txt txt"]
8: [8, txt.]

Body:
Try this,

Dictionary<int, string> dict = new Dictionary<int, string>();
int key = -100; string value = "";
foreach(IWebElement element in all)
{
        foreach (var str in element.Text.Split(' '))
        {
            int new_key;

            if (int.TryParse(str.Trim(), out new_key))
            {
                if (value == "")
                    key = new_key;
                else
                {
                    dict[key] = value.Trim();
                    value = "";
                    key = new_key;
                }
            }
            else
            {
                value += str + " ";
            }

        }
        dict[key] = value.Trim();
}

my code does assume that there will be no integer words in the text like "1 txt txt txt 3 txt" where 3 is part of text not key. Whenever there is an integer, this code will assume it to be a key for the dictionary.


问:
Android ScrollView: Automatically scroll to a few pixels (dips) above a certain view
I am aware that I should decide how many pixels based on density.. not hard coded.

I have section headers and items displayed in a scrollview and I want to scroll to a certain section header (the one for the current date) while making it clear that it is not the top of the screen (show about half of the previous item).

How can I do that? I do not want this automatic scroll to be animated.

答:
With View.requestRectangleOnScreen() you can scroll to show a particular rectangle (the linked method allows disabling animation). You still will have to calculate that rectangle, but once you have the position of the particular child (your header) you can easily do that getting the size of the ScrollView. You could consider the small offset you want in calculating that rectangle or just do a scrollBy() after requestRec....() (the former way is better I think).

An easy way to use a density independent dimension is to define it in xml as a dimension resource.

-- edit: you get the position of the child in parent with getLeft() / getTop().

ContentLicense: CC BY-SA 2.5


问:
Why PATINDEX function returns 1 without finding anything?
Here is the code:

```<code>Select PATINDEX('%[a-z]%','FIRSTNAME')
</code>```

and, the result is 1. I cannot understand.

答:
For that, you will need COLLATE them as follow

```<code>SELECT patindex('%[abcdefghijklmnopqrstuvwxyz]%','FIRSTNAME' COLLATE SQL_Latin1_General_CP1_CS_AS)
</code>```

Body:
Here is the code:

Select PATINDEX('%[a-z]%','FIRSTNAME')

and, the result is 1. I cannot understand.

Body:
For that, you will need COLLATE them as follow

SELECT patindex('%[abcdefghijklmnopqrstuvwxyz]%','FIRSTNAME' COLLATE SQL_Latin1_General_CP1_CS_AS)


问:
How to use Jasmine like Mocha does on node.js
Hi there I was wondering how can I use jasmine like Mocha does w/ Chai.

So basically, in Mocha you just have to install it on node and then include it within your test files like this:

```<code>const assert = require('chai').assert;
const expect = require('chai').expect;
const should = require('chai').should();
const app = require('../app');
</code>```

Then you automatically include some test and run npm run test and you can see the failing and passing test via the terminal.

While I tried to install jasmine via node using npm install jasmine --save-dev and then put the ff:

```<code>const expect = require('jasmine');
const app = require('../app');
</code>```

And then tried some test:

```<code>describe('Multiply Numbers', function(){

  it('should return correct output', function(){
    let result = app.multiplyNumbers(2,2);
    expect(result, 4);
  });

});
</code>```

I got the ff error:

```<code>> jasmine-test@1.0.0 test c:\xampp\htdocs\unitTesting\jasmine
> jasmine

Started

No specs found
Finished in 0.003 seconds
</code>```

Any idea how can I run some test on Node js like mocha and chai does?
Also where can I find the assertion options (like expect, should..etc in chai) documentation?

PS. Here's what my package.json file:

```<code>{
  "name": "jasmine-test",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "directories": {
    "test": "test"
  },
  "scripts":{
    "test": "jasmine"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jasmine": "^2.8.0"
  }
}
</code>```

答:
There is a different way to implement testing environment using Jasmine for node setup.

First Install Jasmine-node Module

```<code>npm install jasmine-node --save-dev
</code>```

Create a tests directory and a spec file

```<code>mkdir tests
touch tests/myFirstTest.js
</code>```

Now you can add your jasmine specs in this file, following the usual Jasmine syntax.
The documentation to be followed is here: https://jasmine.github.io/2.0/introduction.html

Add following in your spec file to integrate your app with the spec.

```<code>var myApp = require("../myApp.js")
</code>```

One problem identified regarding this integration is that the specs may run again and again if server is not closed. For preventing this, just go to your application's main js file and export the close server function. Basically you need to add following in your app.js:

```<code>exports.closeServer = function(){
    server.close();
};
</code>```

Be sure to close the server in afterEach jasmine function (refer doc above) as follows:

```<code>myApp.closeServer();
</code>```

In order to run tests from terminal using npm test, just add this to your packages.json file:

```<code>"scripts": {
"test": "jasmine-node tests"
}
</code>```

You are all setup! Just run in your terminal,

```<code>npm test
</code>```

Body:
Hi there I was wondering how can I use jasmine like Mocha does w/ Chai.

So basically, in Mocha you just have to install it on node and then include it within your test files like this:

const assert = require('chai').assert;
const expect = require('chai').expect;
const should = require('chai').should();
const app = require('../app');

Then you automatically include some test and run npm run test and you can see the failing and passing test via the terminal.

While I tried to install jasmine via node using npm install jasmine --save-dev and then put the ff:

const expect = require('jasmine');
const app = require('../app');

And then tried some test:

describe('Multiply Numbers', function(){

  it('should return correct output', function(){
    let result = app.multiplyNumbers(2,2);
    expect(result, 4);
  });

});

I got the ff error:

> jasmine-test@1.0.0 test c:\xampp\htdocs\unitTesting\jasmine
> jasmine

Started

No specs found
Finished in 0.003 seconds

Any idea how can I run some test on Node js like mocha and chai does?
Also where can I find the assertion options (like expect, should..etc in chai) documentation?

PS. Here's what my package.json file:

{
  "name": "jasmine-test",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "directories": {
    "test": "test"
  },
  "scripts":{
    "test": "jasmine"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jasmine": "^2.8.0"
  }
}

Body:
There is a different way to implement testing environment using Jasmine for node setup.

First Install Jasmine-node Module

npm install jasmine-node --save-dev

Create a tests directory and a spec file

mkdir tests
touch tests/myFirstTest.js

Now you can add your jasmine specs in this file, following the usual Jasmine syntax.
The documentation to be followed is here: https://jasmine.github.io/2.0/introduction.html

Add following in your spec file to integrate your app with the spec.

var myApp = require("../myApp.js")

One problem identified regarding this integration is that the specs may run again and again if server is not closed. For preventing this, just go to your application's main js file and export the close server function. Basically you need to add following in your app.js:

exports.closeServer = function(){
    server.close();
};

Be sure to close the server in afterEach jasmine function (refer doc above) as follows:

myApp.closeServer();

In order to run tests from terminal using npm test, just add this to your packages.json file:

"scripts": {
"test": "jasmine-node tests"
}

You are all setup! Just run in your terminal,

npm test


问:
Integrate MS botframework in android app
I have created a basic Q&A bot using the MS bot framework. Now I want to integrate this chatbot in an android app as a feature. Can you tell me how do i do this.
Point me in the right direction.
Thanks.</p>

答:
If you want to create chat board then use API.AI(API.AI is now Dialogflow) provided by Google

Building engaging voice and text-based conversational interfaces powered by AI.


答:
You're overwriting the file within the loop

Open the file for writing before you loop and write

```<code>with open('crawler_code.txt', 'w') as fx:
    for code in soup_obj.find('code'):
        codes = str(code)
        final_code = codes.replace('<br/>', '').replace('Â', '')
        print(final_code)
        fx.write(final_code)
</code>```

Title: Using .write() in Python only writes a single line

Body:
You're overwriting the file within the loop

Open the file for writing before you loop and write

with open('crawler_code.txt', 'w') as fx:
    for code in soup_obj.find('code'):
        codes = str(code)
        final_code = codes.replace('<br/>', '').replace('Â', '')
        print(final_code)
        fx.write(final_code)


问:
Rotate a moving shape around its center
I'm making a 2D game in Java where the player guides a polygon through obstacles. The polygon moves up and down and the game world scrolls left and right. I need the polygon to rotate around its center, but since it is constantly being translated the point it is being rotated around moves. Trying to translate it back to the original center, rotate it, and translate it back doesn't work. How do I get the center of the shape?

Here are my motion calculations on a 2ms timer:

```<code>@Override
public void actionPerformed(ActionEvent e) {

    double theta = angleRad+90;
    if (up == true) {
        if (accelerating == false) {
            time2 = 0;
            moveX0 = moveX;
            moveY0 = moveY;
            accelerating = true;
        }
        time1++;
        double t = time1/500;
        if (accCount % 10 == 0) {
            DronePilot.velocity++;
        }
        moveX = moveX0 + velX*Math.cos(theta)*t;
        moveY = moveY0 + velY*Math.sin(theta)*t-(1/2d)*g*Math.pow(t, 2);
        velX = (DronePilot.velocity)*Math.cos(theta);
        velY = (DronePilot.velocity)*Math.sin(theta)-g*(t);
        accCount++;
    } else if (up == false){
        if (accelerating == true) {
            time1 = 0;
            moveX0 = moveX;
            moveY0 = moveY;
            accelerating = false;
        }
        time2++;
        double t = time2/500;
        moveX = moveX0 + velX*Math.cos(theta)*t;
        moveY = moveY0 + velY*Math.sin(theta)*t-(1/2d)*g*Math.pow(t, 2);
        accCount = 0;
    } if (left == true) {
        angleCount++;
        if (angleCount % 2 == 0) {
            angleDeg++;
        }
        angleRad = Math.toRadians(angleDeg);
    } else if (right == true) {
        angleCount--;
        if (angleCount % 2 == 0) {
            angleDeg--;
        }
        angleRad = Math.toRadians(angleDeg);
    }
    repaint();
}
}
</code>```

And here is my paintComponent method:

```<code>@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2D = (Graphics2D)g;

    Graphics g2 = g.create();
    Graphics2D copy = (Graphics2D)g2;

    copy.rotate(-angleRad, xPos, yPos);

    copy.translate(0, -moveY);

    g2D.translate(-moveX, 0);

    copy.draw(player.shape);

    for (Rectangle2D.Double r: DronePilot.rocksFloorArray) {
        g2D.draw(r);
    }
    for (Rectangle2D.Double r: DronePilot.rocksCeilArray) {
        g2D.draw(r);
    }
    for (Rectangle2D.Double r: DronePilot.roomsArray) {
        g2D.draw(r);
    }
}
</code>```

where (xPos, yPos) are the center of the screen.

答:
In openGL we save transformation state using pushMatrix() and popMatrix(). Here their equivalents are Graphics.create() and Graphics.dispose()

```<code>Graphics g1 = g.create();
//do transformations
g1.dispose();

Graphics g2 = g.create();
//do other stuff
g2.dispose();
</code>```

Title: Rotate a moving shape around its center

Body:
I'm making a 2D game in Java where the player guides a polygon through obstacles. The polygon moves up and down and the game world scrolls left and right. I need the polygon to rotate around its center, but since it is constantly being translated the point it is being rotated around moves. Trying to translate it back to the original center, rotate it, and translate it back doesn't work. How do I get the center of the shape?

Here are my motion calculations on a 2ms timer:

@Override
public void actionPerformed(ActionEvent e) {

    double theta = angleRad+90;
    if (up == true) {
        if (accelerating == false) {
            time2 = 0;
            moveX0 = moveX;
            moveY0 = moveY;
            accelerating = true;
        }
        time1++;
        double t = time1/500;
        if (accCount % 10 == 0) {
            DronePilot.velocity++;
        }
        moveX = moveX0 + velX*Math.cos(theta)*t;
        moveY = moveY0 + velY*Math.sin(theta)*t-(1/2d)*g*Math.pow(t, 2);
        velX = (DronePilot.velocity)*Math.cos(theta);
        velY = (DronePilot.velocity)*Math.sin(theta)-g*(t);
        accCount++;
    } else if (up == false){
        if (accelerating == true) {
            time1 = 0;
            moveX0 = moveX;
            moveY0 = moveY;
            accelerating = false;
        }
        time2++;
        double t = time2/500;
        moveX = moveX0 + velX*Math.cos(theta)*t;
        moveY = moveY0 + velY*Math.sin(theta)*t-(1/2d)*g*Math.pow(t, 2);
        accCount = 0;
    } if (left == true) {
        angleCount++;
        if (angleCount % 2 == 0) {
            angleDeg++;
        }
        angleRad = Math.toRadians(angleDeg);
    } else if (right == true) {
        angleCount--;
        if (angleCount % 2 == 0) {
            angleDeg--;
        }
        angleRad = Math.toRadians(angleDeg);
    }
    repaint();
}
}

And here is my paintComponent method:

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2D = (Graphics2D)g;

    Graphics g2 = g.create();
    Graphics2D copy = (Graphics2D)g2;

    copy.rotate(-angleRad, xPos, yPos);

    copy.translate(0, -moveY);

    g2D.translate(-moveX, 0);

    copy.draw(player.shape);

    for (Rectangle2D.Double r: DronePilot.rocksFloorArray) {
        g2D.draw(r);
    }
    for (Rectangle2D.Double r: DronePilot.rocksCeilArray) {
        g2D.draw(r);
    }
    for (Rectangle2D.Double r: DronePilot.roomsArray) {
        g2D.draw(r);
    }
}

where (xPos, yPos) are the center of the screen.

Body:
In openGL we save transformation state using pushMatrix() and popMatrix(). Here their equivalents are Graphics.create() and Graphics.dispose()

Graphics g1 = g.create();
//do transformations
g1.dispose();

Graphics g2 = g.create();
//do other stuff
g2.dispose();


问:
How to run windows command from GitBash?
I am using Gitbash to run few jars and other windows command ,so I am trying to make a master.bat to run all these jars. Bat files run them on command prompt.Is there any way to run commands on git bash(not necessarily Git command)?</p>

答: You have to type e.g. ./yourbatname.bat on gitbash, if you're in that folder, otherwise yourpathToBatFile/yourbatname.bat</p>


问:
Uploaded image name need to change
After Uploading image it shows date in the name of image in uploadfolder.Instead

need to show ward number which is posted in $ward.The commentline was i changed

but its not working.please help me.

```<code>$image_name = "img_"."_".date("Y-m-d-H-m-s").".png";

// $image_name = "img_"."_".$ward.".png";
</code>```

答:
The image name should have the ward name so that the saved file will have the same name. U need to get the ward name in some variable say $ward which is posted from the form, then add this $ward as an extension to the image name.

```<code>$ward = $_POST['ward'];
$uploads_dir = "";//path where the image needs to be stored in ur computer
$image_name = "img_".$ward.".png";
</code>```

Try this code snippet in the original code and the extension of the image will be changed

Title: Uploaded image name need to change

Body:
After Uploading image it shows date in the name of image in uploadfolder.Instead

need to show ward number which is posted in $ward.The commentline was i changed

but its not working.please help me.

$image_name = "img_"."_".date("Y-m-d-H-m-s").".png";

// $image_name = "img_"."_".$ward.".png";

Body:
The image name should have the ward name so that the saved file will have the same name. U need to get the ward name in some variable say $ward which is posted from the form, then add this $ward as an extension to the image name.

$ward = $_POST['ward'];
$uploads_dir = "";//path where the image needs to be stored in ur computer
$image_name = "img_".$ward.".png";

Try this code snippet in the original code and the extension of the image will be changed


问:
How to Show interstitial Ad on every 3 clicks in Android using LibGDX gaming framework
How i can show interstitial ad in every 3 button clicks.
Here in my game I've interstitial show in RESTART button

Here is the code

In core module ...MAIN.java and layout main

```<code>@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);

    if (((Act) event.getTarget()).enabled) {
       if (event.getTarget().getName().equals("btnRestart")) {
            loadScreen("game");
            // show AdMob Interstitial
            nativePlatform.admobInterstitial();
            return;
       }
    ....
    }
</code>```

xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <com.google.android.gms.ads.AdView
        android:id="@+id/admob"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:layout_centerHorizontal="true"
        ads:adUnitId="@string/adMob_banner"
        ads:adSize="SMART_BANNER"/>

    <FrameLayout
        android:id="@+id/app"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

    </FrameLayout>

</LinearLayout>
</code>```

there is no btn in layout

答:
Take a static counter .

```<code>public static int counter=0;
</code>```

Increase that counter on every click of your restart button. Use the remainder/modulus operator % to get your desired result.

```<code>if (((Act) event.getTarget()).enabled) {
     if (event.getTarget().getName().equals("btnRestart")) {
            counter++;
            loadScreen("game");
            // show AdMob Interstitial
            if(counter%3==0)
              nativePlatform.admobInterstitial();
            return;
     }
    ....
}
</code>```

Body:
How i can show interstitial ad in every 3 button clicks.
Here in my game I've interstitial show in RESTART button

Here is the code

In core module ...MAIN.java and layout main

@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);

    if (((Act) event.getTarget()).enabled) {
       if (event.getTarget().getName().equals("btnRestart")) {
            loadScreen("game");
            // show AdMob Interstitial
            nativePlatform.admobInterstitial();
            return;
       }
    ....
    }

xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <com.google.android.gms.ads.AdView
        android:id="@+id/admob"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:layout_centerHorizontal="true"
        ads:adUnitId="@string/adMob_banner"
        ads:adSize="SMART_BANNER"/>

    <FrameLayout
        android:id="@+id/app"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

    </FrameLayout>

</LinearLayout>

there is no btn in layout

Body:
Take a static counter .

public static int counter=0;

Increase that counter on every click of your restart button. Use the remainder/modulus operator % to get your desired result.

if (((Act) event.getTarget()).enabled) {
     if (event.getTarget().getName().equals("btnRestart")) {
            counter++;
            loadScreen("game");
            // show AdMob Interstitial
            if(counter%3==0)
              nativePlatform.admobInterstitial();
            return;
     }
    ....
}


问:
Laravel Delete function not work
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

```<code> public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}
</code>```

Model  :

```<code>protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}
</code>```

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

```<code>Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });
</code>```

答:
If you are deleting items from one table that are linked with the other table, then it gives you this error.

If you are using a pivot table, then use onDelete('cascade') like,

```<code>$table->foreign('foreign_key')->references('primary_key')->on('table_name')->onDelete('cascade');
</code>```

Ref:

Title: Laravel Delete function not work

Body:
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

 public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}

Model  :

protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });

Body:
If you are deleting items from one table that are linked with the other table, then it gives you this error.

If you are using a pivot table, then use onDelete('cascade') like,

$table->foreign('foreign_key')->references('primary_key')->on('table_name')->onDelete('cascade');

Ref:


问:
How is the Angular framework loaded into an application with Angular CLI?
I'm converting an existing AngularJS application to a hybrid application, to begin incrementally upgrading it to Angular 4. I want to understand how Angular 4 needs to be referenced in the existing AngularJS. In the existing AngularJS application, it's clear how the AngularJS framework is being loaded - it's simply an included script file:

```<code><script src="/angular/angular.js"></script>
</code>```

To familiarise myself with an up to date Angular version, I've created a separate 'quickstart' Angular 5 application using the Angular quickstart guide at https://angular.io/guide/quickstart, and I can run it using:

```<code>ng serve --open
</code>```

When I look at the project files though, I'm not seeing where the angular framework is actually being loaded. There is no script being included anywhere in the src/index.html file for that application, it simply declares an  directive for a component (app.component.ts) that looks like this:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Test Angular 5 app';
}
</code>```

Where does the import actually import from? The Angular documentation says about the index.html file that it is:

The main HTML page that is served when someone visits your site. Most
  of the time you'll never need to edit it. The CLI automatically adds
  all js and css files when building your app so you never need to add
  any  or  tags here manually.

So what is happening here? How is @angular/core actually being referenced?

答:
You need to understand how imports and exports work in TypeScript

From TypeScript Docs

Exporting a declaration

Any declaration (such as a variable, function, class, type alias, or
  interface) can be exported by adding the export keyword.

Validation.ts

```<code>export interface StringValidator {
    isAcceptable(s: string): boolean;
}
</code>```

ZipCodeValidator.ts

```<code>export const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}
</code>```

Export statements

Export statements are handy when exports need to be renamed for
  consumers, so the above example can be written as:

ZipCodeValidator.ts

```<code>class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}
export { ZipCodeValidator };
export { ZipCodeValidator as mainValidator };
</code>```

Import

Importing is just about as easy as exporting from a module. Importing
  an exported declaration is done through using one of the import forms
  below:

Import a single export from a module

```<code>import { ZipCodeValidator } from "./ZipCodeValidator";

let myValidator = new ZipCodeValidator();
</code>```

imports can also be renamed

```<code>import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
let myValidator = new ZCV();
</code>```

Import the entire module into a single variable, and use it to access the module exports

```<code>import * as validator from "./ZipCodeValidator";
let myValidator = new validator.ZipCodeValidator();
</code>```

Since you followed the Angular quickstart guide you must have used npm which is used to install your modules and dependencies.

If you read angular.io/npm

@angular/core: Critical runtime parts of the framework needed by every
  application. Includes all metadata decorators, Component, Directive,
  dependency injection, and the component lifecycle hooks.

And by default npm stores all your dependencies in node_modules directory.

So you are importing Component from @angular/core which lives inside node_modules directory.

Body:
I'm converting an existing AngularJS application to a hybrid application, to begin incrementally upgrading it to Angular 4. I want to understand how Angular 4 needs to be referenced in the existing AngularJS. In the existing AngularJS application, it's clear how the AngularJS framework is being loaded - it's simply an included script file:

To familiarise myself with an up to date Angular version, I've created a separate 'quickstart' Angular 5 application using the Angular quickstart guide at https://angular.io/guide/quickstart, and I can run it using:

ng serve --open

When I look at the project files though, I'm not seeing where the angular framework is actually being loaded. There is no script being included anywhere in the src/index.html file for that application, it simply declares an  directive for a component (app.component.ts) that looks like this:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Test Angular 5 app';
}

Where does the import actually import from? The Angular documentation says about the index.html file that it is:

The main HTML page that is served when someone visits your site. Most
  of the time you'll never need to edit it. The CLI automatically adds
  all js and css files when building your app so you never need to add
  any  or  tags here manually.

So what is happening here? How is @angular/core actually being referenced?

Body:
You need to understand how imports and exports work in TypeScript

From TypeScript Docs

Exporting a declaration

Any declaration (such as a variable, function, class, type alias, or
  interface) can be exported by adding the export keyword.

Validation.ts

export interface StringValidator {
    isAcceptable(s: string): boolean;
}

ZipCodeValidator.ts

export const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}

Export statements

Export statements are handy when exports need to be renamed for
  consumers, so the above example can be written as:

ZipCodeValidator.ts

class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}
export { ZipCodeValidator };
export { ZipCodeValidator as mainValidator };

Import

Importing is just about as easy as exporting from a module. Importing
  an exported declaration is done through using one of the import forms
  below:

Import a single export from a module

import { ZipCodeValidator } from "./ZipCodeValidator";

let myValidator = new ZipCodeValidator();

imports can also be renamed

import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
let myValidator = new ZCV();

Import the entire module into a single variable, and use it to access the module exports

import * as validator from "./ZipCodeValidator";
let myValidator = new validator.ZipCodeValidator();

Since you followed the Angular quickstart guide you must have used npm which is used to install your modules and dependencies.

If you read angular.io/npm

@angular/core: Critical runtime parts of the framework needed by every
  application. Includes all metadata decorators, Component, Directive,
  dependency injection, and the component lifecycle hooks.

And by default npm stores all your dependencies in node_modules directory.

So you are importing Component from @angular/core which lives inside node_modules directory.


问:
Unable to fetch Stream of Strings and pass it as a parameter to another method which returns int
```<code>public class JavaStreamMultIterator {

    public static void main(String[] args) {
    }

    private void iterateStringList() {
        List<String> stringList = Arrays.asList("one", "two", "three");

        List<Integer> intList = new ArrayList<>();
        intList = stringList
                .stream()
                .forEach(s - > {intForString(s));
                .collect(Collectors.toList());
    }

    private Integer intForString(String s) {

        switch (s) {
            case "one":
                return 1;
            case "two":
                return 2;
            case "three":
                return 3;
            default:
                return 15;
        }
    }
}
</code>```

I have a List<String> and I want to iterate through this list, fetch the String and pass it as a parameter to method.

That method will return an Integer and I want to add it to a List<Integer>.

```<code>intList = stringList
            .stream()
            .forEach(s - > {intForString(s));
            .collect(Collectors.toList());
</code>```

答:
forEach is terminal function, it would consume and does not return anything.
You need to value from intForString() for your list generation.</p>

```<code>List<Integer> intList =
                stringList //your list
                .stream() //generate stream
                .map(this::intForString) //map them to integer
                .collect(Collectors.toList());//collect all the integer toList()
</code>```

Body:
public class JavaStreamMultIterator {

    public static void main(String[] args) {
    }

    private void iterateStringList() {
        List<String> stringList = Arrays.asList("one", "two", "three");

        List<Integer> intList = new ArrayList<>();
        intList = stringList
                .stream()
                .forEach(s - > {intForString(s));
                .collect(Collectors.toList());
    }

    private Integer intForString(String s) {

        switch (s) {
            case "one":
                return 1;
            case "two":
                return 2;
            case "three":
                return 3;
            default:
                return 15;
        }
    }
}

I have a List<String> and I want to iterate through this list, fetch the String and pass it as a parameter to method.

That method will return an Integer and I want to add it to a List<Integer>.

intList = stringList
            .stream()
            .forEach(s - > {intForString(s));
            .collect(Collectors.toList());

Body:
forEach is terminal function, it would consume and does not return anything.
You need to value from intForString() for your list generation.

List<Integer> intList =
                stringList //your list
                .stream() //generate stream
                .map(this::intForString) //map them to integer
                .collect(Collectors.toList());//collect all the integer toList()


问:
Count variables per group at time intervals
I am collecting data about a fleet of vehicles at 10 minute intervals. The following query returns 144 rows as expected (the number of 10-minute intervals in one day).

```<code>  select distinct(date_trunc('minute', (((time::timestamp) AT TIME ZONE 'UTC') AT TIME ZONE 'EST'))) FROM fleet_history WHERE (((time::timestamp) AT TIME ZONE 'UTC') AT TIME ZONE 'EST') BETWEEN '2017-11-30 00:00:00'::timestamp AND '2017-11-30 23:59:59'::timestamp ORDER BY date_trunc DESC
</code>```

In the table fleet_history, there is another column named repair_state - a character column that contains the description of whether the vehicle is "working" or "in repair" or "other".

```<code>select * FROM fleet_history limit 5

  id repair_state                time
1  1      working 2017-11-22 15:45:34
2  2    in repair 2017-11-22 15:45:34
3  3      working 2017-11-22 15:45:34
4  4      working 2017-11-22 15:45:34
5  5        other 2017-11-22 15:45:34
</code>```

My objective is to, at each 10-minute interval, output the truncated time, and number (count) of working vehicles, in repair vehicles and other, (grouping by interval).

How would one write this query in PostgreSQL?

答:
One approach creates a CTE calendar table containing the ten minute intervals on a given day.  Then left join this calendar table to your fleet_history table on the condition that the time falls within a given ten minute interval.  Finally, do a conditional aggregation over each each interval and count the various types of repair states.

```<code>with calendar as (
    select i from generate_series('2017-11-22',
    '2017-11-23', '10 minute'::interval) i
)

select
    t1.i,
    sum(case when t2.repair_state = 'working'   then 1 else 0 end) as working_cnt,
    sum(case when t2.repair_state = 'in repair' then 1 else 0 end) as repair_cnt,
    sum(case when t2.repair_state = 'other'     then 1 else 0 end) as other_cnt
from calendar t1
left join fleet_history t2
    on t2.time >= t1.i and t2.time < t1.i + INTERVAL '10 min'
group by
    t1.i
order by
    t1.i;
</code>```

Follow the link below for a running demo.  It is a bit contrived, because your sample data included only 5 records, all from the same 10 minute interval.

Demo

Body:
I am collecting data about a fleet of vehicles at 10 minute intervals. The following query returns 144 rows as expected (the number of 10-minute intervals in one day).

  select distinct(date_trunc('minute', (((time::timestamp) AT TIME ZONE 'UTC') AT TIME ZONE 'EST'))) FROM fleet_history WHERE (((time::timestamp) AT TIME ZONE 'UTC') AT TIME ZONE 'EST') BETWEEN '2017-11-30 00:00:00'::timestamp AND '2017-11-30 23:59:59'::timestamp ORDER BY date_trunc DESC

In the table fleet_history, there is another column named repair_state - a character column that contains the description of whether the vehicle is "working" or "in repair" or "other".

select * FROM fleet_history limit 5

  id repair_state                time
1  1      working 2017-11-22 15:45:34
2  2    in repair 2017-11-22 15:45:34
3  3      working 2017-11-22 15:45:34
4  4      working 2017-11-22 15:45:34
5  5        other 2017-11-22 15:45:34

My objective is to, at each 10-minute interval, output the truncated time, and number (count) of working vehicles, in repair vehicles and other, (grouping by interval).

How would one write this query in PostgreSQL?

Body:
One approach creates a CTE calendar table containing the ten minute intervals on a given day.  Then left join this calendar table to your fleet_history table on the condition that the time falls within a given ten minute interval.  Finally, do a conditional aggregation over each each interval and count the various types of repair states.

with calendar as (
    select i from generate_series('2017-11-22',
    '2017-11-23', '10 minute'::interval) i
)

select
    t1.i,
    sum(case when t2.repair_state = 'working'   then 1 else 0 end) as working_cnt,
    sum(case when t2.repair_state = 'in repair' then 1 else 0 end) as repair_cnt,
    sum(case when t2.repair_state = 'other'     then 1 else 0 end) as other_cnt
from calendar t1
left join fleet_history t2
    on t2.time >= t1.i and t2.time < t1.i + INTERVAL '10 min'
group by
    t1.i
order by
    t1.i;

Follow the link below for a running demo.  It is a bit contrived, because your sample data included only 5 records, all from the same 10 minute interval.

Demo


问:
Custom error conditions to trigger fallback in Hystrix
From the understanding, Hystrix fallback logic is triggered when certain conditions occurred such as Request timeout, thread-pool running at a capacity of 100% or dependency throws exception. Beside these 3 factors can I add more conditions that are also considered as failures such as any specific HTTP Error code like 413 (payload too large)?</p>

答:
The fallback method of Hystrix will be called under the following condition

circuit open

semaphore/thread pool rejection

execution fail (any exception thrown by your method excluding HystrixBadRequestException)

timeout of your method (hystrix timeout)

Only part that is directly related to the user code is execution fail.

In this case, fallback will be triggered by any exception thrown by run() method. It is same for pure Hystrix via HystrixCommand and Hystrix Javanica via annotation.

Only one exception that doesn't trigger HystrixBadRequestException

Therefore, if you want to trigger your fallback also for HTTP 413 status code, all you have to is just throwing any exception inside your method.

If you're using any library that has built-in Hystrix support like Spring Cloud Feign, you need to implement something that library requires. In case of Spring Cloud Feign, you can implement your own ErrorDecoder. The default error decoder will trigger fallback for all 4XX,5XX errors. If you don't want to trigger any fallback 4XX errors except 413, you can throw HystrixBadRequestException inside it.


答:
By default, your .bat would not be executable.

You need:

```<code>chmod 775 yourScript.bat
./yourScript.bat
</code>```

Title: How to run windows command from GitBash?

Body: I am using Gitbash to run few jars and other windows command ,so I am trying to make a master.bat to run all these jars. Bat files run them on command prompt.Is there any way to run commands on git bash(not necessarily Git command)?

Body:
By default, your .bat would not be executable.

You need:

chmod 775 yourScript.bat
./yourScript.bat


问:
How to use Node Server Writing to Firebase from text file to add Strings to a child without a unique key
I have a working node server that uses FS to read from a text file and uploads the Data into separate strings onto Firebase. I am not concerned about security/authentication because this is just a small senior design 'work-around'. My problem is that I made an Android App to read from Firebase and it cannot read the pushed strings from the node server because of an auto generated key. Here's an illustration:

```<code>   FireBase-Root
  -> CHILD1
     ->String1 from manual input
     ->String2 from manual input
     ->String3 from manual input
     -> AUTO Generated USER KEY
        ->String1 pushed from text file
        ->String2 pushed from txt file
        ->String3 pushed from text file
</code>```

The Android App is able to read the strings from the manual input because it reads CHILD1 directly. I need a way to write to CHILD1 without push so that the auto generated user key does not exist.

I could also change the Android App to implement a USER function to read from the auto generated keys but I would prefer changing the node server

Below is my index.js file which is the node.js server file:

```<code>var admin = require("firebase-admin");
var serviceAccount = require("./adminkey.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://snaresense.firebaseio.com"
    });

var ref = admin.database().ref('snaresense');

var fs = require("fs");

fs.readFile("received_details.txt", "utf8", function(error, data) {

    if (error) {
        return console.log(error);
        }
    StringData = data;

    var dataArr = data.split(" ");
    console.log(dataArr);

    StringActive = dataArr[0];
    console.log(StringActive);

    StringTrapId = dataArr[1];
    console.log(StringTrapId);

    StringPhoneNum = dataArr[2];
    console.log(StringPhoneNum);

    StringBatteryLevel = dataArr[4];
    console.log(StringBatteryLevel);

    var stringsRef = ref.child('strings');

        stringsRef.push({
            StringActive,
            StringTrapId,
            StringPhoneNum,
            StringBatteryLevel
        });

});
</code>```

Just to reiterate. Everything works fine. I just need to write these strings to Firebase without PUSH so that the autogenerated key does not exist. Or another solution that allows an Android App to read from the same child directly that this node server writes to.

Thanks

答:
In the 'Index.js' file (or wherever your node server is)

change "push" to "set"

Yup. It's that easy. Wasted so much time of my life.

Body:
I have a working node server that uses FS to read from a text file and uploads the Data into separate strings onto Firebase. I am not concerned about security/authentication because this is just a small senior design 'work-around'. My problem is that I made an Android App to read from Firebase and it cannot read the pushed strings from the node server because of an auto generated key. Here's an illustration:

   FireBase-Root
  -> CHILD1
     ->String1 from manual input
     ->String2 from manual input
     ->String3 from manual input
     -> AUTO Generated USER KEY
        ->String1 pushed from text file
        ->String2 pushed from txt file
        ->String3 pushed from text file

The Android App is able to read the strings from the manual input because it reads CHILD1 directly. I need a way to write to CHILD1 without push so that the auto generated user key does not exist.

I could also change the Android App to implement a USER function to read from the auto generated keys but I would prefer changing the node server

Below is my index.js file which is the node.js server file:

var admin = require("firebase-admin");
var serviceAccount = require("./adminkey.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "https://snaresense.firebaseio.com"
    });

var ref = admin.database().ref('snaresense');

var fs = require("fs");

fs.readFile("received_details.txt", "utf8", function(error, data) {

    if (error) {
        return console.log(error);
        }
    StringData = data;

    var dataArr = data.split(" ");
    console.log(dataArr);

    StringActive = dataArr[0];
    console.log(StringActive);

    StringTrapId = dataArr[1];
    console.log(StringTrapId);

    StringPhoneNum = dataArr[2];
    console.log(StringPhoneNum);

    StringBatteryLevel = dataArr[4];
    console.log(StringBatteryLevel);

    var stringsRef = ref.child('strings');

        stringsRef.push({
            StringActive,
            StringTrapId,
            StringPhoneNum,
            StringBatteryLevel
        });

});

Just to reiterate. Everything works fine. I just need to write these strings to Firebase without PUSH so that the autogenerated key does not exist. Or another solution that allows an Android App to read from the same child directly that this node server writes to.

Thanks


问:
ng-repeat and ng-if to set value of td
I am trying to set td value based on condition, here is my code

```<code><td>
<span ng-init="tdValue=true;"></span>
<span ng-repeat="value in data_report" ng-if="fellow.F_Id==value.fellowship_id">
<span ng-init="tdValue=false;">{{value.Completed}}</span>
</span>
<span ng-if="tdValue">0</span>
</td>
</code>```

In the following code I am checking
1. If the condition matches set the value to value.completed
2. If not keep default value as zero

But the result i am getting is
14 0

14 is value.completes and 0 is default value (Both the values are getting printed)

答:
Try this

```<code><td>

<span >{{selectedId}}</span>

</td>
</code>```

This is controller code you can try out.

```<code>$scope.selectedId=0;
for(var i=0;i<$scope.data_report.length;i++){
if($scope.fellow.F_Id==$scope.data_report[i].fellowship_id){
$scope.selectedId=$scope.data_report[i].fellowship_id;
break;
}
}
</code>```

Title: ng-repeat and ng-if to set value of td

Body:
I am trying to set td value based on condition, here is my code

{{value.Completed}}

0

In the following code I am checking
1. If the condition matches set the value to value.completed
2. If not keep default value as zero

But the result i am getting is
14 0

14 is value.completes and 0 is default value (Both the values are getting printed)

Body:
Try this

<td>

<span >{{selectedId}}</span>

</td>

This is controller code you can try out.

$scope.selectedId=0;
for(var i=0;i<$scope.data_report.length;i++){
if($scope.fellow.F_Id==$scope.data_report[i].fellowship_id){
$scope.selectedId=$scope.data_report[i].fellowship_id;
break;
}
}


问:
Designing for "Pretty" URLs
I'm aware of mod_rewrite methods to convert ugly URLs to pretty. My question is preceding this conversion.

I have not yet developed my website. I would like to design all pages such that the pretty URLs are also pretty on the server side.

I would like to come up with a general rule for ALL pages. Normally all pages are slightly different...

```<code>/news/12345                        =>    /news.php?id=1234
/members/Mikhail                   =>    /members.php?name=Mikhail
/subsection/page/banned-members    =>    /subsection/page.php?view=banned-members
</code>```

In the three examples above the GET variable name is different for each case, and the third example could ALSO be developed to be interpreted as /subsection.php?file=page&view=banned-members

So my question is: What can I do, from the design point, do have an elegant solution on the client AND server side to create pretty URLs?

Thanks!

答:
A general rule of thumb would be to use a portion of the url to identify resources, and GET parameters for optional modifications to how the resource is presented.

For example, for a user profile url:

/user/joe

and

/user/joe?showfull=1

Both the same resource (the user profile), but the latter specifies how to present the information (show full information about the user instead of the default amount).

Applying this convention to your examples above, I would prefer:

```<code>/news/12345
/members/Mikhail
/subsection/page?view=banned-members
</code>```

Title: Designing for "Pretty" URLs

Body:
I'm aware of mod_rewrite methods to convert ugly URLs to pretty. My question is preceding this conversion.

I have not yet developed my website. I would like to design all pages such that the pretty URLs are also pretty on the server side.

I would like to come up with a general rule for ALL pages. Normally all pages are slightly different...

/news/12345                        =>    /news.php?id=1234
/members/Mikhail                   =>    /members.php?name=Mikhail
/subsection/page/banned-members    =>    /subsection/page.php?view=banned-members

In the three examples above the GET variable name is different for each case, and the third example could ALSO be developed to be interpreted as /subsection.php?file=page&view=banned-members

So my question is: What can I do, from the design point, do have an elegant solution on the client AND server side to create pretty URLs?

Thanks!

Body:
A general rule of thumb would be to use a portion of the url to identify resources, and GET parameters for optional modifications to how the resource is presented.

For example, for a user profile url:

/user/joe

and

/user/joe?showfull=1

Both the same resource (the user profile), but the latter specifies how to present the information (show full information about the user instead of the default amount).

Applying this convention to your examples above, I would prefer:

/news/12345
/members/Mikhail
/subsection/page?view=banned-members


问:
FOS User Change Password Event Listener
I have a problem with a listening event on change password submit.

Here is listener

```<code>public function __construct(
    UrlGeneratorInterface $router,
    Session $session,
    TokenStorageInterface $tokenStorage
) {
    $this->router = $router;
    $this->session = $session;
    $this->tokenStorage = $tokenStorage;
}

public static function getSubscribedEvents()
{
    return [
        FOSUserEvents::CHANGE_PASSWORD_SUCCESS => [
            ['onChangePasswordSuccess', +10000]
        ],
    ];
}

public function onChangePasswordSuccess(GetResponseUserEvent $event)
{
    $this->tokenStorage->setToken(); // logout user
    $this->session->invalidate();
    $event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
}
</code>```

But nothing happens. I put debugger breakpoint on $this->tokenStorage->setToken() but it wasn't stop.
Could somebody help me to figure why this not working

答: Hahaha. I loked in wrong controller. When I found right, everything worked as it should. Thanks Ivan for your help</p>

Title: FOS User Change Password Event Listener

Body:
I have a problem with a listening event on change password submit.

Here is listener

public function __construct(
    UrlGeneratorInterface $router,
    Session $session,
    TokenStorageInterface $tokenStorage
) {
    $this->router = $router;
    $this->session = $session;
    $this->tokenStorage = $tokenStorage;
}

public static function getSubscribedEvents()
{
    return [
        FOSUserEvents::CHANGE_PASSWORD_SUCCESS => [
            ['onChangePasswordSuccess', +10000]
        ],
    ];
}

public function onChangePasswordSuccess(GetResponseUserEvent $event)
{
    $this->tokenStorage->setToken(); // logout user
    $this->session->invalidate();
    $event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
}

But nothing happens. I put debugger breakpoint on $this->tokenStorage->setToken() but it wasn't stop.
Could somebody help me to figure why this not working


问:
use tensorflow object detection API for gender recognition
can I use tensorflow object detection API for gender recognition?
I want to train SSD_mobile net for gender recognition and detection. I changed labelmap to:

```<code>item {
  id: 1
  name: 'man'
}
item {
  id: 2
  name: 'woman'
}
</code>```

and num_classes=2
I attach to training_loss=8 but when I feed an image to the network to test, the result is awful.
what should I do? can somebody help me?

答:
You can. The method that you need to follow is as following:

Use SSD to extract the location of the object to be found (face in here).

Get relevant feature map of the location at conv5 (assume that you use VGG). For example, if you find your object at location (100, 100, 100, 100 - XYWH) within input image with size (300, 300), cut conv5 features at (12, 12, 12, 12 - XYWH). Math is (100 / 300) * 38.

Now you shall have the activation features cut from conv5 (12 x 12 x 512) and which is only relevant with the face that you want to predict the gender.

Flatten this feature activation and apply DNN Classifier for it (i.e. Classifier used for VGG).

Get binary output stating either male or female.

Train your network by adding gender loss to global loss function.

Voila. You have the gender estimation network.

Body:
can I use tensorflow object detection API for gender recognition?
I want to train SSD_mobile net for gender recognition and detection. I changed labelmap to:

item {
  id: 1
  name: 'man'
}
item {
  id: 2
  name: 'woman'
}

and num_classes=2
I attach to training_loss=8 but when I feed an image to the network to test, the result is awful.
what should I do? can somebody help me?


问:
Retrive records of a table with out related tables' records by Entity Framework?
When I get records of a table by EF such as

```<code>db.cities.Tolist();
</code>```

returns all records of the City table and related tables records but I want get city table records only .

Is this possible?

答:
Yes, you can use lazy loading feature of EF like below. Add this line just before any ToList() calls </p>

```<code>db.Configuration.LazyLoadingEnabled = false;
</code>```

<p>also you can configure this behavior globally by setting the property in your DBContext Constructor like below. </p>

```<code>public partial class SchoolDBEntities : DbContext
{
    public SchoolDBEntities(): base("name=SchoolDBEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

}
</code>```

Body:
When I get records of a table by EF such as

db.cities.Tolist();

returns all records of the City table and related tables records but I want get city table records only .

Is this possible?

Body:
Yes, you can use lazy loading feature of EF like below. Add this line just before any ToList() calls

db.Configuration.LazyLoadingEnabled = false;

also you can configure this behavior globally by setting the property in your DBContext Constructor like below.

public partial class SchoolDBEntities : DbContext
{
    public SchoolDBEntities(): base("name=SchoolDBEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

}


问:
Import to the same Subversion repository directory multiple times?
For a number of reasons, the canonical source of some files I have can't be a working copy of the repository (the Subversion server is behind an inaccessible firewall, and the data doesn't natively exist in the file system in my preferred structure). So, I wrote a tool that downloads the data, generates a directory structure from it, and then uses SharpSvn to import the result into the repository. This works… the first time. The second time, of course, a directory of that name already exists in the repository, and I can't import again.

Instead, I could:

Delete the directory, then import. I haven't tested this, but aside from sounding stupid, it probably also deletes the revision history of the respective files, regarding the new ones as entirely different.

See if the directory exists, check it out, remotely delete the files that no longer exist in the canonical source, then replace the remainder and commit. This would probably work, but sounds error-prone and needlessly difficult.

Is my assumption correct that deleting files will mark new ones of the same ways as different files? Is there an easier way than the second approach?

答:
For 1), it won't delete the revision history, but the new files will be treated as completely unrelated to the old ones. You still could get the old files back though.

For 2), that would be the recommended way. But after 'svn delete'ing the existing files and adding the new ones, you also have to 'svn add' those new files before committing.

But it seems you should consider using the svn-load-dirs.pl script. You can read about this in the Subversion book, chapter "Vendor branches".

OwnerDisplayName: Sören Kuklau

OwnerDisplayName: Stefan


问:
How to automatically authenticate windows integrate without login popup?
I wrote an asp.net application with default.aspx. When I hit this page It is asking me windows login popup window. My application should me windows authentication required but it should "Integrated Windows authentication". If I enter login password I am able to see my page.

How can I automatically integrate this windows authentication?

I added below code in web.config. still doesn't work.

```<code><authentication mode="Windows"/>
    <identity impersonate="false"/>
    <authorization>
        <deny users="?"/>
    </authorization>
</code>```

答: You need to uncheck Enable anonymous access in IIS and you can also remove the identity and authorization nodes in your web.config.  Keep in mind that not all browsers support this and most will still prompt you for authentication.

Body:
I wrote an asp.net application with default.aspx. When I hit this page It is asking me windows login popup window. My application should me windows authentication required but it should "Integrated Windows authentication". If I enter login password I am able to see my page.

How can I automatically integrate this windows authentication?

I added below code in web.config. still doesn't work.

<authentication mode="Windows"/>
    <identity impersonate="false"/>
    <authorization>
        <deny users="?"/>
    </authorization>


问:
Trying to update a column before return view with laravel
I am new to laravel.
I am trying to create an update before return view but i am getting Property [Video_Views] does not exist on this collection instance.

This is my code

$vidurl="WZzZdBjnjBwbMJh";
 $curvid = videos::where('Video_URL', '=', $vidurl)->get();
 $viewsarray = array($curvid->Video_Views);

but when i remove $viewsarray = array($curvid->Video_Views); and let my return view work, i can get every information from $curvid into the page. Meaning my code works fine for selecting and display into the return view page. But i want to perform an update before the returnview page but for some reason the Video_Views in $viewsarray = array($curvid->Video_Views); doesnt exist

These are the columns in mysql table called videos
I can select all these in the return view page but i can't retrieve any info before the returnview page

Any help would be nice!

答:
Try
$curvid = videos::where('Video_URL', '=', $vidurl)->first();

instead of $curvid = videos::where('Video_URL', '=', $vidurl)->get();

Or use foreach operator.

Example:

```<code>$vidurl="WZzZdBjnjBwbMJh";
$curvid = videos::where('Video_URL', '=', $vidurl)->get();
foreach($curvid as $vid){
    $viewsarray = array($vid->Video_Views);
}
</code>```

Body:
Try
$curvid = videos::where('Video_URL', '=', $vidurl)->first();

instead of $curvid = videos::where('Video_URL', '=', $vidurl)->get();

Or use foreach operator.

Example:

$vidurl="WZzZdBjnjBwbMJh";
$curvid = videos::where('Video_URL', '=', $vidurl)->get();
foreach($curvid as $vid){
    $viewsarray = array($vid->Video_Views);
}


问:
Is it necessary to url encode placeIDs in google maps/direction api?
It seems like it's not necessary judging from all the placeIDs that I've seen so far. So just making sure.</p>

答:
Yes, it is no longer necessary. As far as I know, placeIDs doesn't contain spaces, characters outside the ASCII set and any reserved ASCII characters, so convertion or URL Encoding won't be necessary, as well with encyrption.

A place ID is a textual identifier that uniquely identifies a
  place. The length of the identifier may vary. Examples:

ChIJrTLr-GyuEmsRBfy61i59si0

EisxMyBNYXJrZXQgU3RyZWV0LCBXaWxtaW5ndG9uLCBOQyAyODQwMSwgVVNB

You can also save place IDs for later use. Place IDs are exempt from the caching restrictions stated in Section 10.5.d of the Google Maps APIs Terms of Service. You can therefore store place ID values for later use. Just refresh your stored place IDs periodically, after 100 days to avoid NOT_FOUND status code.  To learn more about Place IDs, you can check Google Places API Place IDs.

Hope this helps.


答:
Go to your gallery migration file inside database/migrations/examplegallerytable.php and update the relationship definition to these:

```<code>$table->foreign('media_id')->references('id')->on('medias')->onDelete('cascade');
</code>```

then run these command:

```<code>php artisan migrate:reset
</code>```

and

```<code>php artisan migrate
</code>```

that's all

Title: Laravel Delete function not work

Body:
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

 public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}

Model  :

protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });

Body:
Go to your gallery migration file inside database/migrations/examplegallerytable.php and update the relationship definition to these:

$table->foreign('media_id')->references('id')->on('medias')->onDelete('cascade');

then run these command:

php artisan migrate:reset

and

php artisan migrate

that's all


问:
Google Places AutoComplete API gives API_NOT_CONNECTED error in Instant Apps configuration
I am trying to add Google Places AutoComplete API to my Android Instant Apps project.

I followed this sample to implement the API.

My PlacesAdapter class:

```<code>package net.epictimes.uvindex.autocomplete

import android.content.Context
import android.graphics.Typeface
import android.text.style.StyleSpan
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import com.google.android.gms.common.data.DataBufferUtils
import com.google.android.gms.location.places.AutocompletePrediction
import com.google.android.gms.location.places.GeoDataClient
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.tasks.RuntimeExecutionException
import com.google.android.gms.tasks.Tasks
import timber.log.Timber
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

class PlacesAdapter(context: Context, private val geoDataClient: GeoDataClient)
    : ArrayAdapter<AutocompletePrediction>(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1), Filterable {

    private val resultList = mutableListOf<AutocompletePrediction>()
    private val styleBold = StyleSpan(Typeface.BOLD)

    override fun getCount(): Int = resultList.size

    override fun getItem(position: Int): AutocompletePrediction = resultList[position]

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val row = super.getView(position, convertView, parent)

        // Sets the primary and secondary text for a row.
        // Note that getPrimaryText() and getSecondaryText() return a CharSequence that may contain
        // styling based on the given CharacterStyle.

        val item = getItem(position)

        val textView1 = row.findViewById<View>(android.R.id.text1) as TextView
        val textView2 = row.findViewById<View>(android.R.id.text2) as TextView
        textView1.text = item.getPrimaryText(styleBold)
        textView2.text = item.getSecondaryText(styleBold)

        return row
    }

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                val results = FilterResults()

                // We need a separate list to store the results, since
                // this is run asynchronously.
                var filterData: ArrayList<AutocompletePrediction>? = ArrayList()

                // Skip the autocomplete query if no constraints are given.
                if (constraint != null) {
                    // Query the autocomplete API for the (constraint) search string.
                    filterData = getAutocomplete(constraint)
                }

                results.values = filterData
                if (filterData != null) {
                    results.count = filterData.size
                } else {
                    results.count = 0
                }

                return results
            }

            override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                if (results != null && results.count > 0) {
                    // The API returned at least one result, update the data.
                    resultList.clear()
                    resultList.addAll(results.values as ArrayList<AutocompletePrediction>)
                }

                notifyDataSetChanged()
            }

        }
    }

    /**
     * Submits an autocomplete query to the Places Geo Data Autocomplete API.
     * Results are returned as frozen AutocompletePrediction objects, ready to be cached.
     * Returns an empty list if no results were found.
     * Returns null if the API client is not available or the query did not complete
     * successfully.
     * This method MUST be called off the main UI thread, as it will block until data is returned
     * from the API, which may include a network request.
     *
     * @param constraint Autocomplete query string
     * @return Results from the autocomplete API or null if the query was not successful.
     * @see GeoDataClient.getAutocompletePredictions
     * @see AutocompletePrediction.freeze
     */
    private fun getAutocomplete(constraint: CharSequence): ArrayList<AutocompletePrediction>? {
        Timber.d("Starting autocomplete query for: " + constraint)

        val latLngBounds = LatLngBounds(LatLng(-34.041458, 150.790100), LatLng(-33.682247, 151.383362))

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        val results = geoDataClient.getAutocompletePredictions(constraint.toString(), latLngBounds, null)

        // This method should have been called off the main UI thread. Block and wait for at most
        // 60s for a result from the API.
        try {
            Tasks.await(results, 60, TimeUnit.SECONDS)
        } catch (e: ExecutionException) {
            Timber.e(e)
        } catch (e: InterruptedException) {
            Timber.e(e)
        } catch (e: TimeoutException) {
            Timber.e(e)
        }

        Timber.d("Query completed. Received " + results.result.count + " predictions.")

        return try {
            // Freeze the results immutable representation that can be stored safely.
            DataBufferUtils.freezeAndClose<AutocompletePrediction, AutocompletePrediction>(results.result)
        } catch (e: RuntimeExecutionException) {
            // If the query did not complete successfully return null
            Timber.e("Error getting autocomplete prediction API call", e)
            null
        }

    }
}
</code>```

When I run the project in app configuration it works fine.

But when I run it in instantapp configuration it throws this:

```<code>D/PlacesAdapter: Starting autocomplete query for: is
E/GmsClient: unable to connect to service: com.google.android.gms.location.places.GeoDataApi on com.google.android.gms
E/PlacesAdapter: java.util.concurrent.ExecutionException: com.google.android.gms.common.api.ApiException: 17: API_NOT_CONNECTED
                     at com.google.android.gms.tasks.Tasks.zzc(Unknown Source:17)
                     at com.google.android.gms.tasks.Tasks.await(Unknown Source:53)
                     at net.epictimes.uvindex.autocomplete.PlacesAdapter.getAutocomplete(PlacesAdapter.kt:116)
                     at net.epictimes.uvindex.autocomplete.PlacesAdapter.access$getAutocomplete(PlacesAdapter.kt:25)
                     at net.epictimes.uvindex.autocomplete.PlacesAdapter$getFilter$1.performFiltering(PlacesAdapter.kt:64)
                     at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
                     at android.os.Handler.dispatchMessage(Handler.java:105)
                     at android.os.Looper.loop(Looper.java:164)
                     at android.os.HandlerThread.run(HandlerThread.java:65)
                  Caused by: com.google.android.gms.common.api.ApiException: 17: API_NOT_CONNECTED
                     at com.google.android.gms.common.internal.zzb.zzz(Unknown Source:14)
                     at com.google.android.gms.common.internal.zzbk.zzaa(Unknown Source:0)
                     at com.google.android.gms.common.internal.zzbl.zzs(Unknown Source:32)
                     at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source:46)
                     at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source:42)
                     at com.google.android.gms.common.api.internal.zzm.zzv(Unknown Source:17)
                     at com.google.android.gms.common.api.internal.zzc.zzt(Unknown Source:2)
                     at com.google.android.gms.common.api.internal.zzbr.zzx(Unknown Source:27)
                     at com.google.android.gms.common.api.internal.zzbp.handleMessage(Unknown Source:386)
                     at android.os.Handler.dispatchMessage(Handler.java:101)
                     at android.os.Looper.loop(Looper.java:164)
                     at android.os.HandlerThread.run(HandlerThread.java:65)
W/Filter: An exception occured during performFiltering()!
          com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 17: API_NOT_CONNECTED
              at com.google.android.gms.tasks.zzn.getResult(Unknown Source:14)
              at net.epictimes.uvindex.autocomplete.PlacesAdapter.getAutocomplete(PlacesAdapter.kt:123)
              at net.epictimes.uvindex.autocomplete.PlacesAdapter.access$getAutocomplete(PlacesAdapter.kt:25)
              at net.epictimes.uvindex.autocomplete.PlacesAdapter$getFilter$1.performFiltering(PlacesAdapter.kt:64)
              at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
              at android.os.Handler.dispatchMessage(Handler.java:105)
              at android.os.Looper.loop(Looper.java:164)
              at android.os.HandlerThread.run(HandlerThread.java:65)
           Caused by: com.google.android.gms.common.api.ApiException: 17: API_NOT_CONNECTED
              at com.google.android.gms.common.internal.zzb.zzz(Unknown Source:14)
              at com.google.android.gms.common.internal.zzbk.zzaa(Unknown Source:0)
              at com.google.android.gms.common.internal.zzbl.zzs(Unknown Source:32)
              at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source:46)
              at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source:42)
              at com.google.android.gms.common.api.internal.zzm.zzv(Unknown Source:17)
              at com.google.android.gms.common.api.internal.zzc.zzt(Unknown Source:2)
              at com.google.android.gms.common.api.internal.zzbr.zzx(Unknown Source:27)
              at com.google.android.gms.common.api.internal.zzbp.handleMessage(Unknown Source:386)
              at android.os.Handler.dispatchMessage(Handler.java:101)
              at android.os.Looper.loop(Looper.java:164)
              at android.os.HandlerThread.run(HandlerThread.java:65)
</code>```

API_NOT_CONNECTED error code's explation in the docs:

The client attempted to call a method from an API that failed to
  connect. Possible reasons include:

The API previously failed to connect with a resolvable error, but the    user declined the resolution.

The device does not support GmsCore.

The specific API cannot connect on this device.

I updated the Google Play Services on the emulator (it's 11.7.46 (470-175121617) BTW) but it didn't changed anyting.

I put my Google Play Services dependencies into the base module. I checked the merged manifest files, they all have the Google Play API keys.

In the Android Developers site they listed Google Places API in the supported API list.

I am using Google Location API in the other feature module and it is working in both app and instantapp configurations.

So what am I doing wrong here?

答:
I decided to connect the API using the GoogleApiClient:

```<code>GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Places.GEO_DATA_API)
                .build()
                .connect()
</code>```

But the connection attempt failed with status code API_UNAVAILABLE in instantapp configuration.

In the docs, API_UNAVAILABLE means that the API is not available for Instant Apps:

When debugging an instant app that uses a Google Play services library
  other than those included in the list above, you may see the
  API_UNAVAILABLE error in your debugging output. The API_UNAVAILABLE
  error indicates that the library has not been adapted for usage in
  Android Instant Apps.

So I dropped the Places AutoComplete and continued with something similar like geocoding.

Body:
I am trying to add Google Places AutoComplete API to my Android Instant Apps project.

I followed this sample to implement the API.

My PlacesAdapter class:

package net.epictimes.uvindex.autocomplete

import android.content.Context
import android.graphics.Typeface
import android.text.style.StyleSpan
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import com.google.android.gms.common.data.DataBufferUtils
import com.google.android.gms.location.places.AutocompletePrediction
import com.google.android.gms.location.places.GeoDataClient
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.tasks.RuntimeExecutionException
import com.google.android.gms.tasks.Tasks
import timber.log.Timber
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

class PlacesAdapter(context: Context, private val geoDataClient: GeoDataClient)
    : ArrayAdapter<AutocompletePrediction>(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1), Filterable {

    private val resultList = mutableListOf<AutocompletePrediction>()
    private val styleBold = StyleSpan(Typeface.BOLD)

    override fun getCount(): Int = resultList.size

    override fun getItem(position: Int): AutocompletePrediction = resultList[position]

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val row = super.getView(position, convertView, parent)

        // Sets the primary and secondary text for a row.
        // Note that getPrimaryText() and getSecondaryText() return a CharSequence that may contain
        // styling based on the given CharacterStyle.

        val item = getItem(position)

        val textView1 = row.findViewById<View>(android.R.id.text1) as TextView
        val textView2 = row.findViewById<View>(android.R.id.text2) as TextView
        textView1.text = item.getPrimaryText(styleBold)
        textView2.text = item.getSecondaryText(styleBold)

        return row
    }

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                val results = FilterResults()

                // We need a separate list to store the results, since
                // this is run asynchronously.
                var filterData: ArrayList<AutocompletePrediction>? = ArrayList()

                // Skip the autocomplete query if no constraints are given.
                if (constraint != null) {
                    // Query the autocomplete API for the (constraint) search string.
                    filterData = getAutocomplete(constraint)
                }

                results.values = filterData
                if (filterData != null) {
                    results.count = filterData.size
                } else {
                    results.count = 0
                }

                return results
            }

            override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                if (results != null && results.count > 0) {
                    // The API returned at least one result, update the data.
                    resultList.clear()
                    resultList.addAll(results.values as ArrayList<AutocompletePrediction>)
                }

                notifyDataSetChanged()
            }

        }
    }

    /**
     * Submits an autocomplete query to the Places Geo Data Autocomplete API.
     * Results are returned as frozen AutocompletePrediction objects, ready to be cached.
     * Returns an empty list if no results were found.
     * Returns null if the API client is not available or the query did not complete
     * successfully.
     * This method MUST be called off the main UI thread, as it will block until data is returned
     * from the API, which may include a network request.
     *
     * @param constraint Autocomplete query string
     * @return Results from the autocomplete API or null if the query was not successful.
     * @see GeoDataClient.getAutocompletePredictions
     * @see AutocompletePrediction.freeze
     */
    private fun getAutocomplete(constraint: CharSequence): ArrayList<AutocompletePrediction>? {
        Timber.d("Starting autocomplete query for: " + constraint)

        val latLngBounds = LatLngBounds(LatLng(-34.041458, 150.790100), LatLng(-33.682247, 151.383362))

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        val results = geoDataClient.getAutocompletePredictions(constraint.toString(), latLngBounds, null)

        // This method should have been called off the main UI thread. Block and wait for at most
        // 60s for a result from the API.
        try {
            Tasks.await(results, 60, TimeUnit.SECONDS)
        } catch (e: ExecutionException) {
            Timber.e(e)
        } catch (e: InterruptedException) {
            Timber.e(e)
        } catch (e: TimeoutException) {
            Timber.e(e)
        }

        Timber.d("Query completed. Received " + results.result.count + " predictions.")

        return try {
            // Freeze the results immutable representation that can be stored safely.
            DataBufferUtils.freezeAndClose<AutocompletePrediction, AutocompletePrediction>(results.result)
        } catch (e: RuntimeExecutionException) {
            // If the query did not complete successfully return null
            Timber.e("Error getting autocomplete prediction API call", e)
            null
        }

    }
}

When I run the project in app configuration it works fine.

But when I run it in instantapp configuration it throws this:

D/PlacesAdapter: Starting autocomplete query for: is
E/GmsClient: unable to connect to service: com.google.android.gms.location.places.GeoDataApi on com.google.android.gms
E/PlacesAdapter: java.util.concurrent.ExecutionException: com.google.android.gms.common.api.ApiException: 17: API_NOT_CONNECTED
                     at com.google.android.gms.tasks.Tasks.zzc(Unknown Source:17)
                     at com.google.android.gms.tasks.Tasks.await(Unknown Source:53)
                     at net.epictimes.uvindex.autocomplete.PlacesAdapter.getAutocomplete(PlacesAdapter.kt:116)
                     at net.epictimes.uvindex.autocomplete.PlacesAdapter.access$getAutocomplete(PlacesAdapter.kt:25)
                     at net.epictimes.uvindex.autocomplete.PlacesAdapter$getFilter$1.performFiltering(PlacesAdapter.kt:64)
                     at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
                     at android.os.Handler.dispatchMessage(Handler.java:105)
                     at android.os.Looper.loop(Looper.java:164)
                     at android.os.HandlerThread.run(HandlerThread.java:65)
                  Caused by: com.google.android.gms.common.api.ApiException: 17: API_NOT_CONNECTED
                     at com.google.android.gms.common.internal.zzb.zzz(Unknown Source:14)
                     at com.google.android.gms.common.internal.zzbk.zzaa(Unknown Source:0)
                     at com.google.android.gms.common.internal.zzbl.zzs(Unknown Source:32)
                     at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source:46)
                     at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source:42)
                     at com.google.android.gms.common.api.internal.zzm.zzv(Unknown Source:17)
                     at com.google.android.gms.common.api.internal.zzc.zzt(Unknown Source:2)
                     at com.google.android.gms.common.api.internal.zzbr.zzx(Unknown Source:27)
                     at com.google.android.gms.common.api.internal.zzbp.handleMessage(Unknown Source:386)
                     at android.os.Handler.dispatchMessage(Handler.java:101)
                     at android.os.Looper.loop(Looper.java:164)
                     at android.os.HandlerThread.run(HandlerThread.java:65)
W/Filter: An exception occured during performFiltering()!
          com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 17: API_NOT_CONNECTED
              at com.google.android.gms.tasks.zzn.getResult(Unknown Source:14)
              at net.epictimes.uvindex.autocomplete.PlacesAdapter.getAutocomplete(PlacesAdapter.kt:123)
              at net.epictimes.uvindex.autocomplete.PlacesAdapter.access$getAutocomplete(PlacesAdapter.kt:25)
              at net.epictimes.uvindex.autocomplete.PlacesAdapter$getFilter$1.performFiltering(PlacesAdapter.kt:64)
              at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
              at android.os.Handler.dispatchMessage(Handler.java:105)
              at android.os.Looper.loop(Looper.java:164)
              at android.os.HandlerThread.run(HandlerThread.java:65)
           Caused by: com.google.android.gms.common.api.ApiException: 17: API_NOT_CONNECTED
              at com.google.android.gms.common.internal.zzb.zzz(Unknown Source:14)
              at com.google.android.gms.common.internal.zzbk.zzaa(Unknown Source:0)
              at com.google.android.gms.common.internal.zzbl.zzs(Unknown Source:32)
              at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source:46)
              at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source:42)
              at com.google.android.gms.common.api.internal.zzm.zzv(Unknown Source:17)
              at com.google.android.gms.common.api.internal.zzc.zzt(Unknown Source:2)
              at com.google.android.gms.common.api.internal.zzbr.zzx(Unknown Source:27)
              at com.google.android.gms.common.api.internal.zzbp.handleMessage(Unknown Source:386)
              at android.os.Handler.dispatchMessage(Handler.java:101)
              at android.os.Looper.loop(Looper.java:164)
              at android.os.HandlerThread.run(HandlerThread.java:65)

API_NOT_CONNECTED error code's explation in the docs:

The client attempted to call a method from an API that failed to
  connect. Possible reasons include:

The API previously failed to connect with a resolvable error, but the    user declined the resolution.

The device does not support GmsCore.

The specific API cannot connect on this device.

I updated the Google Play Services on the emulator (it's 11.7.46 (470-175121617) BTW) but it didn't changed anyting.

I put my Google Play Services dependencies into the base module. I checked the merged manifest files, they all have the Google Play API keys.

In the Android Developers site they listed Google Places API in the supported API list.

I am using Google Location API in the other feature module and it is working in both app and instantapp configurations.

So what am I doing wrong here?

Body:
I decided to connect the API using the GoogleApiClient:

GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Places.GEO_DATA_API)
                .build()
                .connect()

But the connection attempt failed with status code API_UNAVAILABLE in instantapp configuration.

In the docs, API_UNAVAILABLE means that the API is not available for Instant Apps:

When debugging an instant app that uses a Google Play services library
  other than those included in the list above, you may see the
  API_UNAVAILABLE error in your debugging output. The API_UNAVAILABLE
  error indicates that the library has not been adapted for usage in
  Android Instant Apps.

So I dropped the Places AutoComplete and continued with something similar like geocoding.