问:
Nativescript ListView Refresh
I need to update my ListView constantly but, for some reason, I couldn't identify yet, I haven't been successful doing so.

dash.xml

```<code><ListView id="pilotList" items="{{ activeList }}">
    <ListView.itemTemplate>
       <GridLayout columns="*,*2,*">
            <Label text="{{ listNick }}" col="1"  class="listNick" />
            <Label text="{{ listDistance }}" col="2" class="listDistance" />
       </GridLayout>
    </ListView.itemTemplate>
</ListView>
</code>```

dash.js (I am extracting just the related parts here):

```<code>var observable = require("data/observable");
var pageModule = require("ui/page");

var activePilots = []; //this is the array with the contents

exports.pageLoaded = function(args) {
    page = args.object;
    pilotList = page.getViewById("pilotList");
    page.bindingContext = { activeList:activePilots };
}
</code>```

Later on in the code (every time a location change), I update the activePilots array:

```<code>activePilots.push({listNick:fbMi, listDistance:result.value[uid]["uid"] })
</code>```

So far, everything is working as I can see with the console.log(JSON.stringify(activePilots)).

However, the ListView never updates, even forcing the

```<code>pilotList.refresh();
</code>```

Any ideas of what I am doing wrong?
Thanks,
Alex

答:
Few things that needed to be addressed.
In order to update values in your UI, you need to use an Observable model and data binding.
e.g.
page.js

```<code>var observable = require("data/observable");
var viewModel = new observable.Observable();
viewModel.set("activeList", [1,2,3]);
</code>```

page.xml

```<code><ListView items="{{ activeList }}">
    <ListView.itemTemplate>
       <GridLayout>
            <Label text="{{ $value}}"  />
       </GridLayout>
    </ListView.itemTemplate>
</ListView>
</code>```

Now notice that with this approach you will still not be able to update your list view items when using push for the array. The reason - the list itself is Observable but the property change will be triggered only if your change the whole array and won't be triggered when using arr.push.

To be able to update your list-view items when adding new items to your array you will need to use an ObservableArray
e.g.

```<code>var ObservableArray = require("data/observable-array").ObservableArray;
var viewModel = new observable.Observable();
viewModel.set("activeList", new ObservableArray ([1,2,3]));
</code>```

Now the array is observable meaning you can add new items on the fly and they will be rendered in your ListView. Demo application using Observable and Observable array can be found here - the application is written in TypeScript - just execute tns run android and the respective JavaScript files will be created after the transpilation.

Title: Nativescript ListView Refresh

Body:
I need to update my ListView constantly but, for some reason, I couldn't identify yet, I haven't been successful doing so.

dash.xml

<ListView id="pilotList" items="{{ activeList }}">
    <ListView.itemTemplate>
       <GridLayout columns="*,*2,*">

       </GridLayout>
    </ListView.itemTemplate>
</ListView>

dash.js (I am extracting just the related parts here):

var observable = require("data/observable");
var pageModule = require("ui/page");

var activePilots = []; //this is the array with the contents

exports.pageLoaded = function(args) {
    page = args.object;
    pilotList = page.getViewById("pilotList");
    page.bindingContext = { activeList:activePilots };
}

Later on in the code (every time a location change), I update the activePilots array:

activePilots.push({listNick:fbMi, listDistance:result.value[uid]["uid"] })

So far, everything is working as I can see with the console.log(JSON.stringify(activePilots)).

However, the ListView never updates, even forcing the

pilotList.refresh();

Any ideas of what I am doing wrong?
Thanks,
Alex

Body:
Few things that needed to be addressed.
In order to update values in your UI, you need to use an Observable model and data binding.
e.g.
page.js

var observable = require("data/observable");
var viewModel = new observable.Observable();
viewModel.set("activeList", [1,2,3]);

page.xml

<ListView items="{{ activeList }}">
    <ListView.itemTemplate>
       <GridLayout>
            <Label text="{{ $value}}"  />
       </GridLayout>
    </ListView.itemTemplate>
</ListView>

Now notice that with this approach you will still not be able to update your list view items when using push for the array. The reason - the list itself is Observable but the property change will be triggered only if your change the whole array and won't be triggered when using arr.push.

To be able to update your list-view items when adding new items to your array you will need to use an ObservableArray
e.g.

var ObservableArray = require("data/observable-array").ObservableArray;
var viewModel = new observable.Observable();
viewModel.set("activeList", new ObservableArray ([1,2,3]));

Now the array is observable meaning you can add new items on the fly and they will be rendered in your ListView. Demo application using Observable and Observable array can be found here - the application is written in TypeScript - just execute tns run android and the respective JavaScript files will be created after the transpilation.


来源: stackexchange

问:
Why min({1},{0}) returns {1}
min() function should return the smallest of the numbers given. Then why

```<code>min({0},{1})
</code>```

returns {0}, while

```<code>min({1},{0})
</code>```

returns {1}?

答:
The comparison operators for sets check for "subset" not for numerical comparisons:

set < other

Test whether the set is a proper subset of other, that is, set <= other and set != other.

And both your sets are disjoint so {0} < {1} == False and {1} < {0} == False so it will always return the "first" set you put into min.

ContentLicense: CC BY-SA 3.0

Title: Why min({1},{0}) returns {1}

Body:
min() function should return the smallest of the numbers given. Then why

min({0},{1})

returns {0}, while

min({1},{0})

returns {1}?


问:
angularjs ng-options with one element in array
I'm working on angularjs app, and I can't find the answer for simple question. I've got an select with ng-options, when array that is set for options has more then one object inside the select is empty on start, but when array has only one element it automatically set it as default value. I need this select to be empty at the begining all the time, is there any solution?</p>

答:
in angularJS you may separate the variable used to fill in your options values and the model that stores your selected value.

See that example :

```<code>       //Model used to store selected values
        <select class="form-control" ng-model="myModel.country">
            //I have a $scope.countries array of country
            <option ng-repeat="country in countries" ng-value="country" required>{{country.name}}</option>

        </select>
</code>```

Body:
in angularJS you may separate the variable used to fill in your options values and the model that stores your selected value.

See that example :

       //Model used to store selected values
        <select class="form-control" ng-model="myModel.country">
            //I have a $scope.countries array of country
            <option ng-repeat="country in countries" ng-value="country" required>{{country.name}}</option>

        </select>


问:
Android : How to dynamically add selected Document to imageview as a Preview/Thumbnail Inside a Gridview
I have an android application where I need to implement a Gridview which contains an imageview and a TextView, also have a button to add new view to the gridview.When i click on this button a file chooser will come and can select any document like pdf,docs,images,etc from my device.Then i want to display this document as an image in the gridview with its name.How can i do that?This is exactly the same like if we got a mail with attachments(images,pdf,docs,..), then we can see it as images when we open that mail.That is we can see a preview image of that document before we click on each document as below.I need exactly the same feature in my gridview.

Below is the code that i had used to display the file chooser.

```<code>Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    try {
        startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"),FILE_SELECT_CODE);
    } catch (Exception ex) {
        System.out.println("browseClick :"+ex);
    }
</code>```

And i have implemented the

```<code>onActivityResult(int requestCode, int resultCode, Intent data){}
</code>```

to do the work after selecting the file.After so much of research i got a method to create the thumbnail of a video file as below.

```<code>ThumbnailUtils.createVideoThumbnail(filePath, kind);
</code>```

But didn't find anything to get the thumbnail of other documents.

I don't know how to show documents in gridview like images.Please help me.

答:
There is PdfRenderer library for ".pdf" files.

Android document is here, PDF Renderer Library. Unfortunately, this library added API 21.

There is nice example for this library Create and Display PDF within Android Application

This code in this website. You can create thumbnail with this code.

```<code>    @TargetApi( Build.VERSION_CODES.LOLLIPOP )
    private void generateImageFromPdf(String filePath) {

// filePath must be like : Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+"/42080.pdf"

        File file = new File(filePath);
// FileDescriptor for file, it allows you to close file when you are
// done with it
        ParcelFileDescriptor mFileDescriptor = null;
        try {
            mFileDescriptor = ParcelFileDescriptor.open(file,
                    ParcelFileDescriptor.MODE_READ_ONLY);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
// PdfRenderer enables rendering a PDF document
        PdfRenderer mPdfRenderer = null;
        try {
            mPdfRenderer = new PdfRenderer(mFileDescriptor);
        } catch (IOException e) {
            e.printStackTrace();
        }

// Open page with specified index
        PdfRenderer.Page mCurrentPage = mPdfRenderer.openPage(0);
        Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(),
                mCurrentPage.getHeight(), Bitmap.Config.ARGB_8888);

// Pdf page is rendered on Bitmap
        mCurrentPage.render(bitmap, null, null,
                PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// Set rendered bitmap to ImageView (pdfView in my case)
        ImageView pdfView = (ImageView) findViewById( R.id.bitmap );
        pdfView.setImageBitmap(bitmap);

        mCurrentPage.close();
        mPdfRenderer.close();
        try {
            mFileDescriptor.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

Body:
I have an android application where I need to implement a Gridview which contains an imageview and a TextView, also have a button to add new view to the gridview.When i click on this button a file chooser will come and can select any document like pdf,docs,images,etc from my device.Then i want to display this document as an image in the gridview with its name.How can i do that?This is exactly the same like if we got a mail with attachments(images,pdf,docs,..), then we can see it as images when we open that mail.That is we can see a preview image of that document before we click on each document as below.I need exactly the same feature in my gridview.

Below is the code that i had used to display the file chooser.

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    try {
        startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"),FILE_SELECT_CODE);
    } catch (Exception ex) {
        System.out.println("browseClick :"+ex);
    }

And i have implemented the

onActivityResult(int requestCode, int resultCode, Intent data){}

to do the work after selecting the file.After so much of research i got a method to create the thumbnail of a video file as below.

ThumbnailUtils.createVideoThumbnail(filePath, kind);

But didn't find anything to get the thumbnail of other documents.

I don't know how to show documents in gridview like images.Please help me.

Body:
There is PdfRenderer library for ".pdf" files.

Android document is here, PDF Renderer Library. Unfortunately, this library added API 21.

There is nice example for this library Create and Display PDF within Android Application

This code in this website. You can create thumbnail with this code.

    @TargetApi( Build.VERSION_CODES.LOLLIPOP )
    private void generateImageFromPdf(String filePath) {

// filePath must be like : Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+"/42080.pdf"

        File file = new File(filePath);
// FileDescriptor for file, it allows you to close file when you are
// done with it
        ParcelFileDescriptor mFileDescriptor = null;
        try {
            mFileDescriptor = ParcelFileDescriptor.open(file,
                    ParcelFileDescriptor.MODE_READ_ONLY);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
// PdfRenderer enables rendering a PDF document
        PdfRenderer mPdfRenderer = null;
        try {
            mPdfRenderer = new PdfRenderer(mFileDescriptor);
        } catch (IOException e) {
            e.printStackTrace();
        }

// Open page with specified index
        PdfRenderer.Page mCurrentPage = mPdfRenderer.openPage(0);
        Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(),
                mCurrentPage.getHeight(), Bitmap.Config.ARGB_8888);

// Pdf page is rendered on Bitmap
        mCurrentPage.render(bitmap, null, null,
                PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// Set rendered bitmap to ImageView (pdfView in my case)
        ImageView pdfView = (ImageView) findViewById( R.id.bitmap );
        pdfView.setImageBitmap(bitmap);

        mCurrentPage.close();
        mPdfRenderer.close();
        try {
            mFileDescriptor.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


问:
ERR: pom.xml Unknown lifecycle phase "package;"
```<code>[ERROR] Unknown lifecycle phase "package;". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
</code>```

Pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.socgen.portfolio</groupId>
<artifactId>portfolio</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
    <module>ui</module>
    <module>service</module>
</modules>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.8.RELEASE</version>
</parent>
</code>```

POM.xml[UI]

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.socgen.portfolio</groupId>
<artifactId>ui</artifactId>

<parent>
    <groupId>com.socgen.portfolio</groupId>
    <artifactId>portfolio</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
    <!-- https://mvnrepository.com/artifact/org.webjars/d3js -->
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>d3js</artifactId>
        <version>4.2.1</version>
    </dependency>
</dependencies>
</code>```

POM.xml[Service]

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.socgen.portfolio</groupId>
<artifactId>service</artifactId>
<packaging>war</packaging>

<parent>
    <groupId>com.socgen.portfolio</groupId>
    <artifactId>portfolio</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

Im not able to import the dependencies can someone help me in this?
and not even to import any of the modules its giving the above mentioned error while importing the dependencies.

答:
Dont use a semicolon.

It looks like you called mvn package; instead of mvn package

Body:
[ERROR] Unknown lifecycle phase "package;". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.socgen.portfolio</groupId>
<artifactId>portfolio</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
    <module>ui</module>
    <module>service</module>
</modules>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.8.RELEASE</version>
</parent>

POM.xml[UI]

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.socgen.portfolio</groupId>
<artifactId>ui</artifactId>

<parent>
    <groupId>com.socgen.portfolio</groupId>
    <artifactId>portfolio</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>
<dependencies>

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>d3js</artifactId>
        <version>4.2.1</version>
    </dependency>
</dependencies>

POM.xml[Service]

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.socgen.portfolio</groupId>
<artifactId>service</artifactId>
<packaging>war</packaging>

<parent>
    <groupId>com.socgen.portfolio</groupId>
    <artifactId>portfolio</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Im not able to import the dependencies can someone help me in this?
and not even to import any of the modules its giving the above mentioned error while importing the dependencies.


问:
Using while loop to repeat a function that generates random numbers
I am having trouble when using a while loop to repeat a function.

I am not an American student so please be understanding of my English.
I have no clue of what is going wrong and hope I can get some help.
I am aware that I can append the random number in the function and return it.

The question is:

There is a dice with 5 sides and each side says a , b , c , d ,e. If I get a d or an e, I throw again and I log this until I get an a,b or a c. ex) if I throw the dice 5times I can get: d, e, d, d, a or something like this. In my program, I want to simulate this process. I want it so that the function randomnumbers can generate random numbers from 0~4. I want the main program to loop the process of getting random numbers via this function(mandatory). Then, I want the main program to retrieve these values and use it to determine what these numbers mean(0=a, 1=b, 2=c, 3=d, 4=e) on the dice and append them to a separate list. Finally I want to print the values in the list where I logged the values I got.

I specifically have to do the following:

The function should only return one random number, not a list

The main program should be responsible for making a list and printing the value retrieved from the function.

```<code>def randomnumbers():
    r = 0
    import random
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while randomnumbers()>=3:
    List.append(abc[randomnumbers()])

for i in List:
    print i
</code>```

答:
As I mentioned in the comment, you really don't need a randomnumbers function for this task. You can just call random.randrange directly. But I guess this is a homework task, and it's mandatory for you to have a randomnumbers function, so I've simplified it.

You also say that you want the while loop to run while the random number is greater than or equal to 3, and that you expect the list to contain at least one letter. That means you need to test the value of the random number after you use it to select a letter from abc and add the letter to the list. You can do that like this:

```<code>import random

def randomnumbers():
    return random.randrange(5)

abc = ["a", "b", "c", "d", "e"]

lst = []
while True:
    r = randomnumbers()
    lst.append(abc[r])
    if r < 3:
        break

for i in lst:
    print(i)
</code>```

This code runs correctly on both Python 2 and Python 3.

I changed the name of your output list to lst. According to the PEP-0008 style guide variable names should be all lower-case, names that are Capitalized or CamelCase are used for class names.

FWIW, here's a slightly more "Pythonic" way to write that loop:

```<code>lst = []
while True:
    lst.append(random.choice("abcde"))
    if lst[-1] < "d":
        break
</code>```

Body:
I am having trouble when using a while loop to repeat a function.

I am not an American student so please be understanding of my English.
I have no clue of what is going wrong and hope I can get some help.
I am aware that I can append the random number in the function and return it.

The question is:

There is a dice with 5 sides and each side says a , b , c , d ,e. If I get a d or an e, I throw again and I log this until I get an a,b or a c. ex) if I throw the dice 5times I can get: d, e, d, d, a or something like this. In my program, I want to simulate this process. I want it so that the function randomnumbers can generate random numbers from 0~4. I want the main program to loop the process of getting random numbers via this function(mandatory). Then, I want the main program to retrieve these values and use it to determine what these numbers mean(0=a, 1=b, 2=c, 3=d, 4=e) on the dice and append them to a separate list. Finally I want to print the values in the list where I logged the values I got.

I specifically have to do the following:

The function should only return one random number, not a list

The main program should be responsible for making a list and printing the value retrieved from the function.

def randomnumbers():
    r = 0
    import random
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while randomnumbers()>=3:
    List.append(abc[randomnumbers()])

for i in List:
    print i

Body:
As I mentioned in the comment, you really don't need a randomnumbers function for this task. You can just call random.randrange directly. But I guess this is a homework task, and it's mandatory for you to have a randomnumbers function, so I've simplified it.

You also say that you want the while loop to run while the random number is greater than or equal to 3, and that you expect the list to contain at least one letter. That means you need to test the value of the random number after you use it to select a letter from abc and add the letter to the list. You can do that like this:

import random

def randomnumbers():
    return random.randrange(5)

abc = ["a", "b", "c", "d", "e"]

lst = []
while True:
    r = randomnumbers()
    lst.append(abc[r])
    if r < 3:
        break

for i in lst:
    print(i)

This code runs correctly on both Python 2 and Python 3.

I changed the name of your output list to lst. According to the PEP-0008 style guide variable names should be all lower-case, names that are Capitalized or CamelCase are used for class names.

FWIW, here's a slightly more "Pythonic" way to write that loop:

lst = []
while True:
    lst.append(random.choice("abcde"))
    if lst[-1] < "d":
        break


问:
Json to url with php
In my $output there is this:

```<code>{
  "status" : "success",
  "data" : {
    "network" : "BTC",
    "addresses" : [
      {
        "user_id" : 0,
        "address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
        "label" : "default",
        "available_balance" : "0.00000000",
        "pending_received_balance" : "0.00000000"
      }
    ]
  }
}
</code>```

But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC

etc. etc.

But $output can change to like:

```<code>{
  "status" : "success",
  "data" : {
    "network" : "BTC",
    "available_balance" : "0.00000000",
    "pending_received_balance" : "0.00000000"
  }
}
</code>```

But then I still want it to work.
I don't know PHP enough for this, so I want to ask:

How to do this?

答:
Simply json_decode() and access the status and network properties:

```<code>$decoded = json_decode($output);
header('Location: https://example.com/index.php?status=' . urlencode($decoded->status) . '&network=' . urlencode($decoded->data->network));
exit();
</code>```

Title: Json to url with php

Body:
In my $output there is this:

{
  "status" : "success",
  "data" : {
    "network" : "BTC",
    "addresses" : [
      {
        "user_id" : 0,
        "address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
        "label" : "default",
        "available_balance" : "0.00000000",
        "pending_received_balance" : "0.00000000"
      }
    ]
  }
}

But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC

etc. etc.

But $output can change to like:

{
  "status" : "success",
  "data" : {
    "network" : "BTC",
    "available_balance" : "0.00000000",
    "pending_received_balance" : "0.00000000"
  }
}

But then I still want it to work.
I don't know PHP enough for this, so I want to ask:

How to do this?

Body:
Simply json_decode() and access the status and network properties:

$decoded = json_decode($output);
header('Location: https://example.com/index.php?status=' . urlencode($decoded->status) . '&network=' . urlencode($decoded->data->network));
exit();


问:
How to keep rotating a FontAwesome-icon in Processing?
I'd like to keep rotating a icon from FontAwesome in Processing java. (the fa-spin icon to be precisely.) (\f110)

Link to effect: Example

My create-function for an icon

```<code>public void drawIcon(int size, String icon, float custom_height) {

    font = createFont("fontawesome-webfont.ttf",size);
    textFont(font);
    if(icon != null && !icon.trim().isEmpty()) {
        text(icon, width / 2, height / custom_height);
    }

}
</code>```

Initialization object + called method

To create my icon, I initialized an object and called my function in the draw()-method  :

```<code>Content content = new Content(); // content object
PFont font;  // font object

public void draw() {
     content.drawIcon(46, "\uf110", 7);
}
</code>```

I found the rotate/translate methods from the documentation, but can't figure out the correct parameters for rotating this icon 360 degrees continiously.

Attempt

```<code>public void draw() {
     rotate(degrees(360));
     content.drawIcon(46, "\uf110", 7);
}
</code>```

答:
I recommended loading the font once in setup() rather than potentially multiple times a second in drawIcon().

You can simply use text() after you've loaded the font and called textFont().

e.g.

```<code>PFont font;  // font object

public void setup() {
     font = loadFont("fontawesome-webfont.ttf",46);
    textFont(font);
}

public void drawIcon(String icon, float custom_height) {

    if(icon != null && !icon.trim().isEmpty()) {
        text(icon, width / 2, height / custom_height);
    }

}
</code>```

In terms of rotating, at the moment you're specifying the same angle continuously. What you probably want to do is create a variable to keep track of the current angle, increment the angle and pass that to rotate() in draw().

```<code>PFont font;  // font object
int angle = 0;

public void setup() {
     font = loadFont("fontawesome-webfont.ttf",46);
    textFont(font);
}

public void drawIcon(String icon, float custom_height) {

    if(icon != null && !icon.trim().isEmpty()) {
        text(icon, width / 2, height / custom_height);
    }

}

public void draw() {
//increment angle (angle++; would to the same, but hopefully expanded version is easier to read)
     angle = angle + 1;
     rotate(degrees(angle));
     content.drawIcon("\uf110", 7);
}
</code>```

Be sure to checkout the Rotate Processing example as well.

You may notice that the symbol might not rotate from the centre.
This will require you to use multiple coordinate spaces using pushMatrix();/popMatrix(); calls. Do read the 2D transformations tutorial for more info on how to do that.

Body:
I'd like to keep rotating a icon from FontAwesome in Processing java. (the fa-spin icon to be precisely.) (\f110)

Link to effect: Example

My create-function for an icon

public void drawIcon(int size, String icon, float custom_height) {

    font = createFont("fontawesome-webfont.ttf",size);
    textFont(font);
    if(icon != null && !icon.trim().isEmpty()) {
        text(icon, width / 2, height / custom_height);
    }

}

Initialization object + called method

To create my icon, I initialized an object and called my function in the draw()-method  :

Content content = new Content(); // content object
PFont font;  // font object

public void draw() {
     content.drawIcon(46, "\uf110", 7);
}

I found the rotate/translate methods from the documentation, but can't figure out the correct parameters for rotating this icon 360 degrees continiously.

Attempt

public void draw() {
     rotate(degrees(360));
     content.drawIcon(46, "\uf110", 7);
}

Body:
I recommended loading the font once in setup() rather than potentially multiple times a second in drawIcon().

You can simply use text() after you've loaded the font and called textFont().

e.g.

PFont font;  // font object

public void setup() {
     font = loadFont("fontawesome-webfont.ttf",46);
    textFont(font);
}

public void drawIcon(String icon, float custom_height) {

    if(icon != null && !icon.trim().isEmpty()) {
        text(icon, width / 2, height / custom_height);
    }

}

In terms of rotating, at the moment you're specifying the same angle continuously. What you probably want to do is create a variable to keep track of the current angle, increment the angle and pass that to rotate() in draw().

PFont font;  // font object
int angle = 0;

public void setup() {
     font = loadFont("fontawesome-webfont.ttf",46);
    textFont(font);
}

public void drawIcon(String icon, float custom_height) {

    if(icon != null && !icon.trim().isEmpty()) {
        text(icon, width / 2, height / custom_height);
    }

}

public void draw() {
//increment angle (angle++; would to the same, but hopefully expanded version is easier to read)
     angle = angle + 1;
     rotate(degrees(angle));
     content.drawIcon("\uf110", 7);
}

Be sure to checkout the Rotate Processing example as well.

You may notice that the symbol might not rotate from the centre.
This will require you to use multiple coordinate spaces using pushMatrix();/popMatrix(); calls. Do read the 2D transformations tutorial for more info on how to do that.


问:
Force Umbraco to use https for back office and http for all other requests
I am trying to configure Umbraco so all requests to the back office (www.mydomain.com/umbraco) get redirected to https and all non-backoffice requests are forwarded to http.

I can easily get the back office to use SSL by setting this web config appsetting key:

```<code><add key="umbracoUseSSL" value="false" />
</code>```

However, I am struggling to get all other pages to force http. The certificate is self signed so I don't want end users getting SSL errors. I have tried this rewrite rule in the web.config, but it has no impact.

```<code><rule name="No-https" enabled="true" stopProcessing="true">
   <match url=".*" negate="false" />
   <conditions>
      <add input="{HTTPS}" pattern="on" />
      <add input="{URL}" pattern="umbraco" negate="true" />
   </conditions>
   <action type="Redirect" url="http://{HTTP_HOST}{REQUEST_URI}" />
</rule>
</code>```

My aim is that any request to https://www.mydomain.com is redirected to http://www.mydomain.com unless it matches the folder /umbraco.

If I have this rule, all http requests are redirected to https:

```<code><rule name="Redirect to HTTPS" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
      <add input="{HTTPS}" pattern="^OFF$" />
   </conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</code>```

But when I negate the rule, it no longer has any effect?

```<code><rule name="Redirect to HTTP" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
      <add input="{HTTPS}" pattern="^OFF$" negate="true" />
   </conditions>
   <action type="Redirect" url="http://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</code>```

Update. It looks like it isn't possible to process the redirect because the browser is giving the https error before the rewrite rule runs? Redirect from https to http when the SSL cert is no longer valid. Is there any way to redirect to http when using a self signed certificate?

答:
I would recommend looking into making /umbraco/ unavailable on your site, and making it HTTP only.

I would then setup a different site, perhaps umbraco.yoursite.domain which does require SSL and allowing that address to access Umbraco.

Also, have you considered using LetsEncrypt to get a proper SSL certificate for your site?

Body:
I am trying to configure Umbraco so all requests to the back office (www.mydomain.com/umbraco) get redirected to https and all non-backoffice requests are forwarded to http.

I can easily get the back office to use SSL by setting this web config appsetting key:

<add key="umbracoUseSSL" value="false" />

However, I am struggling to get all other pages to force http. The certificate is self signed so I don't want end users getting SSL errors. I have tried this rewrite rule in the web.config, but it has no impact.

<rule name="No-https" enabled="true" stopProcessing="true">
   <match url=".*" negate="false" />
   <conditions>
      <add input="{HTTPS}" pattern="on" />
      <add input="{URL}" pattern="umbraco" negate="true" />
   </conditions>
   <action type="Redirect" url="http://{HTTP_HOST}{REQUEST_URI}" />
</rule>

My aim is that any request to https://www.mydomain.com is redirected to http://www.mydomain.com unless it matches the folder /umbraco.

If I have this rule, all http requests are redirected to https:

<rule name="Redirect to HTTPS" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
      <add input="{HTTPS}" pattern="^OFF$" />
   </conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>

But when I negate the rule, it no longer has any effect?

<rule name="Redirect to HTTP" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
      <add input="{HTTPS}" pattern="^OFF$" negate="true" />
   </conditions>
   <action type="Redirect" url="http://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>

Update. It looks like it isn't possible to process the redirect because the browser is giving the https error before the rewrite rule runs? Redirect from https to http when the SSL cert is no longer valid. Is there any way to redirect to http when using a self signed certificate?


问:
iOS - Set CollectionView Header with dynamic height
I have a collection view with a Header and no cells.

I've set the header size to be equal to the superview bounds as following:

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}
</code>```

This header has a UITextView in it, which is anchored, as well, to the headers bounds (topAnchor, leftAnchor, bottomAnchor and rightAnchor).

I need the header to be anchored to the collection view height when the keyboard is closed, but anchored to the top of the keyboard when this one is opened, changing its size respectively.

The problem here lies when the text of the headers UITextView subview keeps growing and the text goes behind the keyboard.

Here's a GIF showing what's happening.
The yellow view is the Header
The white view is the TextView with some padding.

When I pass the keyboard the text goes behind it - if I could anchor the header to the bottom of the screen when there's no keyboard and to the bottom of the keyboard when its shown would be great.

Any hint?
Thanks

EDIT ADICIONAL INFO

As @Aravind said I've implemented the Notification listener to fire whenever the keyboard shows or hides.

Since I'm using the UITextView inside the Header class as its subview I've implemented the following:

This is an helper function to anchor my views easily:

```<code>extension UIView {
func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddinfLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat) {
    translatesAutoresizingMaskIntoConstraints = false
    if let top = top {
        topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
    }
    if let left = left {
        leftAnchor.constraint(equalTo: left, constant: paddinfLeft).isActive = true
    }
    if let bottom = bottom {
        bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
    }
    if let right = right {
        rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
    }
    if width != 0 {
        widthAnchor.constraint(equalToConstant: width).isActive = true
    }
    if height != 0 {
        heightAnchor.constraint(equalToConstant: height).isActive = true
    }
}
}

override init(frame: CGRect) {
    super.init(frame: frame)

    addSubview(inputTextView)
    inputTextView.delegate = self

    inputTextView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddinfLeft: 12, paddingBottom: 0, paddingRight: 12, width: 0, height: 0)

    setupInputTextViewToolbar()

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(keyboardWillShow(_:)),
        name: NSNotification.Name.UIKeyboardWillShow,
        object: nil)

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(keyboardWillHide(_:)),
        name: NSNotification.Name.UIKeyboardWillHide,
        object: nil)
}
</code>```

Then the Show/Hide functions

```<code>func keyboardWillShow(_ sender:NSNotification){
    guard let keyboardSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return }
    inputTextView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddinfLeft: 12, paddingBottom: keyboardSize.height, paddingRight: 12, width: 0, height: 0)
}

func keyboardWillHide(_ sender:NSNotification){
        self.inputTextView.anchor(top: self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, paddingTop: 0, paddinfLeft: 12, paddingBottom: 0, paddingRight: 12, width: 0, height: 0)
}
</code>```

The show function works properly and makes the text view to the remaining screen size so it doesn't stay behind the keyboard, so far so good.

But when I fire the hide function it doesn't resize again to the bottom of the screen.

What maybe causing this?

答:
Here make an outlet of the textView's bottom constraint and change its value when keyboard shows up and when it hides like,</p>

```<code>    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillShow(_:)),
            name: NSNotification.Name.UIKeyboardWillShow,
            object: nil)
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillHide(_:)),
            name: NSNotification.Name.UIKeyboardWillHide,
            object: nil)

}

   func keyboardWillShow(_ sender:NSNotification){

        let keyboardSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
        bottomSpace.constant = (keyboardSize?.height)!

    }
    func keyboardWillHide(_ sender:NSNotification){
    bottomSpace.constant = 0
   }
</code>```

Body:
I have a collection view with a Header and no cells.

I've set the header size to be equal to the superview bounds as following:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}

This header has a UITextView in it, which is anchored, as well, to the headers bounds (topAnchor, leftAnchor, bottomAnchor and rightAnchor).

I need the header to be anchored to the collection view height when the keyboard is closed, but anchored to the top of the keyboard when this one is opened, changing its size respectively.

The problem here lies when the text of the headers UITextView subview keeps growing and the text goes behind the keyboard.

Here's a GIF showing what's happening.
The yellow view is the Header
The white view is the TextView with some padding.

When I pass the keyboard the text goes behind it - if I could anchor the header to the bottom of the screen when there's no keyboard and to the bottom of the keyboard when its shown would be great.

Any hint?
Thanks

EDIT ADICIONAL INFO

As @Aravind said I've implemented the Notification listener to fire whenever the keyboard shows or hides.

Since I'm using the UITextView inside the Header class as its subview I've implemented the following:

This is an helper function to anchor my views easily:

extension UIView {
func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddinfLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat) {
    translatesAutoresizingMaskIntoConstraints = false
    if let top = top {
        topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
    }
    if let left = left {
        leftAnchor.constraint(equalTo: left, constant: paddinfLeft).isActive = true
    }
    if let bottom = bottom {
        bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
    }
    if let right = right {
        rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
    }
    if width != 0 {
        widthAnchor.constraint(equalToConstant: width).isActive = true
    }
    if height != 0 {
        heightAnchor.constraint(equalToConstant: height).isActive = true
    }
}
}

override init(frame: CGRect) {
    super.init(frame: frame)

    addSubview(inputTextView)
    inputTextView.delegate = self

    inputTextView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddinfLeft: 12, paddingBottom: 0, paddingRight: 12, width: 0, height: 0)

    setupInputTextViewToolbar()

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(keyboardWillShow(_:)),
        name: NSNotification.Name.UIKeyboardWillShow,
        object: nil)

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(keyboardWillHide(_:)),
        name: NSNotification.Name.UIKeyboardWillHide,
        object: nil)
}

Then the Show/Hide functions

func keyboardWillShow(_ sender:NSNotification){
    guard let keyboardSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return }
    inputTextView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddinfLeft: 12, paddingBottom: keyboardSize.height, paddingRight: 12, width: 0, height: 0)
}

func keyboardWillHide(_ sender:NSNotification){
        self.inputTextView.anchor(top: self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, paddingTop: 0, paddinfLeft: 12, paddingBottom: 0, paddingRight: 12, width: 0, height: 0)
}

The show function works properly and makes the text view to the remaining screen size so it doesn't stay behind the keyboard, so far so good.

But when I fire the hide function it doesn't resize again to the bottom of the screen.

What maybe causing this?

Body:
Here make an outlet of the textView's bottom constraint and change its value when keyboard shows up and when it hides like,

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillShow(_:)),
            name: NSNotification.Name.UIKeyboardWillShow,
            object: nil)
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(keyboardWillHide(_:)),
            name: NSNotification.Name.UIKeyboardWillHide,
            object: nil)

}

   func keyboardWillShow(_ sender:NSNotification){

        let keyboardSize = (sender.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
        bottomSpace.constant = (keyboardSize?.height)!

    }
    func keyboardWillHide(_ sender:NSNotification){
    bottomSpace.constant = 0
   }


问:
Piecewise linear optimisation using matlab
I want to solve the following optimisation problem, whose objective function is independent of x:

minimise t

subject to a_i*x+b_i<=t

over x for all i from 1 to n=100

This problem arised from if I rewrite a piecewise linear optimisation problem to a linear optimisation problem.

Question:
How can I implement this in the matlab using linprog. In linprog I am asked to insert the objective function f as a matrix multiplying with x. Is it possible to have a objective function independent of x? If not, how am I going to implement this?

P.S: I don't know why Mathjax is not working here, I have been looking for how to ask questions with Math formula, but I was not successful. Therefore any correction is welcomed.

Edit:Here is the official document from Matlab for linprog. In it it is stated that the minimalising function has the shape of f^Tx. My problem is just that my minimalising function doesn't take such shape and is in the absence of x. How can I implement this in the Matlab?

答:
You need to reformulate your problem into standard LP, i.e. find the nominal f, A and b as required by MATLAB's function linprog.

Here is the reformulation. From your question it seems x and t are two scalars.

Assume the given a_i's and b_i's are stored in column vectors a and b respectively, then your original problem:

min t, s.t. a * x + b <= t * ones(n,1)

is equivalent to:

min [0; 1]' * [x; t], s.t. [a, ones(n,1)] * [x; t] <= -b.

Thus, just use linprog([0; 1], [a, ones(n,1)], -b), and the solution is [x; t].


问:
How to retrieve multiple blob images from database
Hi i am using Spring mvc and hibernate. I want to retrieve multiple blob images from database and want to display in jsp. I tried a lot but did not get fruitful answer. If anyone gives link or sample code then it would be great for me.</p>

答:
If you are already using spring you could also have a look at spring data and the data repositories (http://docs.spring.io/spring-data/commons/docs/current/reference/html/#repositories).

There are a lot examples out there how it should look in action :)

If you use the newest Version you can stream the results. With that you can load the images async if you have performance issues.


问:
Setting a type on specific property of a mapped type in TypeScript
I'm trying to create a type in TypeScript for something we are converting over from JavaScript.

Basically the type is a standard object literal where each child is a repeat of the same type. However if its the '_errors' property this should be an array of another type and is optional.

Is this possible in TypeScript?

This is sort of what I'm after but the syntax below is invalid.

```<code>// This is invalid but might demonstrate what I'm after...
type MyType = {
    _errors?: ErrorWrapper[]; // Anything using the key '_errors' should be an array of ErrorWrapper. But this should be optional.
    [key: string]: MyType; // Any other properties should be MyType.
 };

interface ErrorWrapper {
    message: string;
    mapped: boolean;
}
</code>```

In JavaScript the object looked like this:

```<code>let myObject = {
  property1: {
    property1a: {
       _errors: [{
          message: 'string message',
          mapped: false
       },{
          message: 'string message',
          mapped: false
       }]
    },
    property1b: {
       _errors: [{
          message: 'string message',
          mapped: false
      }]
    }
  },
  property2: {
       _errors: [{
          message: 'string message',
          mapped: false
      }]
  }
}
</code>```

答:
Maybe I'm wrong but I don't think this is possible today. I tried with:

```<code>interface ErrorWrapper {
    message: string;
    mapped: boolean;
}

type ErrorMap<T> = {
    [P in keyof T]: Partial<{ _errors: ErrorWrapper[] }> & ErrorMap<(Partial<T[P]>)>;
};

interface SomeObj {
    property1: {
        property1a: number;
        property1b: string;
    };
    property2: number;
}

declare let x: ErrorMap<SomeObj> ;

// Autocomplete works as expected
console.log(x.property1.property1a._errors);
console.log(x.property1.property1b._errors);
console.log(x.property2._errors);

// Error
let myObject: ErrorMap<SomeObj> =  {
  property1: {
    property1a: {
       _errors: [{
          message: "string message",
          mapped: false
       }, {
          message: "string message",
          mapped: false
       }]
    },
    property1b: {
       _errors: [{
          message: "string message",
          mapped: false
      }]
    }
  },
  property2: {
    _errors: [{
        message: "string message",
        mapped: false
    }]
  }
};
</code>```

I think we need a conditional in the mapped type but that feature is not available yet.

Body:
I'm trying to create a type in TypeScript for something we are converting over from JavaScript.

Basically the type is a standard object literal where each child is a repeat of the same type. However if its the '_errors' property this should be an array of another type and is optional.

Is this possible in TypeScript?

This is sort of what I'm after but the syntax below is invalid.

// This is invalid but might demonstrate what I'm after...
type MyType = {
    _errors?: ErrorWrapper[]; // Anything using the key '_errors' should be an array of ErrorWrapper. But this should be optional.
    [key: string]: MyType; // Any other properties should be MyType.
 };

interface ErrorWrapper {
    message: string;
    mapped: boolean;
}

In JavaScript the object looked like this:

let myObject = {
  property1: {
    property1a: {
       _errors: [{
          message: 'string message',
          mapped: false
       },{
          message: 'string message',
          mapped: false
       }]
    },
    property1b: {
       _errors: [{
          message: 'string message',
          mapped: false
      }]
    }
  },
  property2: {
       _errors: [{
          message: 'string message',
          mapped: false
      }]
  }
}

Body:
Maybe I'm wrong but I don't think this is possible today. I tried with:

interface ErrorWrapper {
    message: string;
    mapped: boolean;
}

type ErrorMap<T> = {
    [P in keyof T]: Partial<{ _errors: ErrorWrapper[] }> & ErrorMap<(Partial<T[P]>)>;
};

interface SomeObj {
    property1: {
        property1a: number;
        property1b: string;
    };
    property2: number;
}

declare let x: ErrorMap<SomeObj> ;

// Autocomplete works as expected
console.log(x.property1.property1a._errors);
console.log(x.property1.property1b._errors);
console.log(x.property2._errors);

// Error
let myObject: ErrorMap<SomeObj> =  {
  property1: {
    property1a: {
       _errors: [{
          message: "string message",
          mapped: false
       }, {
          message: "string message",
          mapped: false
       }]
    },
    property1b: {
       _errors: [{
          message: "string message",
          mapped: false
      }]
    }
  },
  property2: {
    _errors: [{
        message: "string message",
        mapped: false
    }]
  }
};

I think we need a conditional in the mapped type but that feature is not available yet.


问:
GET RESPONSE APDU Command
When I am tryi ng to get the response by using (A0 C0 00 00 1A)GET RESPONSE command,
I am getting
SCardTransmit Failed! (80100008) The data buffer to receive returned data is too small for the returned data.
HOW TO RESOLVE THIS ERROR?</p>

答: I don't know the framework you are using. I assume you use native WinSCard or PCSC Lite. When using SCardTransmit you have to make sure parameter pcbRecvLength is big enough for your response to fit in.

Title: GET RESPONSE APDU Command


问:
issue with filter binding with knockout.js
I'm new working with Knockout.js framework and I'm having the following error in my code, I'm building an application using Knockout.js, everything works fine except when I tried to create a dependentObservable.

This is the javascript code:

```<code>(function() {
  'use strict';

    console.log("This is my Application");

     var app = {
         mapElement: document.getElementById('map'),
         mapObj: map,
         locations : ko.observableArray([
            {id: 1, title: 'Holywood Theater', location: {lat: 43.098344, lng: -76.145697}},
            {id: 2, title: 'Mattydale Fire Department', location: {lat: 43.098172, lng: -76.142189}},
            {id: 3, title: 'Original Italian Pizza', location: {lat: 43.098854, lng:  -76.144700}},
            {id: 4, title: 'Roxboro Road Middle School', location: {lat: 43.101110, lng: -76.150901}},
            {id: 5, title: 'Big Lots', location: {lat: 43.101400, lng: -76.146985}},
            {id: 6, title: 'Camnel pub', location: {lat: 43.098670, lng: -76.145832}}
        ]),
        markers:[],
        textFilter: ko.observable(),
        filterLocations: ko.dependentObservable(function () {
                            return ko.utils.arrayFilter(app.locations(), function (loc) {
                                return loc.title().toLowerCase().includes(app.textFilter().toLowerCase());
                            });
                        })
     };

    ko.applyBindings(app);
})();
</code>```

The error in the chrome console is:

Uncaught TypeError: Cannot read property 'locations' of undefined

答:
When using object literal for viewmodels, you should define your computed/dependent observables as

```<code>app.filterLocations = ko.computed(function () {
                        return ko.utils.arrayFilter(this.locations(), function (loc) {
                            return loc.title.toLowerCase().includes(app.textFilter().toLowerCase());
                        });
                    }, app);
</code>```

Notice passing of app object as second parameter to computed function that defines scope for this.

Also use computed instead of dependentObservable.

Computed Observables

Body:
I'm new working with Knockout.js framework and I'm having the following error in my code, I'm building an application using Knockout.js, everything works fine except when I tried to create a dependentObservable.

This is the javascript code:

(function() {
  'use strict';

    console.log("This is my Application");

     var app = {
         mapElement: document.getElementById('map'),
         mapObj: map,
         locations : ko.observableArray([
            {id: 1, title: 'Holywood Theater', location: {lat: 43.098344, lng: -76.145697}},
            {id: 2, title: 'Mattydale Fire Department', location: {lat: 43.098172, lng: -76.142189}},
            {id: 3, title: 'Original Italian Pizza', location: {lat: 43.098854, lng:  -76.144700}},
            {id: 4, title: 'Roxboro Road Middle School', location: {lat: 43.101110, lng: -76.150901}},
            {id: 5, title: 'Big Lots', location: {lat: 43.101400, lng: -76.146985}},
            {id: 6, title: 'Camnel pub', location: {lat: 43.098670, lng: -76.145832}}
        ]),
        markers:[],
        textFilter: ko.observable(),
        filterLocations: ko.dependentObservable(function () {
                            return ko.utils.arrayFilter(app.locations(), function (loc) {
                                return loc.title().toLowerCase().includes(app.textFilter().toLowerCase());
                            });
                        })
     };

    ko.applyBindings(app);
})();

The error in the chrome console is:

Uncaught TypeError: Cannot read property 'locations' of undefined

Body:
When using object literal for viewmodels, you should define your computed/dependent observables as

app.filterLocations = ko.computed(function () {
                        return ko.utils.arrayFilter(this.locations(), function (loc) {
                            return loc.title.toLowerCase().includes(app.textFilter().toLowerCase());
                        });
                    }, app);

Notice passing of app object as second parameter to computed function that defines scope for this.

Also use computed instead of dependentObservable.

Computed Observables


问:
Defensive copy of a mutable collection in Kotlin data class
I want to have a data class accepting a read-only list:

```<code>data class Notebook(val notes: List<String>) {
}
</code>```

But it can accept MutableList as well, because it is a subtype of the List.

For example the following code modifies the passed in list:

```<code>fun main(args: Array<String>) {
    val notes = arrayListOf("One", "Two")
    val notebook = Notebook(notes)

    notes.add("Three")

    println(notebook)       // prints: Notebook(notes=[One, Two, Three])
}
</code>```

Is there a way how perform defensive copy of the passed in list in the data class?

答:
There is no way to override the assignment of a property declared in the primary constructor. If you need a custom assignment, you'll have to move it out of the constructor, but then you can no longer make your class a data class.

```<code>class Notebook(notes: List<String>) {
    val notes: List<String> = notes.toList()
}
</code>```

If you must keep it a data class, the only way I see for doing this is to use the init block to make the copy, but you'll have to make your property a var to be able to do this, since the first assignment of the property will happen automatically, and here you're modifying it afterwards.

```<code>data class Notebook(var notes: List<String>) {
    init {
        notes = notes.toList()
    }
}
</code>```

Body:
I want to have a data class accepting a read-only list:

data class Notebook(val notes: List<String>) {
}

But it can accept MutableList as well, because it is a subtype of the List.

For example the following code modifies the passed in list:

fun main(args: Array<String>) {
    val notes = arrayListOf("One", "Two")
    val notebook = Notebook(notes)

    notes.add("Three")

    println(notebook)       // prints: Notebook(notes=[One, Two, Three])
}

Is there a way how perform defensive copy of the passed in list in the data class?

Body:
There is no way to override the assignment of a property declared in the primary constructor. If you need a custom assignment, you'll have to move it out of the constructor, but then you can no longer make your class a data class.

class Notebook(notes: List<String>) {
    val notes: List<String> = notes.toList()
}

If you must keep it a data class, the only way I see for doing this is to use the init block to make the copy, but you'll have to make your property a var to be able to do this, since the first assignment of the property will happen automatically, and here you're modifying it afterwards.

data class Notebook(var notes: List<String>) {
    init {
        notes = notes.toList()
    }
}


问:
How to detect object property delete
Hey in my component template I iterate over object property.
The problem is when I delete one of them the template doesn't refresh.
How can I refresh them?
Object looks loke this:

```<code>{name:'david', year:12, parents:{mother:MotherObject,father:FatherObject}}
</code>```

And an object like this I delete in parents mother but the template doesn't refresh.
I use delete [propertyname] to delete property.

I tried zone.run() but nothing changes. Can anyone knows how can I force refresh template?

答:
Guess you are using Pipe(if not, let me know) to iterate over object properties, the reason is that angular triggers object instance for DetectChange, and  deleting properties of object won't change the original instance and this is why DetectChange won't fire.

you have to create a new instance when you delete some fields, here is one way using ES6 new feature:

```<code>obj = {...obj};  // copy obj with a new instance
</code>```

Add another way using Object.assign

```<code>obj = Object.assign({}, obj);
</code>```

Plunker demo

Title: How to detect object property delete

Body:
Hey in my component template I iterate over object property.
The problem is when I delete one of them the template doesn't refresh.
How can I refresh them?
Object looks loke this:

{name:'david', year:12, parents:{mother:MotherObject,father:FatherObject}}

And an object like this I delete in parents mother but the template doesn't refresh.
I use delete [propertyname] to delete property.

I tried zone.run() but nothing changes. Can anyone knows how can I force refresh template?

Body:
Guess you are using Pipe(if not, let me know) to iterate over object properties, the reason is that angular triggers object instance for DetectChange, and  deleting properties of object won't change the original instance and this is why DetectChange won't fire.

you have to create a new instance when you delete some fields, here is one way using ES6 new feature:

obj = {...obj};  // copy obj with a new instance

Add another way using Object.assign

obj = Object.assign({}, obj);

Plunker demo


问:
How can search results be cached?
How do I implement caching mechanism of search results as on stackoverflow?
How does elastic search and lucene deal with caching? </p>

答:
Warmers

Warmers have been removed. There have been significant improvements to the index that make warmers not necessary anymore.

in ElasticSearch 5.4+

Title: How can search results be cached?


问:
Run view in command
I have a view to download a file. I want to create a command to be able to call this view and download the file in a certain folder.

```<code>class DownloadFile(View):
    def get(self, request, pk):
        ...
</code>```

How can I run this view in a custom command and save the file locally?

答:
If you want to create a Django Management Command (and not a function), create a new python file under

"Your-Django-App -> management -> commands -> your_custom_command.py"

Then, create a Command class. You can define here where you want to download your files. Example:

```<code>class Command(BaseCommand):
    media_folder = os.getcwd() + '/media/'
    private_folder = os.getcwd() + '/private/'

def handle(self, *args, **options):
    # insert your code here
</code>```

You can execute this command from the terminal:

```<code>python manage.py your_custom_command
</code>```

Or you can execute it from your code. More information here on Django documentation: https://docs.djangoproject.com/en/1.11/ref/django-admin/#running-management-commands-from-your-code

Here you can read more about management commands:
https://docs.djangoproject.com/en/1.11/howto/custom-management-commands/

Title: Run view in command

Body:
I have a view to download a file. I want to create a command to be able to call this view and download the file in a certain folder.

class DownloadFile(View):
    def get(self, request, pk):
        ...

How can I run this view in a custom command and save the file locally?

Body:
If you want to create a Django Management Command (and not a function), create a new python file under

"Your-Django-App -> management -> commands -> your_custom_command.py"

Then, create a Command class. You can define here where you want to download your files. Example:

class Command(BaseCommand):
    media_folder = os.getcwd() + '/media/'
    private_folder = os.getcwd() + '/private/'

def handle(self, *args, **options):
    # insert your code here

You can execute this command from the terminal:

python manage.py your_custom_command

Or you can execute it from your code. More information here on Django documentation: https://docs.djangoproject.com/en/1.11/ref/django-admin/#running-management-commands-from-your-code

Here you can read more about management commands:
https://docs.djangoproject.com/en/1.11/howto/custom-management-commands/


答:
Get the data in the json as an array:

```<code>$url = 'https://example.com/index.php?status=' . $status;
foreach($data as $param->$value) {
    $url += '&' . $param . '=' . $value
}
header('Location:' $url);
</code>```

Been a while since i've worked in php but this should handle a varying amount of parameters.

Title: Json to url with php

Body:
In my $output there is this:

{
  "status" : "success",
  "data" : {
    "network" : "BTC",
    "addresses" : [
      {
        "user_id" : 0,
        "address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
        "label" : "default",
        "available_balance" : "0.00000000",
        "pending_received_balance" : "0.00000000"
      }
    ]
  }
}

But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC

etc. etc.

But $output can change to like:

{
  "status" : "success",
  "data" : {
    "network" : "BTC",
    "available_balance" : "0.00000000",
    "pending_received_balance" : "0.00000000"
  }
}

But then I still want it to work.
I don't know PHP enough for this, so I want to ask:

How to do this?

Body:
Get the data in the json as an array:

$url = 'https://example.com/index.php?status=' . $status;
foreach($data as $param->$value) {
    $url += '&' . $param . '=' . $value
}
header('Location:' $url);

Been a while since i've worked in php but this should handle a varying amount of parameters.


问:
Retrieving the MethodInfo of of the correct overload of a generic method
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

Here is my class definition:

```<code>public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}
</code>```

And this is what I've come up with, unfortunately without succes:

```<code>[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}
</code>```

How can I get the MethodInfo of a generic method of which I know the parameters?

答:
You'll struggle with just with just GetMethod - you could try something along the lines of;</p>

```<code>var method = (from m in typeof(Foo).GetMethods()
  where
    m.IsGenericMethodDefinition == true &&
    m.Name == "Bar" &&
    m.GetParameters().Length > 0 &&
    m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == parameterType
  select m).FirstOrDefault();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

Here is my class definition:

public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}

And this is what I've come up with, unfortunately without succes:

[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}

How can I get the MethodInfo of a generic method of which I know the parameters?

Body:
You'll struggle with just with just GetMethod - you could try something along the lines of;

var method = (from m in typeof(Foo).GetMethods()
  where
    m.IsGenericMethodDefinition == true &&
    m.Name == "Bar" &&
    m.GetParameters().Length > 0 &&
    m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == parameterType
  select m).FirstOrDefault();


问:
Mongoose connect throwing a warning
I am writing a mongodb connected app and while connecting to the server like bellow getting a warning like this:

Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

My codes are like bellow

```<code>import mongoose from 'mongoose';
import config from './config';
mongoose.connect(config.db.uri);
</code>```

at config.js

```<code>const config = {
    name: 'API',
    version: '0.0.1',
    env: process.env.NODE_ENV || 'development',
    port: process.env.PORT || 3000,
    base_url: process.env.BASE_URL || 'http://localhost:3000',
    db: {
        uri: 'mongodb://admin:harry123@127.0.0.1:27017/ai?authSource=admin',
    },
}

export default config;
</code>```

I am using Node v8.0.0 and mongoose 4.10.5

答: This is a harmless warning and a known mongoose issue. See the mongoose thread for details, but as of mongoose 4.10.5, there is no known workaround and it shouldn't affect your application's functionality.</p>

Title: Mongoose connect throwing a warning

Body:
I am writing a mongodb connected app and while connecting to the server like bellow getting a warning like this:

Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

My codes are like bellow

import mongoose from 'mongoose';
import config from './config';
mongoose.connect(config.db.uri);

at config.js

const config = {
    name: 'API',
    version: '0.0.1',
    env: process.env.NODE_ENV || 'development',
    port: process.env.PORT || 3000,
    base_url: process.env.BASE_URL || 'http://localhost:3000',
    db: {
        uri: 'mongodb://admin:harry123@127.0.0.1:27017/ai?authSource=admin',
    },
}

export default config;

I am using Node v8.0.0 and mongoose 4.10.5


问:
parsing xml data return empty value in php
i'm trying to parse data in xml with simple_load_string function in php and it's return an empty data in the $parsed (data parsed) .

the data to parse is like :

```<code><cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
    <cas:authenticationSuccess>
        <cas:user>yassine458</cas:user>
    </cas:authenticationSuccess>
</cas:serviceResponse>
</code>```

is that possible to parse data with this format or there is another method to do it .

this is my code :

```<code>$xml = simplexml_load_string($result);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$parsed= simplexml_load_string($result);
</code>```

i'm trying to convert it to json format

答:
```<code>$xml_string = file_get_contents('/path');
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
</code>```

Then you can use $json or $array as you want.

Body:
i'm trying to parse data in xml with simple_load_string function in php and it's return an empty data in the $parsed (data parsed) .

the data to parse is like :

<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
    <cas:authenticationSuccess>
        <cas:user>yassine458</cas:user>
    </cas:authenticationSuccess>
</cas:serviceResponse>

is that possible to parse data with this format or there is another method to do it .

this is my code :

$xml = simplexml_load_string($result);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$parsed= simplexml_load_string($result);

i'm trying to convert it to json format

Body:
$xml_string = file_get_contents('/path');
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Then you can use $json or $array as you want.


问:
Meaning of Open hashing and Closed hashing
Open Hashing (Separate Chaining):

In open hashing, keys are stored in linked lists attached to cells of a hash table.

Closed Hashing (Open Addressing):

In closed hashing, all keys are stored in the hash table itself without the use of linked lists.

I am unable to understand why they are called open, closed and Separate. Can some one explain it?

答:
The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index.
In a good hash table, each bucket has zero or one entries, because we need operations of order O(1)  for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)


问:
Use ANTLR to find Variable usage/reference in Java source-code?
A variable usage is basically every occurrence of a variable after its declaration in the same scope, where some operation may be applied to it. Variable usage highlighting is even supported in some IDEs like IntelliJ and Eclipse.

I was wondering if there is a way to find variable usages using ANTLR ? I have already generated the Lexer, Parser, and BaseListener classes by running ANTLR on Java8.g4. I can find variable declarations but am not able to find variable usages in a given Java source code. How can I do this ?

Example :

```<code>int i;    // Variable declaration
i++;      // Variable usage
i = 2;    // Variable usage
foo(i);   // Variable 'i' usage
</code>```

I am able to capture the declaration but not usage using the Listener class. I am parsing Java source codes here.

答:
I'll assume you're only considering local variables.

You'll need scopes and resolving to do this.

Scope will represent Java's variable scope. It will hold information about which variables are declared in the given scope. You'll have to create it when you enter a Java scope (start of block, method, ...) and get rid of it upon leaving the scope. You'll keep a stack of scopes to represent nested blocks / scopes (Java doesn't allow hiding a local variable in nested scope, but you still need to track when a variable goes out of scope at the end of a nested scope).

And then you'll need to resolve each name you encounter in the parsed input - determine whether the name refers to a variable or not (using scope). Basically, it refers to a local variable, whenever it is the first part of name (before any .), is not followed by ( and matches a name of a local variable.

Parser cannot do this for you, because whether a name refers to a variable or not depends on available variables:

```<code>private static class A {
    B out = new B();
}

private static class B {
    void println(String foo) {
        System.out.println("ha");
    }
}

public static void main(String[] args) {
    {
        A System = new A();
        System.out.println("a");
    }
    System.out.println("b");
}
</code>```

ha

  b

If you're considering also instance and static fields instead of just local variables, the resolving part becomes much more complicated, because you'll need to consider all classes in the current class' hierarchy, their instance and static fields, visibilities etc. to determine whether a variable of a given name exists and is visible.

Body:
A variable usage is basically every occurrence of a variable after its declaration in the same scope, where some operation may be applied to it. Variable usage highlighting is even supported in some IDEs like IntelliJ and Eclipse.

I was wondering if there is a way to find variable usages using ANTLR ? I have already generated the Lexer, Parser, and BaseListener classes by running ANTLR on Java8.g4. I can find variable declarations but am not able to find variable usages in a given Java source code. How can I do this ?

Example :

int i;    // Variable declaration
i++;      // Variable usage
i = 2;    // Variable usage
foo(i);   // Variable 'i' usage

I am able to capture the declaration but not usage using the Listener class. I am parsing Java source codes here.

Body:
I'll assume you're only considering local variables.

You'll need scopes and resolving to do this.

Scope will represent Java's variable scope. It will hold information about which variables are declared in the given scope. You'll have to create it when you enter a Java scope (start of block, method, ...) and get rid of it upon leaving the scope. You'll keep a stack of scopes to represent nested blocks / scopes (Java doesn't allow hiding a local variable in nested scope, but you still need to track when a variable goes out of scope at the end of a nested scope).

And then you'll need to resolve each name you encounter in the parsed input - determine whether the name refers to a variable or not (using scope). Basically, it refers to a local variable, whenever it is the first part of name (before any .), is not followed by ( and matches a name of a local variable.

Parser cannot do this for you, because whether a name refers to a variable or not depends on available variables:

private static class A {
    B out = new B();
}

private static class B {
    void println(String foo) {
        System.out.println("ha");
    }
}

public static void main(String[] args) {
    {
        A System = new A();
        System.out.println("a");
    }
    System.out.println("b");
}

ha

  b

If you're considering also instance and static fields instead of just local variables, the resolving part becomes much more complicated, because you'll need to consider all classes in the current class' hierarchy, their instance and static fields, visibilities etc. to determine whether a variable of a given name exists and is visible.


问:
Html input loses focus on Samsung Android when virtual keyboard appears
I have the problem of losing focus on an input element on a Samsung Galaxy Tab A (Android 7.0) with a html5 web application. It seems to be a problem in android, as on windows 10 or iOS (although the resize event is also triggered when the virtual keyboard pops up) the element does not lose focus. Windows 10 and iOS apparently suppress this when the virtual keyboard is called (but not when manually resizing the browser window). Anybody any help on this?</p>

答:
It's an Android issue losing focus due to the resize() event.

Have you tried something like this for your resize functionality if something is not in focus:

```<code>$(window).bind('resize', function() {

    if ($("input").is(":focus")) {
        // Nothing will happen
    } else {
        // Other resize functions
    }
});
</code>```

Body:
It's an Android issue losing focus due to the resize() event.

Have you tried something like this for your resize functionality if something is not in focus:

$(window).bind('resize', function() {

    if ($("input").is(":focus")) {
        // Nothing will happen
    } else {
        // Other resize functions
    }
});


问:
Syntax Error issues around Case When
I am trying to write the following query for Microsoft Access and am encountering issues around the last three characters here, Can someone tell me what's wrong with my syntax for Access purposes:

SELECT DISTINCT Searches.Search ,IIF(Chemical_Names.Category  IS NOT NULL, Chemical_Names.Category, IIF(CAS_Numbers.Category IS NOT NULL , CAS_Numbers.Category, IIF(Brand_Name.Category IS NOT NULL, Brand_Name.Category,
IIF(PART.Category IS NOT NULL , PART.Category,CAT.Category))))  AS Category
FROM Searches
     LEFT JOIN
       (SELECT * FROM Cat1 UNION
        SELECT * FROM Cat2 UNION
        SELECT * FROM Cat3 UNION
        SELECT * FROM Cat4) as CAT
    ON
                       Searches.Search = CAT.Search
     LEFT JOIN
       (SELECT * FROM Part1 UNION
        SELECT * FROM Part2 UNION
        SELECT * FROM Part3 UNION

        SELECT * FROM Part4) as PART
    ON
                       Searches.Search = PART.Search
      LEFT JOIN
       Supplier_Name
    ON
                       Searches.Search = Supplier_Name.Search
      LEFT JOIN
       Chemical_Names
    ON
                       Searches.Search = Chemical_Names.Search
     LEFT JOIN
       Chemical_Names
    ON
                       Searches.Search = CAS_Number.Search
     LEFT JOIN
       Brand_Name
    ON
                       Searches.Search = Brand_Name.Search;

答:
If I understand your desired result, Switch should be applied as follows:
Switch(Chemical_Names.Category IS NOT NULL, Chemical_Names.Category, CAS_Namber.Category IS NOT NULL, CAS_Number.Category, Brand_Name.Category IS NOT NULL, Brand_Name.Category, PART.Category IS NOT NULL,  PART.Category, 1=1, CAT.Category) AS Category

Title: Syntax Error issues around Case When


问:
note: candidate: MyClass:MyClass(const MyClass&) error
My C++ program is occurring following error when I saving it:

```<code>hw.cpp|10 col 7 error| note: candidate: Category::Category(const Category&) [cpp/gcc]
hw.cpp|10 col 7 error| note:   candidate expects 1 argument, 0 provided [cpp/gcc]
hw.cpp|14 col 9 error| note: candidate: Category::Category(std::__cxx11::string) [cpp/gcc]
hw.cpp|14 col 9 error| note:   candidate expects 1 argument, 0 provided [cpp/gcc]
hw.cpp|36 col 9 error| no matching function for call to ‘Category::Category()’ [cpp/gcc]
hw.cpp|39 col 51 error| cannot call constructor ‘Category::Category’ directly [-fpermissive] [cpp/gcc]
hw.cpp|39 col 51 error| note: for a function-style cast, remove the redundant ‘::Category’ [cpp/gcc]
</code>```

My code is:

```<code>class Category {
    private:
        string name;
    public:
        Category(string _name)
        {
            name = _name;
        }

        string getCategory()
        {
            return name;
        }
        void setCategory(string _name)
        {
            name = _name;
        }
};

class Book {
    private:
        string name;
        string author;
        Category category;
    public:
        Book(string _name, string _author, string _category)
        {
           name = _name;
           author = _author;
           category = Category::Category(_category);
        }
        Category getCategory()
        {
            return category;
        }

        void setCategory(string _name)
        {
            category.setCategory(_name);
        }
        string getName()
        {
            return name;
        }
        void setName(string _name)
        {
            name = _name;
        }

        string getAuthor()
        {
            return author;
        }
        void setAuthor(string _author)
        {
            author = _author;
        }
};
</code>```

What is wrong in my code? How can I fix it?

答:
The problem is here:

```<code>    Book(string _name, string _author, string _category)
    {
       name = _name;
       author = _author;
       category = Category::Category(_category);
    }
</code>```

Look at the last line. What value do you think category has before that line executes? How do you expect category to be constructed in the first place so that you can give it a new value here?

How you fix it depends on what you want to do. You can use an initializer list. You can use a default constructor.

Body:
My C++ program is occurring following error when I saving it:

hw.cpp|10 col 7 error| note: candidate: Category::Category(const Category&) [cpp/gcc]
hw.cpp|10 col 7 error| note:   candidate expects 1 argument, 0 provided [cpp/gcc]
hw.cpp|14 col 9 error| note: candidate: Category::Category(std::__cxx11::string) [cpp/gcc]
hw.cpp|14 col 9 error| note:   candidate expects 1 argument, 0 provided [cpp/gcc]
hw.cpp|36 col 9 error| no matching function for call to ‘Category::Category()’ [cpp/gcc]
hw.cpp|39 col 51 error| cannot call constructor ‘Category::Category’ directly [-fpermissive] [cpp/gcc]
hw.cpp|39 col 51 error| note: for a function-style cast, remove the redundant ‘::Category’ [cpp/gcc]

My code is:

class Category {
    private:
        string name;
    public:
        Category(string _name)
        {
            name = _name;
        }

        string getCategory()
        {
            return name;
        }
        void setCategory(string _name)
        {
            name = _name;
        }
};

class Book {
    private:
        string name;
        string author;
        Category category;
    public:
        Book(string _name, string _author, string _category)
        {
           name = _name;
           author = _author;
           category = Category::Category(_category);
        }
        Category getCategory()
        {
            return category;
        }

        void setCategory(string _name)
        {
            category.setCategory(_name);
        }
        string getName()
        {
            return name;
        }
        void setName(string _name)
        {
            name = _name;
        }

        string getAuthor()
        {
            return author;
        }
        void setAuthor(string _author)
        {
            author = _author;
        }
};

What is wrong in my code? How can I fix it?

Body:
The problem is here:

    Book(string _name, string _author, string _category)
    {
       name = _name;
       author = _author;
       category = Category::Category(_category);
    }

Look at the last line. What value do you think category has before that line executes? How do you expect category to be constructed in the first place so that you can give it a new value here?

How you fix it depends on what you want to do. You can use an initializer list. You can use a default constructor.


问:
Number to text decoding
Can anybody help me come up with an algorithm or way to decode a number to 3 characters when they are encoded in the following manner:

Each element represents 3 alphabetic characters as in the following examples:

DOG -> (3 * 26^2) + (14 * 26) + 6 = 2398

CAT -> (2 * 26^2) + (0 * 26) + 19 = 1371

ZZZ -> (25 * 26^2) + (25 * 26) + 25 = 17575

So say I have 7446 or 3290 how would I go about converting them to text?

答:
Modulo</p>

```<code>input = 2398
iteration = 1
while input > 0
    character = input % 26
    input = input - character
    input = input / 26
    print character
</code>```

Title: Number to text decoding

Body:
Modulo

input = 2398
iteration = 1
while input > 0
    character = input % 26
    input = input - character
    input = input / 26
    print character


问:
Unexpected result in Java (floating to integer)
I have a problem with this

```<code>System.out.print((9/5) * 3);
</code>```

I expects the result 5.4 but it returns 3. Why is this happening?

答:
In java when you make division of integers it will return an integer not a real number :

9/5 return 1 instead of 1.8

to solve your problem you have two solutions :

use a real number instead so you have to use 9.0/5

or you can cast the number to double ((double)9/5) * 3

Body:
I have a problem with this

System.out.print((9/5) * 3);

I expects the result 5.4 but it returns 3. Why is this happening?


问:
How exactly works the Angular 2 property binding? What really happens in this example?
I am an absolute beginner with Angular 2 and I have the following doubt relate property binding.

This example works but I have doubt about what exactly happen under the hood.

I have a component view (the servers.component.html file) containing this button:

```<code><button [disabled]="!allowNewServer" class="btn btn-primary">Add Server</button>
</code>```

The related component is:

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

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
  allowNewServer = false;

  constructor() {
    setTimeout(() => {
      this.allowNewServer = true;
    }, 8000);
  }

  ngOnInit() {
  }

}
</code>```

As you can see at the beginning the allowNewServer value is false, after 8 seconds it is setted to true by a function declared in the constructor.

On my button is setted this disabled attribute:

```<code> [disabled]="!allowNewServer"
</code>```

So at the beginning the button is disabled and after 8 seconds it will enabled.

Mu doubts are:

1) What exactly means the [...] Angular syntax?

2) I expected that was rendered something like disabled=true (at the beginning) and after 8 seconds something like disabled=dalse, but after 8 seconds simply the disable attribute is deleted. So I think that I am not understending what the [...] syntax mean.

答:
The [] syntax tells angular to bind information from the data
source (component instance) with the template (html).

What is your question?

Body:
I am an absolute beginner with Angular 2 and I have the following doubt relate property binding.

This example works but I have doubt about what exactly happen under the hood.

I have a component view (the servers.component.html file) containing this button:

<button [disabled]="!allowNewServer" class="btn btn-primary">Add Server</button>

The related component is:

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

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
  allowNewServer = false;

  constructor() {
    setTimeout(() => {
      this.allowNewServer = true;
    }, 8000);
  }

  ngOnInit() {
  }

}

As you can see at the beginning the allowNewServer value is false, after 8 seconds it is setted to true by a function declared in the constructor.

On my button is setted this disabled attribute:

 [disabled]="!allowNewServer"

So at the beginning the button is disabled and after 8 seconds it will enabled.

Mu doubts are:

1) What exactly means the [...] Angular syntax?

2) I expected that was rendered something like disabled=true (at the beginning) and after 8 seconds something like disabled=dalse, but after 8 seconds simply the disable attribute is deleted. So I think that I am not understending what the [...] syntax mean.


问:
Cross domain issue when making ajax call from one site to another to get data from database
I am creating a site in which user can create popup on one site and then take small code to used on other site . Problem is when i am made ajax call from other site to fetch data in others site database i am getting error "No cross origin access allowed".When i am using jsonp it is giving me correct response but i am not able to collect it. It is giving me error"Unexpected token". I am using jquery ajax if you have any other idea then let me know i will implement it also. Here is my code :</p>

```
$.ajax({
    url: "url",
    // Tell jQuery we're expecting JSONP
  dataType: "jsonp",
  jsonpCallback: 'callback',
    type: 'GET',

        data: {

            format: "json"
        },

    // Work with the response
    success: function( response ) {
        console.log( response ); // server response
    }
});
```

答: If Your response has error server side Cross domain issue then your server side response should  exist Access-Controll-Allow-Origin with * value will solve your problem.

Body:
I am creating a site in which user can create popup on one site and then take small code to used on other site . Problem is when i am made ajax call from other site to fetch data in others site database i am getting error "No cross origin access allowed".When i am using jsonp it is giving me correct response but i am not able to collect it. It is giving me error"Unexpected token". I am using jquery ajax if you have any other idea then let me know i will implement it also. Here is my code :

$.ajax({
    url: "url",
    // Tell jQuery we're expecting JSONP
  dataType: "jsonp",
  jsonpCallback: 'callback',
    type: 'GET',

        data: {

            format: "json"
        },

    // Work with the response
    success: function( response ) {
        console.log( response ); // server response
    }
});


问:
How to include chart js annotations in ember?
I am trying to include this annotation in my project in ember, this is th link to the plugin https://www.npmjs.com/package/chartjs-plugin-annotation.
I tried

```<code>npm i chartjs-plugin-annotation
</code>```

but still no luck,
i tried this also

```<code>npm i chartjs-plugin-annotation --save
</code>```

Is there another way to incude this plugin in ember?

答:
You can include it as bower dependency with bower install command.

After including it to the project,In ember-cli-build.js file, use app.import to add it to build as following (please check the path):

```<code>app.import('bower_components\chartjs-plugin-annotation\chartjs-plugin-annotation.min.js');
</code>```

If you don't want to use bower and if you prefer npm, then have a look at broccoli family. It is a bit long way.

Body:
I am trying to include this annotation in my project in ember, this is th link to the plugin https://www.npmjs.com/package/chartjs-plugin-annotation.
I tried

npm i chartjs-plugin-annotation

but still no luck,
i tried this also

npm i chartjs-plugin-annotation --save

Is there another way to incude this plugin in ember?

Body:
You can include it as bower dependency with bower install command.

After including it to the project,In ember-cli-build.js file, use app.import to add it to build as following (please check the path):

app.import('bower_components\chartjs-plugin-annotation\chartjs-plugin-annotation.min.js');

If you don't want to use bower and if you prefer npm, then have a look at broccoli family. It is a bit long way.


问:
Migrating from one Trac instance to another
I want to move tickets from one trac instance to another. Is there some utility that will help me do this? The current instance is running on my server using a sqllite db. The instance that I want to move to is on sourcerepo. Are there any utilities that can help me migrate these tickets? </p>

<p>Since sourcerepo also provides a redmine installation, I wouldn't mind if I could move tickets from trac to redmine. </p>

答: Take a look at what the Trac wiki has to say about migrating data between Trac installations.</p>

Body:
I want to move tickets from one trac instance to another. Is there some utility that will help me do this? The current instance is running on my server using a sqllite db. The instance that I want to move to is on sourcerepo. Are there any utilities that can help me migrate these tickets?

Since sourcerepo also provides a redmine installation, I wouldn't mind if I could move tickets from trac to redmine.