问:
get xpath from xsl variable
I am trying to get some xpath from xsl variable using xsl ver 1.0 .
That’s  my variable:

```<code>  <xsl:variable name ="myVar">
        <RefData RefTag="test1" bbb="false" />
        <RefData RefTag="test2" bbb="false" />
        <RefData RefTag="test3" bbb="false" />
        <RefData RefTag="test4" bbb="true"  />
        <RefData RefTag="test5" bbb="false" />
        <RefData RefTag="test6" bbb="false" />
  </xsl:variable>
</code>```

I am trying to get bbb attribure value using the RefTag value:

```<code><xsl:if test="$myVar/RefData[@RefTag = 'test3']/@bbb">
</code>```

this is not working.

VS XSL Debugger returns an error:
"To use a result tree fragment in a path expression, first convert it to a node-set using the msxsl:node-set() function."

I don't understand how to use msxsl:node-set() function, and anyway I prefer not to use msxsl namesapce.

Can anyone help here?

答:
```<code><xsl:variable name="myVariable" select="msxsl:node-set($myVar)"/>
</code>```

You can avoid msxsl namespace by moving variable contents to the source xml.

OwnerDisplayName: Schwartser

Title: get xpath from xsl variable

Body:
I am trying to get some xpath from xsl variable using xsl ver 1.0 .
That’s  my variable:

  <xsl:variable name ="myVar">
        <RefData RefTag="test1" bbb="false" />
        <RefData RefTag="test2" bbb="false" />
        <RefData RefTag="test3" bbb="false" />
        <RefData RefTag="test4" bbb="true"  />
        <RefData RefTag="test5" bbb="false" />
        <RefData RefTag="test6" bbb="false" />
  </xsl:variable>

I am trying to get bbb attribure value using the RefTag value:

<xsl:if test="$myVar/RefData[@RefTag = 'test3']/@bbb">

this is not working.

VS XSL Debugger returns an error:
"To use a result tree fragment in a path expression, first convert it to a node-set using the msxsl:node-set() function."

I don't understand how to use msxsl:node-set() function, and anyway I prefer not to use msxsl namesapce.

Can anyone help here?

Body:
<xsl:variable name="myVariable" select="msxsl:node-set($myVar)"/>

You can avoid msxsl namespace by moving variable contents to the source xml.

OwnerDisplayName: Azat Razetdinov


来源: stackexchange

问:
Protractor by.binding() returns two bindings combined
I'm using AngularJs 1.6 and protractor to do e2e tests.

I have the following code in my HTML template

{{exercise.a}} * {{exercise.b}}

Then in protractor I'm testing the page and want to get value of that bindings. I do

element(by.binding('exercise.a')).getText().then(console.log)

and the result is combination of exercise.a and exercise.b i.e. '9 * 2' while I expect the result to be '9'. I get exactly the same result is when I try to get value of exercise.b i.e. '9 * 2' while I expect '2'.

It took me a while to find a workaround. After I modifies my code to this it start working properly

{{exercise.a}} * {{exercise.b}}

It seems that something combines both bindings to one.

Could anybody explain why it happens and how to make it work without workaround.

答:
To my understanding, Angular attaches your h1 tag with watchers to exercise.a and excercise.b. The original bindings are gone since inner body of h1 tag get's replaced with text 9 * 2.

Angular however remebers the interpolation function together with watchers so that when any of them changes it would recalculate the new value.

That said, both bindings here point to body of h1 which is in your case 9 * 2. The only way to have them separate is to use wrapper element (span in you example) or use ng-bind but again it would require two elements.

ContentLicense: CC BY-SA 3.0


问:
How can I do a Monte Carlo analysis on an equation?
Given a function that depends on multiple variables, each with a certain probability distribution, how can I do a Monte Carlo analysis to obtain a probability distribution of the function. I'd ideally like the solution to be high performing as the number of parameters or number of iterations increase.

As an example, I've provided an equation for total_time that depends on a number of other parameters.

```<code>import numpy as np
import matplotlib.pyplot as plt

size = 1000

gym = [30, 30, 35, 35, 35, 35, 35, 35, 40, 40, 40, 45, 45]

left = 5
right = 10
mode = 9
shower = np.random.triangular(left, mode, right, size)

argument = np.random.choice([0, 45], size, p=[0.9, 0.1])

mu = 15
sigma = 5 / 3
dinner = np.random.normal(mu, sigma, size)

mu = 45
sigma = 15/3
work = np.random.normal(mu, sigma, size)

brush_my_teeth = 2

variables = gym, shower, dinner, argument, work, brush_my_teeth
for variable in variables:
    plt.figure()
    plt.hist(variable)
plt.show()

def total_time(variables):
    return np.sum(variables)
</code>```

gym

shower

dinner

argument

work

brush_my_teeth

答:
Have you tried with a simple for loop? First, define your constants and function. Then, run a loop n times (10'000 in the example), drawing new random values for the variables and calculating the function result each time. Finally, append all results to results_dist, then plot it.

```<code>import numpy as np
import matplotlib.pyplot as plt

gym = [30, 30, 35, 35, 35, 35, 35, 35, 40, 40, 40, 45, 45]
brush_my_teeth = 2
size = 1000

def total_time(variables):
    return np.sum(variables)

results_dist = []
for i in range(10000):
    shower = np.random.triangular(left=5, mode=9, right=10, size)
    argument = np.random.choice([0, 45], size, p=[0.9, 0.1])
    dinner = np.random.normal(mu=15, sigma=5/3, size)
    work = np.random.normal(mu=45, sigma=15/3, size)

    variables = gym, shower, dinner, argument, work, brush_my_teeth

    results_dist.append(total_time(variables))

plt.figure()
plt.hist(results_dist)
plt.show()
</code>```

Body:
Given a function that depends on multiple variables, each with a certain probability distribution, how can I do a Monte Carlo analysis to obtain a probability distribution of the function. I'd ideally like the solution to be high performing as the number of parameters or number of iterations increase.

As an example, I've provided an equation for total_time that depends on a number of other parameters.

import numpy as np
import matplotlib.pyplot as plt

size = 1000

gym = [30, 30, 35, 35, 35, 35, 35, 35, 40, 40, 40, 45, 45]

left = 5
right = 10
mode = 9
shower = np.random.triangular(left, mode, right, size)

argument = np.random.choice([0, 45], size, p=[0.9, 0.1])

mu = 15
sigma = 5 / 3
dinner = np.random.normal(mu, sigma, size)

mu = 45
sigma = 15/3
work = np.random.normal(mu, sigma, size)

brush_my_teeth = 2

variables = gym, shower, dinner, argument, work, brush_my_teeth
for variable in variables:
    plt.figure()
    plt.hist(variable)
plt.show()

def total_time(variables):
    return np.sum(variables)

gym

shower

dinner

argument

work

brush_my_teeth

Body:
Have you tried with a simple for loop? First, define your constants and function. Then, run a loop n times (10'000 in the example), drawing new random values for the variables and calculating the function result each time. Finally, append all results to results_dist, then plot it.

import numpy as np
import matplotlib.pyplot as plt

gym = [30, 30, 35, 35, 35, 35, 35, 35, 40, 40, 40, 45, 45]
brush_my_teeth = 2
size = 1000

def total_time(variables):
    return np.sum(variables)

results_dist = []
for i in range(10000):
    shower = np.random.triangular(left=5, mode=9, right=10, size)
    argument = np.random.choice([0, 45], size, p=[0.9, 0.1])
    dinner = np.random.normal(mu=15, sigma=5/3, size)
    work = np.random.normal(mu=45, sigma=15/3, size)

    variables = gym, shower, dinner, argument, work, brush_my_teeth

    results_dist.append(total_time(variables))

plt.figure()
plt.hist(results_dist)
plt.show()


问:
C# Classes to List => Loop => Print Out
Hey guys I recently started learning C# using microsoft .Net Tutorials.

I'm stuck at "Classes and Objects" Lesson.
At the end of the each lesson we have a little "homework" to do.
I need to write a program that prints out addresses for people and companies using three different classes (Person, Copmany, Address). I need to add them to collection and loop through, printing out the address for each company or person.

Here is the LINK (at the end of the page there is an example how the program should look like.

I'm not really sure how am I suppose to achieve this. Can someone please help me understand. This is what I come so far:

```<code>public class Address
{
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }

public override string ToString()
{
    return $"{StreetAddress}, {City}, {PostalCode}, {Country}";
}
public Address()
{
    StreetAddress = "Main123";
    City = "SomeTown";
    State = "OH";
    PostalCode = "12345";
    Country = "United States";
}
}

public class Person : Master
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address ShippingAddress { get; set; }

public Person(string firstName, string lastName)
{
    FirstName = firstName;
    LastName = lastName;
    ShippingAddress = new Address();
}
public override string ToString()
{
    return $"{FirstName} {LastName} {ShippingAddress}\n";
}
}

public class Company : Master
{
public string Name { get; set; }
public Address ShippingAddress { get; set; }

public Company(string name)
{
    Name = name;
    ShippingAddress = new Address();
}
public override string ToString()
{
    return $"{Name} {ShippingAddress}\n";
}
}

public class Master
{
public static List<Master> data = new List<Master>();
public static void Coll(Master master)
{
    data.Add(master);
    data.ForEach(Console.WriteLine);
}
}

class MainClass
{
public static void Main(string[] args)
{
    Person John = new Person("John", "Smith");
    Master.Coll(John);
}
}
</code>```

答:
If you have already reached the end of your tutorial, then it means that you have read the section about Inheritance and Polymorphism.
Please read this section again carefully.

If your task is: printing out the address for each company or person

Have a look on what the tutorial says about the ToString method:

Note that you can override the ToString method on any class where it will make sense to display string data related to an instance of the class.

So you first step would be to give the class Address the ability to display it's content, by overriding the ToString method.

You second step would be to use inheritance and create a super class which can be inherited by your 2 classes Person and Company. As it is done in the tutorial with the class Shape.

This will allow you to to add them to [a single] collection (as you wrote in your request).

Try to combine these steps and if you still have questions drop me a comment.
(Please keep rereading the tutorial, all the necessary information is in there, you just have to combine the different parts). Good fortune!

EDIT:

After you have edited your code, the next steps would be to give your classes Person and Company the ability to display information about themselves. Meaning you should override the ToString method also there.

One tip : you can use the ToString method of the class Address to display the details of the ShippingAddress. No need to write the details again ;) If you include the variable in the extrapolated string $"... the ToString method will be called implicitly and display all the details:

```<code>$"{ShippingAddress}"
</code>```

One problem with your Coll method is that it is using a local variable List<Master> data as storage. This variable will cease to exist when the compiler returns from the method. Another problem is that in each call you create a new List making it impossible to store more than 1 element. What you can do is to make it a static variable inside the Master class. So that every time you add an item it will stay in memory and can be accessed later on.
You can also make the method static since it does not really require an object of type Master to be called (it does not access any class properties)

```<code>public class Master
{
    public static List<Master> data = new List<Master>();

    public static void Coll(Master master)
    {
        data.Add(master);
        data.ForEach(Console.WriteLine);
    }
}
</code>```

You can call it like this then:

```<code>Person John = new Person("John", "Smith");
Master.Coll(John);
</code>```

Title: C# Classes to List => Loop => Print Out

Body:
Hey guys I recently started learning C# using microsoft .Net Tutorials.

I'm stuck at "Classes and Objects" Lesson.
At the end of the each lesson we have a little "homework" to do.
I need to write a program that prints out addresses for people and companies using three different classes (Person, Copmany, Address). I need to add them to collection and loop through, printing out the address for each company or person.

Here is the LINK (at the end of the page there is an example how the program should look like.

I'm not really sure how am I suppose to achieve this. Can someone please help me understand. This is what I come so far:

public class Address
{
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }

public override string ToString()
{
    return $"{StreetAddress}, {City}, {PostalCode}, {Country}";
}
public Address()
{
    StreetAddress = "Main123";
    City = "SomeTown";
    State = "OH";
    PostalCode = "12345";
    Country = "United States";
}
}

public class Person : Master
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address ShippingAddress { get; set; }

public Person(string firstName, string lastName)
{
    FirstName = firstName;
    LastName = lastName;
    ShippingAddress = new Address();
}
public override string ToString()
{
    return $"{FirstName} {LastName} {ShippingAddress}\n";
}
}

public class Company : Master
{
public string Name { get; set; }
public Address ShippingAddress { get; set; }

public Company(string name)
{
    Name = name;
    ShippingAddress = new Address();
}
public override string ToString()
{
    return $"{Name} {ShippingAddress}\n";
}
}

public class Master
{
public static List<Master> data = new List<Master>();
public static void Coll(Master master)
{
    data.Add(master);
    data.ForEach(Console.WriteLine);
}
}

class MainClass
{
public static void Main(string[] args)
{
    Person John = new Person("John", "Smith");
    Master.Coll(John);
}
}

Body:
If you have already reached the end of your tutorial, then it means that you have read the section about Inheritance and Polymorphism.
Please read this section again carefully.

If your task is: printing out the address for each company or person

Have a look on what the tutorial says about the ToString method:

Note that you can override the ToString method on any class where it will make sense to display string data related to an instance of the class.

So you first step would be to give the class Address the ability to display it's content, by overriding the ToString method.

You second step would be to use inheritance and create a super class which can be inherited by your 2 classes Person and Company. As it is done in the tutorial with the class Shape.

This will allow you to to add them to [a single] collection (as you wrote in your request).

Try to combine these steps and if you still have questions drop me a comment.
(Please keep rereading the tutorial, all the necessary information is in there, you just have to combine the different parts). Good fortune!

EDIT:

After you have edited your code, the next steps would be to give your classes Person and Company the ability to display information about themselves. Meaning you should override the ToString method also there.

One tip : you can use the ToString method of the class Address to display the details of the ShippingAddress. No need to write the details again ;) If you include the variable in the extrapolated string $"... the ToString method will be called implicitly and display all the details:

$"{ShippingAddress}"

One problem with your Coll method is that it is using a local variable List<Master> data as storage. This variable will cease to exist when the compiler returns from the method. Another problem is that in each call you create a new List making it impossible to store more than 1 element. What you can do is to make it a static variable inside the Master class. So that every time you add an item it will stay in memory and can be accessed later on.
You can also make the method static since it does not really require an object of type Master to be called (it does not access any class properties)

public class Master
{
    public static List<Master> data = new List<Master>();

    public static void Coll(Master master)
    {
        data.Add(master);
        data.ForEach(Console.WriteLine);
    }
}

You can call it like this then:

Person John = new Person("John", "Smith");
Master.Coll(John);


问:
How do I update a Python package?
I'm running Ubuntu 9:10 and a package called M2Crypto is installed (version is 0.19.1). I need to download, build and install the latest version of the M2Crypto package (0.20.2).

The 0.19.1 package has files in a number of locations including (/usr/share/pyshared and /usr/lib/pymodules.python2.6).

How can I completely uninstall version 0.19.1 from my system before installing 0.20.2?

答:
Via windows command prompt, run: pip list --outdated
You will get the list of outdated packages.

Run: pip install [package] --upgrade
It will upgrade the [package] and uninstall the previous version.

To update pip:

```<code>pip install --upgrade pip
</code>```

Again, this will uninstall the previous version of pip and will install the latest version of pip.

ContentLicense: CC BY-SA 2.5

Title: How do I update a Python package?

Body:
Via windows command prompt, run: pip list --outdated
You will get the list of outdated packages.

Run: pip install [package] --upgrade
It will upgrade the [package] and uninstall the previous version.

To update pip:

pip install --upgrade pip

Again, this will uninstall the previous version of pip and will install the latest version of pip.

ContentLicense: CC BY-SA 4.0


问:
Clone panel to external monitor
I have just installed Mint 18.1 with Cinnamon 3.2.7 (Kernel: 4.4.0-78) on my laptop and on the external monitor I have no panel at all. I read somewhere that this might be intentionally so I can have different items on the internal monitor and other on the external. I have no issue with this as long as I can "clone" somehow the settings/items from one panel to the other. How can I do that?</p>

答:
Finally, I managed to find a way to partially solve this productivity issue. After lots of panel changes and finds (to see what files have changed) I noticed that the panel information is stored here:

```<code>~/.cinnamon/configs/panel-launchers@cinnamon.org
</code>```

There are 2 .json files (one called 2.json for the main panel and another one called 30.json for the panel on the external monitor) and by copying the contents of one panel to another, I managed to clone the applications from the left to the right side.

Note 1: this is only a partial fix because I could only clone the launcher part of the panel and not the full panel, but this partial solution solves my problem

Note 2: I've tried soft linking these files but I managed to make the changes only one way (from one panel to another), so soft linking the files is not an option. Hardlink doesn't have any automated effects

Note 3: I'm not sure how the filenames are assigned on the panels but I assume they follow some convention-over-configuration naming policy because I couldn't find the names mentioned anywhere on the ~/.cinnamon folder

Title: Clone panel to external monitor

Body:
Finally, I managed to find a way to partially solve this productivity issue. After lots of panel changes and finds (to see what files have changed) I noticed that the panel information is stored here:

~/.cinnamon/configs/panel-launchers@cinnamon.org

There are 2 .json files (one called 2.json for the main panel and another one called 30.json for the panel on the external monitor) and by copying the contents of one panel to another, I managed to clone the applications from the left to the right side.

Note 1: this is only a partial fix because I could only clone the launcher part of the panel and not the full panel, but this partial solution solves my problem

Note 2: I've tried soft linking these files but I managed to make the changes only one way (from one panel to another), so soft linking the files is not an option. Hardlink doesn't have any automated effects

Note 3: I'm not sure how the filenames are assigned on the panels but I assume they follow some convention-over-configuration naming policy because I couldn't find the names mentioned anywhere on the ~/.cinnamon folder


问:
NSDateFormatter's init method is deprecated?
Per

http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

The init method of NSDateFormatter is "Available in iPhone OS 2.0 through iPhone OS 3.2", and therefore not in 4.0.  Now, it certainly works, but this seems odd.  Is this is a mistake or is there some other way to create a NSDateFormatter?

答: That’s really strange. Maybe +[NSDateFormatter new] will do the job?


问:
Search using TextFiled in Multi Sectioned TableView - Swift
I made a search with textfield with the below method and its working fine when i use single section in table view.

But i don’t know how to achieve this when i have multiple sections in table View

In Normal Single Sectioned tableview

```<code>foodTypeArr = ["Japanesh", "Chinesh", "Lebanesh", "Italian", "Indian"]
searchResultArr.addObjects(from: foodTypeArr as! [Any])

func searchAutocompleteEntriesWithSubstring(substring: String)
{
 searchResultArr.removeAllObjects()

        for curString in foodTypeArr
        {
            let myString:NSString! = curString as! NSString

            if (myString).lowercased.contains(substring)
            {
                searchResultArr.add(curString)
            }
        }

        self.tblList.reloadData()
 }
</code>```

In Multi Section TableView

```<code>var searchAreaArr = NSMutableArray()
var areaArr = [[String]]()
var areaTitles = NSArray()

areaArr = [["Vadvalli", "Mullai Nagar", "P.N.Pudhur"], ["Lawly Road", "Kowly Brown", "D.B Road"], ["Raja Street", "Gandhipark", "Five corner road”, "Main Town Hall”]]

areaTitles = ["Vadavalli", "R.S.Puram", "Town Hall"]

for i in 0..<areaArr.count
{
   searchAreaArr.addObjects(from: areaArr[i])
}
</code>```

I’m calling the below method in TextField-shouldChangeCharactersIn range

```<code>func searchAutocompleteEntriesWithSubstring(substring: String)
{
    areaArr.removeAll()
            var mArr = [String]()

        for curString in searchAreaArr
        {
            let myString:NSString! = curString as! NSString

            if (myString).lowercased.contains(substring)
            {
                mArr.append(curString as! String)
            }
        }
        areaArr.insert(mArr, at: 0)
}
</code>```

with this it is inserting the filtered Strings in the 0th array Index in areaArr. But I need it should be on their sections and the section name should be their own, and to change the section Index of the filtered sections of strings

Say For example if the search text is road, it should be

```<code>R.S puram (Section 1)
- Lawly Road
- D.B Road
Town Hall (Section 2)
- Five corner road
</code>```

My tableview Methods

```<code>func numberOfSections(in tableView: UITableView) -> Int
{
    return areaArr.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return areaArr[section].count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
    if section < areaTitles.count
        {
            return areaTitles[section] as? String
        }
    return nil
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
        let cell:UITableViewCell =
self.tblList.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell!
    cell.textLabel?.text = "\(areaArr[indexPath.section][indexPath.row])"
}
</code>```

I Lost my One whole day with it, Please Help to Fix this…. Your Suggestions are welcomed

答:
You can do something like this in shouldChangeCharactersIn method

```<code>let areaArr = [["Vadvalli", "Mullai Nagar", "P.N.Pudhur"], ["Lawly Road", "Kowly Brown", "D.B Road"], ["Raja Street", "Gandhipark", "Five corner road", "Main Town Hall"]]

let areaTitles = ["Vadavalli", "R.S.Puram", "Town Hall"]
let searchText = "road"
var areaArrResult = areaArr.map { $0.filter({ $0.lowercased().contains(searchText) }) }
let areaTitlesResult = areaTitles.filter {  !areaArrResult[areaTitles.index(of: $0)!].isEmpty }
areaArrResult = areaArrResult.filter { !$0.isEmpty }

print(areaArrResult)//[["Lawly Road", "D.B Road"], ["Five corner road"]]
print(areaTitlesResult)//["R.S.Puram", "Town Hall"]
</code>```

OR

```<code>     var allDetails:[(String,[String])] = []
     var searchResult:[(String,[String])] = []

    allDetails = [("Vadavalli",["Vadvalli", "Mullai Nagar", "P.N.Pudhur"]),
                  ("R.S.Puram",["Lawly Road", "Kowly Brown", "D.B Road"]),
                  ("Town Hall",["Raja Street", "Gandhipark", "Five corner road", "Main Town Hall"])]
    searchAreaArr = areaArr.map({ ($0.0,$0.1.filter({ $0.lowercased().contains(substring) })) }).filter { !$0.1.isEmpty}
    print(searchResult)//[("R.S.Puram", ["Lawly Road", "D.B Road"]), ("Town Hall", ["Five corner road"])]
</code>```

Then
In numberOfSections return searchResult.count

In numberOfRowsInScetion return searchResult[section].1.count

In titleForHeaderInSection method you can use

```<code>return searchResult[section].0
</code>```

In cellForRowAt method

cell.textLabel?.text = "\(searchResult[indexPath.section].1[indexPath.row])"

Body:
I made a search with textfield with the below method and its working fine when i use single section in table view.

But i don’t know how to achieve this when i have multiple sections in table View

In Normal Single Sectioned tableview

foodTypeArr = ["Japanesh", "Chinesh", "Lebanesh", "Italian", "Indian"]
searchResultArr.addObjects(from: foodTypeArr as! [Any])

func searchAutocompleteEntriesWithSubstring(substring: String)
{
 searchResultArr.removeAllObjects()

        for curString in foodTypeArr
        {
            let myString:NSString! = curString as! NSString

            if (myString).lowercased.contains(substring)
            {
                searchResultArr.add(curString)
            }
        }

        self.tblList.reloadData()
 }

In Multi Section TableView

var searchAreaArr = NSMutableArray()
var areaArr = [[String]]()
var areaTitles = NSArray()

areaArr = [["Vadvalli", "Mullai Nagar", "P.N.Pudhur"], ["Lawly Road", "Kowly Brown", "D.B Road"], ["Raja Street", "Gandhipark", "Five corner road”, "Main Town Hall”]]

areaTitles = ["Vadavalli", "R.S.Puram", "Town Hall"]

for i in 0..<areaArr.count
{
   searchAreaArr.addObjects(from: areaArr[i])
}

I’m calling the below method in TextField-shouldChangeCharactersIn range

func searchAutocompleteEntriesWithSubstring(substring: String)
{
    areaArr.removeAll()
            var mArr = [String]()

        for curString in searchAreaArr
        {
            let myString:NSString! = curString as! NSString

            if (myString).lowercased.contains(substring)
            {
                mArr.append(curString as! String)
            }
        }
        areaArr.insert(mArr, at: 0)
}

with this it is inserting the filtered Strings in the 0th array Index in areaArr. But I need it should be on their sections and the section name should be their own, and to change the section Index of the filtered sections of strings

Say For example if the search text is road, it should be

R.S puram (Section 1)
- Lawly Road
- D.B Road
Town Hall (Section 2)
- Five corner road

My tableview Methods

func numberOfSections(in tableView: UITableView) -> Int
{
    return areaArr.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return areaArr[section].count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
    if section < areaTitles.count
        {
            return areaTitles[section] as? String
        }
    return nil
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
        let cell:UITableViewCell =
self.tblList.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell!
    cell.textLabel?.text = "\(areaArr[indexPath.section][indexPath.row])"
}

I Lost my One whole day with it, Please Help to Fix this…. Your Suggestions are welcomed

Body:
You can do something like this in shouldChangeCharactersIn method

let areaArr = [["Vadvalli", "Mullai Nagar", "P.N.Pudhur"], ["Lawly Road", "Kowly Brown", "D.B Road"], ["Raja Street", "Gandhipark", "Five corner road", "Main Town Hall"]]

let areaTitles = ["Vadavalli", "R.S.Puram", "Town Hall"]
let searchText = "road"
var areaArrResult = areaArr.map { $0.filter({ $0.lowercased().contains(searchText) }) }
let areaTitlesResult = areaTitles.filter {  !areaArrResult[areaTitles.index(of: $0)!].isEmpty }
areaArrResult = areaArrResult.filter { !$0.isEmpty }

print(areaArrResult)//[["Lawly Road", "D.B Road"], ["Five corner road"]]
print(areaTitlesResult)//["R.S.Puram", "Town Hall"]

OR

     var allDetails:[(String,[String])] = []
     var searchResult:[(String,[String])] = []

    allDetails = [("Vadavalli",["Vadvalli", "Mullai Nagar", "P.N.Pudhur"]),
                  ("R.S.Puram",["Lawly Road", "Kowly Brown", "D.B Road"]),
                  ("Town Hall",["Raja Street", "Gandhipark", "Five corner road", "Main Town Hall"])]
    searchAreaArr = areaArr.map({ ($0.0,$0.1.filter({ $0.lowercased().contains(substring) })) }).filter { !$0.1.isEmpty}
    print(searchResult)//[("R.S.Puram", ["Lawly Road", "D.B Road"]), ("Town Hall", ["Five corner road"])]

Then
In numberOfSections return searchResult.count

In numberOfRowsInScetion return searchResult[section].1.count

In titleForHeaderInSection method you can use

return searchResult[section].0

In cellForRowAt method

cell.textLabel?.text = "\(searchResult[indexPath.section].1[indexPath.row])"


问:
Please I need to get this clear PHP_SELF
I understand that it validate form data on the same page, but what if i want my form data to be handled by example.php can I use PHP_SELF and example.php together on some condition?</p>

答:
If you want to submit your form to the same page, i.e. PHP_SELF when a condition is met and submit it to example.php when a different condition is met, then try this:

```<code><form method="POST"
  action="<?php echo $some_condition == "some_value" ? $_SERVER['PHP_SELF'] : 'example.php'  ?>">
...
Your form content here
...
</form>
</code>```

You will replace $some_condition == "some_value" with whatever condition you want to check.

Body:
If you want to submit your form to the same page, i.e. PHP_SELF when a condition is met and submit it to example.php when a different condition is met, then try this:

<form method="POST"
  action="<?php echo $some_condition == "some_value" ? $_SERVER['PHP_SELF'] : 'example.php'  ?>">
...
Your form content here
...
</form>

You will replace $some_condition == "some_value" with whatever condition you want to check.


问:
Babel not compiling within a class
I have just started using a new JS stack - Node, Webpack, Babel, React and ExpressJS with ES6. Never used any of these previously. I am having issues where I am getting the error:

Module build failed: SyntaxError: Unexpected token (7:8)

on the line state = {

In the file Login.js which is:

```<code>import React from 'react';
import styles from './Login.css';
import auth from './auth.js';

class Login extends React.Component {

  state = {
    redirectToReferrer: false
  }

  login(e) {
    e.preventDefault();
    console.log('logging in');
    auth.authenticate("/");
  }

  render() {

    if (redirectToReferrer) {
      return (
        <Redirect to="/" />
      )
    }

    return (
      <div className={styles.loginPage}>
        <div className={styles.form}>
          <form className={styles.loginForm}>
            <input type="text" placeholder="username" />
            <input type="password" placeholder="password" />
            <button onClick={this.login}>login</button>
          </form>
        </div>
      </div>
    );
  }
}

export default Login;
</code>```

However, I believe that is the correct syntax as I am trying to learn/follow from the react training website which has exactly the same.

So I assume it is my stack configuration and its not compiling something that way it should. Though, some ES6 is obviously being compiled as import is working.

Here is my stack files, shortened for brevity

package.json

```<code>{
  "name": "exampleApp",
  "version": "1.0.0",
  "description": "NodeJS version of the control panel",
  "main": "server.js",
  "scripts": {
    "start": "babel-node ./server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    ...
  },
  "devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.24.1",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-hmre": "^1.1.1",
    "css-loader": "^0.28.4",
    "eslint": "^3.19.0",
    "eslint-config-airbnb": "^15.0.1",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-import": "^2.3.0",
    "eslint-plugin-jsx-a11y": "^5.0.3",
    "eslint-plugin-react": "^7.0.1",
    "react-hot-loader": "^3.0.0-beta.7",
    "redux-devtools": "^3.4.0",
    "style-loader": "^0.18.1",
    "webpack": "^2.6.1",
    "webpack-dev-middleware": "^1.10.2",
    "webpack-dev-server": "^2.4.5",
    "webpack-hot-middleware": "^2.18.0"
  }
}
</code>```

.babelrc

```<code>{
  "presets": [
    "es2015",
    "react"
  ],
  "plugins": [
    "react-hot-loader/babel"
  ],
  "env": {
    "presets": [
      "react-hrme"
    ]
  }
}
</code>```

webpack.config.json

```<code>const { resolve } = require('path');
const webpack = require('webpack');

module.exports = {
  context: resolve(__dirname, 'src'),

  devtool: 'source-map',

  entry: [
    'react-hot-loader/patch',
    resolve(__dirname, './src/index.js'),
  ],

  output: {
    path: resolve(__dirname, 'src'),
    publicPath: '/',
    filename: 'bundle.js',
  },

  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'eslint-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: ['babel-loader'],
      },
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader?modules', ],
      }
    ]
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
  ],
}
</code>```

I am starting my server with npm start - In honesty I don't think this is set up correctly as hot reloading doesn't seem to work either.

答:
You're trying to use class properties, which are part of the stage 2 Babel preset, so you should install it (npm i -D babel-preset-stage-2) and add it to your presets list.

Or you can add only the transform-class-properties plugin.

Title: Babel not compiling within a class

Body:
I have just started using a new JS stack - Node, Webpack, Babel, React and ExpressJS with ES6. Never used any of these previously. I am having issues where I am getting the error:

Module build failed: SyntaxError: Unexpected token (7:8)

on the line state = {

In the file Login.js which is:

import React from 'react';
import styles from './Login.css';
import auth from './auth.js';

class Login extends React.Component {

  state = {
    redirectToReferrer: false
  }

  login(e) {
    e.preventDefault();
    console.log('logging in');
    auth.authenticate("/");
  }

  render() {

    if (redirectToReferrer) {
      return (
        <Redirect to="/" />
      )
    }

    return (

          <form className={styles.loginForm}>
            <input type="text" placeholder="username" />
            <input type="password" placeholder="password" />
            <button onClick={this.login}>login</button>
          </form>

    );
  }
}

export default Login;

However, I believe that is the correct syntax as I am trying to learn/follow from the react training website which has exactly the same.

So I assume it is my stack configuration and its not compiling something that way it should. Though, some ES6 is obviously being compiled as import is working.

Here is my stack files, shortened for brevity

package.json

{
  "name": "exampleApp",
  "version": "1.0.0",
  "description": "NodeJS version of the control panel",
  "main": "server.js",
  "scripts": {
    "start": "babel-node ./server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    ...
  },
  "devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.24.1",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-hmre": "^1.1.1",
    "css-loader": "^0.28.4",
    "eslint": "^3.19.0",
    "eslint-config-airbnb": "^15.0.1",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-import": "^2.3.0",
    "eslint-plugin-jsx-a11y": "^5.0.3",
    "eslint-plugin-react": "^7.0.1",
    "react-hot-loader": "^3.0.0-beta.7",
    "redux-devtools": "^3.4.0",
    "style-loader": "^0.18.1",
    "webpack": "^2.6.1",
    "webpack-dev-middleware": "^1.10.2",
    "webpack-dev-server": "^2.4.5",
    "webpack-hot-middleware": "^2.18.0"
  }
}

.babelrc

{
  "presets": [
    "es2015",
    "react"
  ],
  "plugins": [
    "react-hot-loader/babel"
  ],
  "env": {
    "presets": [
      "react-hrme"
    ]
  }
}

webpack.config.json

const { resolve } = require('path');
const webpack = require('webpack');

module.exports = {
  context: resolve(__dirname, 'src'),

  devtool: 'source-map',

  entry: [
    'react-hot-loader/patch',
    resolve(__dirname, './src/index.js'),
  ],

  output: {
    path: resolve(__dirname, 'src'),
    publicPath: '/',
    filename: 'bundle.js',
  },

  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'eslint-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: ['babel-loader'],
      },
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader?modules', ],
      }
    ]
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
  ],
}

I am starting my server with npm start - In honesty I don't think this is set up correctly as hot reloading doesn't seem to work either.


问:
SyntaxError: Unexpected token: string (expose?Tether!tether) on npm run build
Hi I get an error when running npm run build on my prestashop theme and I have no idea where it's coming from.

The error is as follows :

```<code>SyntaxError: Unexpected token: string (expose?Tether!tether) [./js/theme.js:25,7]
</code>```

My webpack.config.js looks like this :

```<code>var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

var plugins = [];

var production = true;

if (production) {
    plugins.push(
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    );
}

plugins.push(
    new ExtractTextPlugin(
        path.join(
            '..', 'css', 'theme.css'
        )
    )
);

module.exports = {
    entry: [
        './js/theme.js'
    ],
    output: {
        path: '../assets/js',
        filename: 'theme.js'
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loaders: ['babel-loader']
        }, {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract(
                "style",
                "css?sourceMap!postcss!sass?sourceMap"
            )
        }, {
            test: /.(png|woff(2)?|eot|ttf|svg)(\?[a-z0-9=\.]+)?$/,
            loader: 'file-loader?name=../css/[hash].[ext]'
        }, {
            test: /\.css$/,
            loader: "style-loader!css-loader!postcss-loader"
        }]
    },
    postcss: function() {
        return [require('postcss-flexibility')];
    },
    externals: {
        prestashop: 'prestashop',
        $: '$',
        jquery: 'jQuery'
    },
    devtool: 'source-map',
    plugins: plugins,
    resolve: {
        extensions: ['', '.js', '.scss']
    }
};
</code>```

And the file that throws the error is the theme.js

```<code>import 'expose/Tether/tether';
import 'bootstrap/dist/js/bootstrap.min';
import 'flexibility';
import 'bootstrap-touchspin';

import '../css/theme';
import './responsive';
import './checkout';
import './customer';
import './listing';
import './product';
import './cart';

import DropDown from './components/drop-down';
import Form from './components/form';
import ProductMinitature from './components/product-miniature';
import ProductSelect from './components/product-select';
import TopMenu from './components/top-menu';

import prestashop from 'prestashop';
import EventEmitter from 'events';

import './lib/bootstrap-filestyle.min';
import './lib/jquery.scrollbox.min';

import './components/block-cart';

// "inherit" EventEmitter
for (var i in EventEmitter.prototype) {
  prestashop[i] = EventEmitter.prototype[i];
}

$(document).ready(() => {
  let dropDownEl = $('.js-dropdown');
  const form = new Form();
  let topMenuEl = $('.js-top-menu ul[data-depth="0"]');
  let dropDown = new DropDown(dropDownEl);
  let topMenu = new TopMenu(topMenuEl);
  let productMinitature = new ProductMinitature();
  let productSelect  = new ProductSelect();
  dropDown.init();
  form.init();
  topMenu.init();
  productMinitature.init();
  productSelect.init();
});
</code>```

Webpack really is not my strong suit and I have searched all over but I can not find anything related to this error.

Any help would be much appreciated.

答:
A colleague helped me figure it out in the end.
I needed to add the correct preset to the babel-loader query : </p>

```<code>loaders: [{
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
            presets: ['es2015']
        }
    },
</code>```

Body:
Hi I get an error when running npm run build on my prestashop theme and I have no idea where it's coming from.

The error is as follows :

SyntaxError: Unexpected token: string (expose?Tether!tether) [./js/theme.js:25,7]

My webpack.config.js looks like this :

var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

var plugins = [];

var production = true;

if (production) {
    plugins.push(
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    );
}

plugins.push(
    new ExtractTextPlugin(
        path.join(
            '..', 'css', 'theme.css'
        )
    )
);

module.exports = {
    entry: [
        './js/theme.js'
    ],
    output: {
        path: '../assets/js',
        filename: 'theme.js'
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loaders: ['babel-loader']
        }, {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract(
                "style",
                "css?sourceMap!postcss!sass?sourceMap"
            )
        }, {
            test: /.(png|woff(2)?|eot|ttf|svg)(\?[a-z0-9=\.]+)?$/,
            loader: 'file-loader?name=../css/[hash].[ext]'
        }, {
            test: /\.css$/,
            loader: "style-loader!css-loader!postcss-loader"
        }]
    },
    postcss: function() {
        return [require('postcss-flexibility')];
    },
    externals: {
        prestashop: 'prestashop',
        $: '$',
        jquery: 'jQuery'
    },
    devtool: 'source-map',
    plugins: plugins,
    resolve: {
        extensions: ['', '.js', '.scss']
    }
};

And the file that throws the error is the theme.js

import 'expose/Tether/tether';
import 'bootstrap/dist/js/bootstrap.min';
import 'flexibility';
import 'bootstrap-touchspin';

import '../css/theme';
import './responsive';
import './checkout';
import './customer';
import './listing';
import './product';
import './cart';

import DropDown from './components/drop-down';
import Form from './components/form';
import ProductMinitature from './components/product-miniature';
import ProductSelect from './components/product-select';
import TopMenu from './components/top-menu';

import prestashop from 'prestashop';
import EventEmitter from 'events';

import './lib/bootstrap-filestyle.min';
import './lib/jquery.scrollbox.min';

import './components/block-cart';

// "inherit" EventEmitter
for (var i in EventEmitter.prototype) {
  prestashop[i] = EventEmitter.prototype[i];
}

$(document).ready(() => {
  let dropDownEl = $('.js-dropdown');
  const form = new Form();
  let topMenuEl = $('.js-top-menu ul[data-depth="0"]');
  let dropDown = new DropDown(dropDownEl);
  let topMenu = new TopMenu(topMenuEl);
  let productMinitature = new ProductMinitature();
  let productSelect  = new ProductSelect();
  dropDown.init();
  form.init();
  topMenu.init();
  productMinitature.init();
  productSelect.init();
});

Webpack really is not my strong suit and I have searched all over but I can not find anything related to this error.

Any help would be much appreciated.

Body:
A colleague helped me figure it out in the end.
I needed to add the correct preset to the babel-loader query :

loaders: [{
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
            presets: ['es2015']
        }
    },


问:
Training The Ubuntu Dialog Corpus with chatterbot
How much time does it take to train the Ubuntu Dialog Corpus with chatterbot? How many examples are needed to train the bot well?</p>

答:
Current chatterbot train based on your input file size, if the train file is bigger it will take more time to train the bot.

There is no specific examples to train the bot, it will learn past user inputs and responds your answers


问:
How to make my application system
I need create my app as system, because i need get permission android.permission.WRITE_SECURE_SETTINGS.
After install to virtual device (Eclipse) my app appears in '/data/app'. I try manually move him to '/system/app', set rights 644, but when i launch my app - toast 'App isn't installed'. After reboot (close virtual device and restart) my app disappeared from '/system/app'.

Add:
- 1. Why android can not see my application in '/system/app'?
- 2. Why after restart virtual device my app disappeared from '/system/app'?

What the best way make my app system on Eclipse Emulator and real devices?

答:
If the device is not rooted, you cannot copy anything to the System or Data partitions.

With root do the following commands in a command prompt or linux shell and all should be fine:

```<code>adb push fileName /data/local/tmp
adb shell
su
mount -o remount, rw /system
cp /data/local/tmp/fileName /system/folderOfYourChoise
chmod 644 (if its an apk and you want the system to use it as a system app)
exit (exits the su shell)
exit (exits the adb shell)
adb reboot (to apply and see changes on the device)
</code>```

Title: How to make my application system

Body:
If the device is not rooted, you cannot copy anything to the System or Data partitions.

With root do the following commands in a command prompt or linux shell and all should be fine:

adb push fileName /data/local/tmp
adb shell
su
mount -o remount, rw /system
cp /data/local/tmp/fileName /system/folderOfYourChoise
chmod 644 (if its an apk and you want the system to use it as a system app)
exit (exits the su shell)
exit (exits the adb shell)
adb reboot (to apply and see changes on the device)


问:
Hide/show individual items inside ngFor in angular 2
I want to hide a span and show dropdown when span (Active) is click and after select the specific value hide the dropdown and again show span in the cell of the table for every span individually. how to achieve it?</p>

```<code><table class="table">
    <tbody>
        <tr *ngFor="let user of data | paginate: config; let i">
            <td class="row">
                <a [routerLink]="['/user-edit', user.Id]" style="text-transform: capitalize;">{{user.FirstName}} {{user.LastName}}</a><br />
                {{user.Email}}<br />
                <i class="fa fa-user"></i> Developer
            </td>
            <td style="width:15px;" *ngIf="user.IsActive==false"><br /><br /><b>Blocked</b></td>
            <td *ngIf="user.IsActive==true">
                <div class="inline-edit">
                    <span [hidden]="!isDisplay" (click)="beginEdit(editText,i)">
                        Active

                    </span>
                    <span>
                        <ng-select [items]="items"
                        (selected)="selected($event,i)">
                    </ng-select>
                </span>
            </div>
        </td>
    </tr>
</tbody>
</table>
</code>```

答:
you used the flag variable isDisplay, which is the same for every loop. add there some ID from user to distinct the flags for every loop. I am not sure, what beginEdit does, maybe you need to change it, too</p>

```<code><table class="table">
    <tbody>
        <tr *ngFor="let user of data | paginate: config; let i">
            <td class="row">
                <a [routerLink]="['/user-edit', user.Id]" style="text-transform: capitalize;">{{user.FirstName}} {{user.LastName}}</a><br />
                {{user.Email}}<br />
                <i class="fa fa-user"></i> Developer
            </td>
            <td style="width:15px;" *ngIf="user.IsActive==false"><br /><br /><b>Blocked</b></td>
            <td *ngIf="user.IsActive==true">
                <div class="inline-edit">
                    <span [hidden]="!isDisplay[user.id]" (click)="beginEdit(editText,i)">
                        Active

                    </span>
                    <span>
                        <ng-select [items]="items"
                                   (selected)="selected($event,i)">
                        </ng-select>
                    </span>
                </div>
            </td>
        </tr>
    </tbody>
</table>
</code>```

Body:
I want to hide a span and show dropdown when span (Active) is click and after select the specific value hide the dropdown and again show span in the cell of the table for every span individually. how to achieve it?

                {{user.FirstName}} {{user.LastName}}

                {{user.Email}}

                 Developer

Blocked

                        Active

                        <ng-select [items]="items"
                        (selected)="selected($event,i)">
                    </ng-select>

Body:
you used the flag variable isDisplay, which is the same for every loop. add there some ID from user to distinct the flags for every loop. I am not sure, what beginEdit does, maybe you need to change it, too

<table class="table">
    <tbody>
        <tr *ngFor="let user of data | paginate: config; let i">
            <td class="row">
                <a [routerLink]="['/user-edit', user.Id]" style="text-transform: capitalize;">{{user.FirstName}} {{user.LastName}}</a><br />
                {{user.Email}}<br />
                <i class="fa fa-user"></i> Developer
            </td>
            <td style="width:15px;" *ngIf="user.IsActive==false"><br /><br /><b>Blocked</b></td>
            <td *ngIf="user.IsActive==true">
                <div class="inline-edit">
                    <span [hidden]="!isDisplay[user.id]" (click)="beginEdit(editText,i)">
                        Active

                    </span>
                    <span>
                        <ng-select [items]="items"
                                   (selected)="selected($event,i)">
                        </ng-select>
                    </span>
                </div>
            </td>
        </tr>
    </tbody>
</table>


问:
Send Email to Edit MediaWiki
How can I enable this workflow:

Send an email to me@mywikiserver.com with the subject MyWikiPage

mywikiserver.com edits MyWikiPage and appends the email contents to the page

I'd like to avoid manually writing SQL statements to update the database.  For example, is there a Python library that can edit the MediaWiki on the server?

答: Here are three python mediawiki api accessing tools: http://www.mediawiki.org/wiki/API:Client_code#Python</p>

Title: Send Email to Edit MediaWiki


问:
GCP Autoscaler Instance Group Error: service account issue
I'm trying to create an instance group for autoscaling and after creation, there is this red icon with an exclamation point next to the instance group name, telling me the the service account xxx (this is the efault service account actually) is not associated with the project.

I don't get it, and I don't see how to fix this.

Does anybody know this one ?

答:
It seems that the Google APIs Service Account was missing permissions in your project.

The service account should be added to the project as part of activation of compute APIs. But it can be also manually deleted/added to your project.

The easiest procedure to enable it in your project (so grant Managed Instance Group permission to edit your instances) is to execute following script:

```<code>PROJECT_NAME=your-project-name

PROJECT_ID=`gcloud projects describe $PROJECT_NAME --format 'value(projectNumber)'`
gcloud projects add-iam-policy-binding ${PROJECT_NAME}  --member=serviceAccount:${PROJECT_ID}@cloudservices.gserviceaccount.com --role=roles/editor
</code>```

Alternatively you can configure it on IAM page of your project in the developer console.

Body:
It seems that the Google APIs Service Account was missing permissions in your project.

The service account should be added to the project as part of activation of compute APIs. But it can be also manually deleted/added to your project.

The easiest procedure to enable it in your project (so grant Managed Instance Group permission to edit your instances) is to execute following script:

PROJECT_NAME=your-project-name

PROJECT_ID=`gcloud projects describe $PROJECT_NAME --format 'value(projectNumber)'`
gcloud projects add-iam-policy-binding ${PROJECT_NAME}  --member=serviceAccount:${PROJECT_ID}@cloudservices.gserviceaccount.com --role=roles/editor

Alternatively you can configure it on IAM page of your project in the developer console.


问:
Django server side caching of uploaded file
I am running a server in django and I want to serve a file. I am storing the file under '/upload/directory/filename' and I return it using

```<code>from django.shortcuts import redirect

file_path = '/upload/directory/filename'
return redirect(file_path)
</code>```

However, the file appears to have been cached to the first version that had been placed locally and is never updated. Even if I remove the file, the file is still served. I checked that if I change the path to 'upload/directory_2/filename then I correctly get my new file. What is going on and how can I fight this ?

This is happening locally and I am making a direct server request (hence there is no possibility of browser caching or anything else).

Additional information:

I understand that maybe I should be using static files, although for instance this answer suggests that it is quite debatable for files that I am uploading myself.

When I say "I want to serve files with django" I just mean that I have associated a file path to a particular entity in my database (using models.FileField) and based on what the user requests I want to return this file. I kind of doubt this is a clear cut for using static files in that case.

There are many workarounds to my issue, like generating unique filenames every time I want to "clear my cache" or explicitly opening the file:

```<code>with open(absolute_file_path) as file:
    response = HttpResponse(file.read(), content_type='application/octet-stream')
</code>```

My question was about understanding why the particular piece of code above does what it does, i.e. leads to data caching, and how to prevent this.

答:
You must use django static facility to serve static files. On your local machine this is setup properly in settings to point a folder static in your app then you can point to the file using the static function.

All is explained here:

https://docs.djangoproject.com/en/1.11/howto/static-files/

In an url you access the code:

```<code>from django.templatetags.static import static
url_to_file = static('some_app/path/to_file')
</code>```

On a production machine the static files are served by a web server or a specific service like aws S3 or similar but not from django! For this reason the static facility is a must.

To avoid the cache, in case you have this problem, have a look at the never_cache decorator: https://docs.djangoproject.com/en/1.11/topics/http/decorators/#caching

Body:
I am running a server in django and I want to serve a file. I am storing the file under '/upload/directory/filename' and I return it using

from django.shortcuts import redirect

file_path = '/upload/directory/filename'
return redirect(file_path)

However, the file appears to have been cached to the first version that had been placed locally and is never updated. Even if I remove the file, the file is still served. I checked that if I change the path to 'upload/directory_2/filename then I correctly get my new file. What is going on and how can I fight this ?

This is happening locally and I am making a direct server request (hence there is no possibility of browser caching or anything else).

Additional information:

I understand that maybe I should be using static files, although for instance this answer suggests that it is quite debatable for files that I am uploading myself.

When I say "I want to serve files with django" I just mean that I have associated a file path to a particular entity in my database (using models.FileField) and based on what the user requests I want to return this file. I kind of doubt this is a clear cut for using static files in that case.

There are many workarounds to my issue, like generating unique filenames every time I want to "clear my cache" or explicitly opening the file:

with open(absolute_file_path) as file:
    response = HttpResponse(file.read(), content_type='application/octet-stream')

My question was about understanding why the particular piece of code above does what it does, i.e. leads to data caching, and how to prevent this.

Body:
You must use django static facility to serve static files. On your local machine this is setup properly in settings to point a folder static in your app then you can point to the file using the static function.

All is explained here:

https://docs.djangoproject.com/en/1.11/howto/static-files/

In an url you access the code:

from django.templatetags.static import static
url_to_file = static('some_app/path/to_file')

On a production machine the static files are served by a web server or a specific service like aws S3 or similar but not from django! For this reason the static facility is a must.

To avoid the cache, in case you have this problem, have a look at the never_cache decorator: https://docs.djangoproject.com/en/1.11/topics/http/decorators/#caching


问:
Visual Studio Azure Function Publishing function.json
I am new to Azure Functions, and attempting to put them to good use in conjunction with Blob Storage.

I have downloaded Visual Studio 2017 Preview which has given me access to creating an Azure Function project template (https://marketplace.visualstudio.com/items?itemName=AndrewBHall-MSFT.AzureFunctionToolsforVisualStudio2017)

Then following this example https://blogs.msdn.microsoft.com/webdev/2017/05/10/azure-function-tools-for-visual-studio-2017/ I am able to create a new Function in VS, then publish to Azure.

When I then look on Azure, I can see my new Function, but it just shows json from within a function.json file.

So this works fine when my Function code is just

```<code>public static void Run([BlobTrigger("images/{name}",
    Connection = "fakename_STORAGE")]Stream myBlob, string name, TraceWriter log)
</code>```

However, when I want to start playing around with outputs and I change my code to include out string myOutputBlob

```<code>public static void Run([BlobTrigger("images/{name}",
    Connection = "fakename_STORAGE")]Stream myBlob, string name, out string myOutputBlob, TraceWriter log)
</code>```

Then Publish to Azure, I see an error:

Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'myOutputBlob' to
  type String&. Make sure the parameter Type is supported by the
  binding.

I can get round this buy updating the function.json file on Azure to include additional information,

but every time I publish to Azure, this file is overwritten.

I have tried adding a function.json file to my project which matches the config required, but this does not work. Am I missing something?

How can I ensure the function.json file is not overwritten every time? Do I need to configure my project to allow me to manage the file?

答:
You have to decorate your output parameter with an attribute to configure what kind of output binding you need:

```<code>public static void Run(
    [BlobTrigger("images/{name}", Connection = "fakename_STORAGE")]Stream myBlob,
    string name,
    [Blob("images/copy-{name}", Connection = "fakename_STORAGE")]out string myOutputBlob,
    TraceWriter log)
</code>```

which will add the required lines in your function.json during the publish.

Body:
I am new to Azure Functions, and attempting to put them to good use in conjunction with Blob Storage.

I have downloaded Visual Studio 2017 Preview which has given me access to creating an Azure Function project template (https://marketplace.visualstudio.com/items?itemName=AndrewBHall-MSFT.AzureFunctionToolsforVisualStudio2017)

Then following this example https://blogs.msdn.microsoft.com/webdev/2017/05/10/azure-function-tools-for-visual-studio-2017/ I am able to create a new Function in VS, then publish to Azure.

When I then look on Azure, I can see my new Function, but it just shows json from within a function.json file.

So this works fine when my Function code is just

public static void Run([BlobTrigger("images/{name}",
    Connection = "fakename_STORAGE")]Stream myBlob, string name, TraceWriter log)

However, when I want to start playing around with outputs and I change my code to include out string myOutputBlob

public static void Run([BlobTrigger("images/{name}",
    Connection = "fakename_STORAGE")]Stream myBlob, string name, out string myOutputBlob, TraceWriter log)

Then Publish to Azure, I see an error:

Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'myOutputBlob' to
  type String&. Make sure the parameter Type is supported by the
  binding.

I can get round this buy updating the function.json file on Azure to include additional information,

but every time I publish to Azure, this file is overwritten.

I have tried adding a function.json file to my project which matches the config required, but this does not work. Am I missing something?

How can I ensure the function.json file is not overwritten every time? Do I need to configure my project to allow me to manage the file?

Body:
You have to decorate your output parameter with an attribute to configure what kind of output binding you need:

public static void Run(
    [BlobTrigger("images/{name}", Connection = "fakename_STORAGE")]Stream myBlob,
    string name,
    [Blob("images/copy-{name}", Connection = "fakename_STORAGE")]out string myOutputBlob,
    TraceWriter log)

which will add the required lines in your function.json during the publish.


问:
Populate a text field from a bash script
So I have a webform with a dropdown list, and a field that needs to be populated with the results of a very simple script that takes the option chosen from the dropdown list as imput. (The web server uses apache2 and bash, and a bit of js on the user side. And that is it. Unfortunatelly I can't install anything else on the machine.)

The dropdown menu is automatically populated correctly.
And when run as a separate bash script the bash function returns what it should.

All the html pieces are inserted on the web page and rendered correctly too.

The problem seems to be because I can't pass the value choseen on the dropdown menu, (processed by the javascript function) to the bash script function.

Any ideas?

There is two text files used as source, one for the dropdown menu:

STUFF.txt:

eggs

milk

flour

An another for the text field to be populated:

QUANTITY.txt:

eggs 12unit

milk 6Liters

flour 2Kg

Dropdown:

```<code>   if [[ "$User" == "$Authorized" ]];then
    echo "<td height=\"30\">$C_STUFF:</td><td colspan=\"3\" align=\"left\" cellpadding=\"0\"><select id=\"STUFF\" name=\"STUFF\" onChange=\"JS_stuff(this.value);\">"
    STUFF=/apache2/cgi-bin/STUFF.txt
    while IFS='' read -r line || [[ -n "$line" ]]; do
        echo "<option id=\"$line\" name=\"STUFF\" value=\"$line\">$line</option>"
    done < "$STUFF"
    echo "</select>"
    echo "</td><td>  </td>"
    fi
</code>```

Text Field:

```<code>echo "<td></td>
<td>Quantity:</td>
<td colspan=\"3\"><text id=\"quantity\" size=\"15\" type=\"quantity\" name=\"quantity\" value=\"$STUFF\" ></text></td></tr>
</code>```

Javascript function:

```<code>/****STUFF for the text field**********/
function JS_stuff(sel)
{
    var xhttp;
  if (str.length == 0) {
    document.getElementById("quantity").innerHTML = "";
    return;
 }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
  document.getElementById("quantity").innerHTML = this.responseText;
 }
 };
  xhttp.open("GET", "getquantity.sh?"+str, true);
  xhttp.send();
 }
</code>```

Bash script & Function:

SCRIPT:

```<code>#!/bin/bash
source ./functions.sh
getquantity $QUERY_STRING
</code>```

FUNCTION in functions.sh:

```<code> get_stuff_fromlist () {
    STUFF="$QUERY_STRING"
    QUANTITY=/apache2/cgi-bin/QUANTITY.txt
    while IFS= read -r line; do
        if [[ $line == $QUERY_STRING* ]] ; then
            printline="yes"
        fi
        if [[ $printline == "yes" ]] ; then
          QUANTITY=  echo "$line" | awk '{print $2}'
        fi
        if [[ $line == $QUERY_STRING* ]] ; then
            printline="no"
            echo "$STUFF"
        fi
    done < "$QUANTITY"
    }
</code>```

答:
At first, some generic comments.

I assume the bash script is run as CGI script.

Generally, interactive web pages with a bash backend is not a good idea for security reason. It's much easier to do some command injection and, as a result, compromise the server. I do not now the reasons why other stuff cannot be installed, but if you had been said  it's because of the security, then you should also avoid processing data fed from browser to server using bash.

As for the problem you mentioned. There are two solutions possible.

Solution 1 - not suitable for bash because of security reasons.

You need to have two scripts. One main script to generate the webform with dropdown. Other one, helper, to receive the stuff as a parameter and return the quantity. So, your javascript onChange handler will use  XMLHttpRequest() to run the helper script to get the quantity. Welcome in the AJAX world. Obvious drawback of this solution is that helper script is fed with data from browser, and the malicious user can spoof the request to provide its own value. In the helper script you need to make sure you won't accidentally run the code provided by such rascal. It's hard in bash, it's easier in other scripting languages.

Solution 2

Prepare your webform in a way it contains a javascript variable being an associative array with stuff and quantities. And onChange handler looks up this table and fills quantity appropriately. To develop needed code you can even write a static HTML file with all data encoded. Then, when you're happy with your javascript solution, generate the webpage using CGI script. This solution is good as long, as the amount of stuff is small (the threshold of being small is up to you). It runs on the client side, in browser, and does not make any additional requests to the server.

PS. In dropdown part of the script you are closing the </select> tag twice.

Body:
So I have a webform with a dropdown list, and a field that needs to be populated with the results of a very simple script that takes the option chosen from the dropdown list as imput. (The web server uses apache2 and bash, and a bit of js on the user side. And that is it. Unfortunatelly I can't install anything else on the machine.)

The dropdown menu is automatically populated correctly.
And when run as a separate bash script the bash function returns what it should.

All the html pieces are inserted on the web page and rendered correctly too.

The problem seems to be because I can't pass the value choseen on the dropdown menu, (processed by the javascript function) to the bash script function.

Any ideas?

There is two text files used as source, one for the dropdown menu:

STUFF.txt:

eggs

milk

flour

An another for the text field to be populated:

QUANTITY.txt:

eggs 12unit

milk 6Liters

flour 2Kg

Dropdown:

   if [[ "$User" == "$Authorized" ]];then
    echo "$C_STUFF:	<select id=\"STUFF\" name=\"STUFF\" onChange=\"JS_stuff(this.value);\">"
    STUFF=/apache2/cgi-bin/STUFF.txt
    while IFS='' read -r line || [[ -n "$line" ]]; do
        echo "<option id=\"$line\" name=\"STUFF\" value=\"$line\">$line</option>"
    done < "$STUFF"
    echo "</select>"
    echo "	  	"
    fi

Text Field:

echo "
Quantity:
<text id=\"quantity\" size=\"15\" type=\"quantity\" name=\"quantity\" value=\"$STUFF\" ></text>

Javascript function:

/****STUFF for the text field**********/
function JS_stuff(sel)
{
    var xhttp;
  if (str.length == 0) {
    document.getElementById("quantity").innerHTML = "";
    return;
 }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
  document.getElementById("quantity").innerHTML = this.responseText;
 }
 };
  xhttp.open("GET", "getquantity.sh?"+str, true);
  xhttp.send();
 }

Bash script & Function:

SCRIPT:

#!/bin/bash
source ./functions.sh
getquantity $QUERY_STRING

FUNCTION in functions.sh:

 get_stuff_fromlist () {
    STUFF="$QUERY_STRING"
    QUANTITY=/apache2/cgi-bin/QUANTITY.txt
    while IFS= read -r line; do
        if [[ $line == $QUERY_STRING* ]] ; then
            printline="yes"
        fi
        if [[ $printline == "yes" ]] ; then
          QUANTITY=  echo "$line" | awk '{print $2}'
        fi
        if [[ $line == $QUERY_STRING* ]] ; then
            printline="no"
            echo "$STUFF"
        fi
    done < "$QUANTITY"
    }


问:
C++ Variable doesn't change until thread finished
I wrote a very simple code to reproduce my problem.

```<code>#include <iostream>
#include "tools.h"  //contains s_sleep()
#include <thread>
using namespace std;

void change( int *i)
{
        while (true)
        {
                *i = 4356;
        }
}

int main()
{
        int v=3;
        cout << v <<endl;
        thread t(change, &v);
        s_sleep(1); //sleep one second
        cout << v << endl;
        t.join();
}
</code>```

The output is 3, and after a second 3 again. But when I change one line to

```<code>//while ( true )
</code>```

I receive 3, and a second later 4356.

How can that be?
Hope somebody can help.

答:
This might also be due to caching. You are first reading a variable frome one thread, then manipulating the variable from another thread and reading it again from the first thread. The compiler cannot know that it changed in the meantime.
To safely do this "v" has to be declared volatile.

Body:
I wrote a very simple code to reproduce my problem.

#include <iostream>
#include "tools.h"  //contains s_sleep()
#include <thread>
using namespace std;

void change( int *i)
{
        while (true)
        {
                *i = 4356;
        }
}

int main()
{
        int v=3;
        cout << v <<endl;
        thread t(change, &v);
        s_sleep(1); //sleep one second
        cout << v << endl;
        t.join();
}

The output is 3, and after a second 3 again. But when I change one line to

//while ( true )

I receive 3, and a second later 4356.

How can that be?
Hope somebody can help.


问:
JS hide div if it has a class added via JS
I am working on a code where an active class is added to a div via JS.

What I would like to do is, when that div has active class, hide another div. But, due to the active class was added via JS, this code doesn't work:

```<code>if($("#section3").hasClass("active")) {
    $(".menu").fadeOut("fast");
}
</code>```

I think I would need to use the on function: .on()

Something like this, but it's not working... Any ideas?

```<code>$("#section3").on( function() {
    $(this).hasClass('active') {
        $(".menu").fadeOut("fast");
    }
});
</code>```

EDITED:

I'm afraid I cannot paste the code because I am using a plugin. This is the one that I am using, so you can see the functionality there.

I've added this bullet menu to it:

```<code><ul id="menu">
    <li data-menuanchor="slide1"><a href="#slide1"><span></span></a></li>
    <li data-menuanchor="slide2"><a href="#slide2"><span></span></a></li>
    <li data-menuanchor="slide3"><a href="#slide3"><span></span></a></li>
    <li data-menuanchor="slide4"><a href="#slide4"><span></span></a></li>
</ul>
</code>```

Each slide has a active class when it's on viewport, so what I would like to achieve is when the last slider is active, hide the menu

答:
$(document).ready(function(){
$('section').click(function(){

$(this).addClass('active');
if($('section').hasClass('active')){

$('ul#menu').hide();

}
});

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>check</section>
<ul id="menu">
<li data-menuanchor="slide1"><span></span></li>
    <li data-menuanchor="slide2"><span></span></li>
    <li data-menuanchor="slide3"><span></span></li>
    <li data-menuanchor="slide4"><span></span></li>

</ul></code>```

Body:
I am working on a code where an active class is added to a div via JS.

What I would like to do is, when that div has active class, hide another div. But, due to the active class was added via JS, this code doesn't work:

if($("#section3").hasClass("active")) {
    $(".menu").fadeOut("fast");
}

I think I would need to use the on function: .on()

Something like this, but it's not working... Any ideas?

$("#section3").on( function() {
    $(this).hasClass('active') {
        $(".menu").fadeOut("fast");
    }
});

EDITED:

I'm afraid I cannot paste the code because I am using a plugin. This is the one that I am using, so you can see the functionality there.

I've added this bullet menu to it:

Each slide has a active class when it's on viewport, so what I would like to achieve is when the last slider is active, hide the menu

Body:
$(document).ready(function(){
$('section').click(function(){

$(this).addClass('active');
if($('section').hasClass('active')){

$('ul#menu').hide();

}
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>check</section>
<ul id="menu">
<li data-menuanchor="slide1"><a href="#slide1"><span></span></a></li>
    <li data-menuanchor="slide2"><a href="#slide2"><span></span></a></li>
    <li data-menuanchor="slide3"><a href="#slide3"><span></span></a></li>
    <li data-menuanchor="slide4"><a href="#slide4"><span></span></a></li>

</ul>


问:
Reverse selection in ArcPy?
I am trying to find out the counties that don't contain any stores in ArcGIS using python.

I have a point layer (representing the stores) and a polygon layer (counties). I have managed to write some code to find out the counties that DO contain the stores. The code is below.

```<code>import arcpy
arcpy.env.overwriteOutput = True
path="C:/Users/XARDAS/Documents/ArcGIS/Packages/Romania1000k_9E5B7FEC-6005-4D3A-81EA-E95FAACEF69E/v101/ro1mil.gdb"
arcpy.MakeFeatureLayer_management(path+"/Counties", "Counties_lyr")
arcpy.MakeFeatureLayer_management(path+"/Stores", "Stores_lyr")
arcpy.SelectLayerByAttribute_management("Stores_lyr", "NEW_SELECTION","Type=1")
arcpy.SelectLayerByLocation_management("Counties_lyr","INTERSECT","Stores_lyr",0,"NEW_SELECTION")
</code>```

So this gives me the counties that have stores but I would like to somehow inverse the intersection for the program to give me the ones that don't have any stores. I have thought about just deleting the selected counties but I don't think that it would be too nice.

答:
Since you have selected everything that you don't want selected, inverting (or switching) the selection will give you what you want. (ref help page)

Add this line at the end:

```<code>arcpy.SelectLayerByAttribute_management("Counties_lyr", "SWITCH_SELECTION")
</code>```

Title: Reverse selection in ArcPy?

Body:
I am trying to find out the counties that don't contain any stores in ArcGIS using python.

I have a point layer (representing the stores) and a polygon layer (counties). I have managed to write some code to find out the counties that DO contain the stores. The code is below.

import arcpy
arcpy.env.overwriteOutput = True
path="C:/Users/XARDAS/Documents/ArcGIS/Packages/Romania1000k_9E5B7FEC-6005-4D3A-81EA-E95FAACEF69E/v101/ro1mil.gdb"
arcpy.MakeFeatureLayer_management(path+"/Counties", "Counties_lyr")
arcpy.MakeFeatureLayer_management(path+"/Stores", "Stores_lyr")
arcpy.SelectLayerByAttribute_management("Stores_lyr", "NEW_SELECTION","Type=1")
arcpy.SelectLayerByLocation_management("Counties_lyr","INTERSECT","Stores_lyr",0,"NEW_SELECTION")

So this gives me the counties that have stores but I would like to somehow inverse the intersection for the program to give me the ones that don't have any stores. I have thought about just deleting the selected counties but I don't think that it would be too nice.

Body:
Since you have selected everything that you don't want selected, inverting (or switching) the selection will give you what you want. (ref help page)

Add this line at the end:

arcpy.SelectLayerByAttribute_management("Counties_lyr", "SWITCH_SELECTION")


问:
String vs string

Possible Duplicate:

  In C# what is the difference between String and string

Should I use string or String when declaring a basic string variable in c# and does it matter?

答:
The string keyword is an alias for System.String.

(The same goes for int - System.Int32 long - System.Int64 and so on)

C# doesn't have two different representations for primitives the same way that Java does. (Where an int is far different from an Integer)

In most cases it is best to use lowercase string because it is an alias to the fully qualified System.String.  This way you can avoid type conflicts if there is another String type somewhere in your code.

Title: String vs string


问:
increment is not happening in for loop in c
I had written a program in C in which the population of a town increases by 10% each year, but the variable pop is not incrementing in the for loop.

This is my code:

```<code>#include <stdio.h>

int main() { // B main
    int pop = 100000, year, popatend;
    printf("\nyear\t\t\tpopulation\n\n");
    for (year = 1; year <= 10; year++) { // B loop
        popatend = pop * (10 / 100);
        pop = pop + popatend;

        printf("%d\t\t\t %d\n", year, pop);
    } // B loop
} // B main
</code>```

And this is the output:

```<code>year            population

   1             100000
   2             100000
   3             100000
   4             100000
   5             100000
   6             100000
   7             100000
   8             100000
   9             100000
  10             100000
</code>```

I made this program in Eclipse, in ubuntu mate.

答: 10/100 is integer division, so 0.</p>

Body:
I had written a program in C in which the population of a town increases by 10% each year, but the variable pop is not incrementing in the for loop.

This is my code:

#include <stdio.h>

int main() { // B main
    int pop = 100000, year, popatend;
    printf("\nyear\t\t\tpopulation\n\n");
    for (year = 1; year <= 10; year++) { // B loop
        popatend = pop * (10 / 100);
        pop = pop + popatend;

        printf("%d\t\t\t %d\n", year, pop);
    } // B loop
} // B main

And this is the output:

year            population

   1             100000
   2             100000
   3             100000
   4             100000
   5             100000
   6             100000
   7             100000
   8             100000
   9             100000
  10             100000

I made this program in Eclipse, in ubuntu mate.

Body: 10/100 is integer division, so 0.


问:
Increment aaz to aba in PHP without getting an extra character --> aaz --> aaaa
So I have researched numerous sites but haven't come across a solid answer yet.
I need to:
Increment aaz to aba in PHP without getting an extra character aaz --> aaaa

This is the code i have used which is incrementing my code correctly until it gets to aaz then it goes to aaaa.
the full code im incrementing is AAA001

heres my code:

```<code><?php

$player_code_array =  array(
  'letter_3' => chr(65),
  'letter_2' => chr(65),
  'letter_1' => chr(65),
  'number_3' => '0',
  'number_2' => '0',
  'number_1' => '1'
);

$counter = 0;
while ($counter < 100000) {
$player_code =  $player_code_array['letter_3'].
                $player_code_array['letter_2'].
                $player_code_array['letter_1'].
                $player_code_array['number_3'].
                $player_code_array['number_2'].
                $player_code_array['number_1'];
        if ($player_code_array['number_1'] < 11) {
            $player_code_array['number_1']++;
            echo $player_code.'<br>';
        }if ($player_code_array['number_1'] == 10) {
            $player_code_array['number_1'] = 0;
            $player_code_array['number_2']++;
        }if ($player_code_array['number_2'] == 10) {
            $player_code_array['number_2'] = 0;
            $player_code_array['number_3']++;
        }if ($player_code_array['number_3'] == 10) {
            $player_code_array['number_3'] = 0;
            $player_code_array['letter_1']++;
        }if ($player_code_array['letter_1'] == 91) {
            $player_code_array['letter_1'] = 65;
        }if ($player_code_array['letter_2'] == 91) {
            $player_code_array['letter_2'] = 65;
            $player_code_array['letter_3']++;
        }if ($player_code_array['letter_3'] == 90) {
            $counter = 999999999999999999;
        }
$counter++;
}

?>
</code>```

The counter is looping it for me as many times as i need it top be looped.
so my code can get incremented.

答:
Please find below solution, this will help you out.

```<code><?php
for($i = 'aaa'; $i < 'zzz'; $i++){
  print "$i ";
}
?>
</code>```

Let me know if it not works for you or you need specific output.

Body:
So I have researched numerous sites but haven't come across a solid answer yet.
I need to:
Increment aaz to aba in PHP without getting an extra character aaz --> aaaa

This is the code i have used which is incrementing my code correctly until it gets to aaz then it goes to aaaa.
the full code im incrementing is AAA001

heres my code:

<?php

$player_code_array =  array(
  'letter_3' => chr(65),
  'letter_2' => chr(65),
  'letter_1' => chr(65),
  'number_3' => '0',
  'number_2' => '0',
  'number_1' => '1'
);

$counter = 0;
while ($counter < 100000) {
$player_code =  $player_code_array['letter_3'].
                $player_code_array['letter_2'].
                $player_code_array['letter_1'].
                $player_code_array['number_3'].
                $player_code_array['number_2'].
                $player_code_array['number_1'];
        if ($player_code_array['number_1'] < 11) {
            $player_code_array['number_1']++;
            echo $player_code.'
';
        }if ($player_code_array['number_1'] == 10) {
            $player_code_array['number_1'] = 0;
            $player_code_array['number_2']++;
        }if ($player_code_array['number_2'] == 10) {
            $player_code_array['number_2'] = 0;
            $player_code_array['number_3']++;
        }if ($player_code_array['number_3'] == 10) {
            $player_code_array['number_3'] = 0;
            $player_code_array['letter_1']++;
        }if ($player_code_array['letter_1'] == 91) {
            $player_code_array['letter_1'] = 65;
        }if ($player_code_array['letter_2'] == 91) {
            $player_code_array['letter_2'] = 65;
            $player_code_array['letter_3']++;
        }if ($player_code_array['letter_3'] == 90) {
            $counter = 999999999999999999;
        }
$counter++;
}

?>

The counter is looping it for me as many times as i need it top be looped.
so my code can get incremented.

Body:
Please find below solution, this will help you out.

<?php
for($i = 'aaa'; $i < 'zzz'; $i++){
  print "$i ";
}
?>

Let me know if it not works for you or you need specific output.


答:
When you do integer division:

```<code>  popatend=pop*(10/100);
</code>```

popatend will have a value of 0, since (10/100) will evaluate to 0.

So when you add it to pop, the value of pop will not change.

I believe this could be fixed by changing it to

```<code>  popatend=pop*(10f/100f);
</code>```

Title: increment is not happening in for loop in c

Body:
When you do integer division:

  popatend=pop*(10/100);

popatend will have a value of 0, since (10/100) will evaluate to 0.

So when you add it to pop, the value of pop will not change.

I believe this could be fixed by changing it to

  popatend=pop*(10f/100f);


问:
How do I incorporate Geolocation into the Google Places API?
I want to:

Render a google map on a web page;

Have the map centre on a user's current location;

Show places local to that user.

Question: Assuming this is possible (and that the limiting factor is my current ability), how might this be achieved?

Resources:

I am using the Google Maps JS API v3 and Places Library

Currently, I can achieve either rendering places around a hardcoded location or centring the map on the user.

I have used this Geolocation code and this Places Search code assuming that I could integrate the code of one into the other (by handing lat/long values from the geolocator into the location object pyrmont).

There exists a SO question on this for Google Maps API v2, deprecated by v3.

答:
First thing you need to do is define the map:

```<code><div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&libraries=places&callback=initMap" async defer></script>
</code>```

this tells us that we are using the places library and on callback we are going to call the initMap function.

```<code>function initMap() {
  var london = {
    lat: 51.5073509,
    lng: -0.12775829999998223
  };
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      london = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      map.setCenter(london);
      setPlaces(london);
    });
  } else {
    // Browser doesn't support Geolocation
    //since you set coords above this section it will default to that
    setPlaces(london);
  }
  map = new google.maps.Map(document.getElementById('map'), {
    center: london,
    zoom: 15
  });
}
</code>```

The initMap function initialises the map. We set var london to the co-ordinates of London in case the user does not have location turned on.

We then check to see if their location is turned on if (navigator.geolocation) {does this. if this is true then we override london to the users position. If changed we then move the map to the users location.

both outcomes will call:

```<code>function setPlaces(location) {
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: location,
    radius: 1000,
    type: ['store']
  }, callback);
}
</code>```

Which gets the places around the location (either user or predefined)

A working example can be seen here, for parameters etc just read the API.

JSFIDDLE: https://jsfiddle.net/4kgy68rg/1/

Body:
First thing you need to do is define the map:

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&libraries=places&callback=initMap" async defer></script>

this tells us that we are using the places library and on callback we are going to call the initMap function.

function initMap() {
  var london = {
    lat: 51.5073509,
    lng: -0.12775829999998223
  };
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      london = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      map.setCenter(london);
      setPlaces(london);
    });
  } else {
    // Browser doesn't support Geolocation
    //since you set coords above this section it will default to that
    setPlaces(london);
  }
  map = new google.maps.Map(document.getElementById('map'), {
    center: london,
    zoom: 15
  });
}

The initMap function initialises the map. We set var london to the co-ordinates of London in case the user does not have location turned on.

We then check to see if their location is turned on if (navigator.geolocation) {does this. if this is true then we override london to the users position. If changed we then move the map to the users location.

both outcomes will call:

function setPlaces(location) {
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: location,
    radius: 1000,
    type: ['store']
  }, callback);
}

Which gets the places around the location (either user or predefined)

A working example can be seen here, for parameters etc just read the API.

JSFIDDLE: https://jsfiddle.net/4kgy68rg/1/


问:
Is there a way to preload video using javascript?
I am developing a web app that is similar to an online version of power point. What I want to do is preload the previous and next slide while the user is viewing the current slide so that there is very little lag when clicking previous and next. </p>

<p>Each slide has the jwplayer on it to play audio that goes along with the slide. At this point I have javascript variables that act as a buffer and holds the html for the previous and next slides.  When the user clicks next I use jquery to replace the html currently displaying with the html in the buffer variable. At this point the jwplayer is created and the audio begins to buffer and then play. I would like to be able to buffer the audio when I put the html in the buffer. Is there a way to do that using javascript? </p>

答: Instead of caching the slides html source, actually embed their HTML into the page, but in an invisible div. When the user wants to see the next slide, make the old one invisible and the new one visible.</p>

Body:
I am developing a web app that is similar to an online version of power point. What I want to do is preload the previous and next slide while the user is viewing the current slide so that there is very little lag when clicking previous and next.

Each slide has the jwplayer on it to play audio that goes along with the slide. At this point I have javascript variables that act as a buffer and holds the html for the previous and next slides.  When the user clicks next I use jquery to replace the html currently displaying with the html in the buffer variable. At this point the jwplayer is created and the audio begins to buffer and then play. I would like to be able to buffer the audio when I put the html in the buffer. Is there a way to do that using javascript?


问:
Using Angular CLI and unable to use relative image paths in CSS files
Have setup an angular app using the angular CLI and have created a component that has an image in the components directory.

For example:

```<code>app/
---/common-components
------/header
---------/header.component.ts
---------/header.component.css
---------/images
--------------/image.png
</code>```

Within the CSS file I am using the following style:

```<code>.image {
    background-url: url('images/image.png');
}
</code>```

When I run the application it gives me a 304 Not Modified and the image does not show up int he preview.  If I use an absolute path '/src/app/common-components/header/images' the file loads properly.  However, this is not ideal since I would like the component to be self sufficient.

The response that is given is:

```<code>Request URL:http://localhost:4201/images/test-image.jpeg
Request Method:GET
Status Code:304 Not Modified
Remote Address:127.0.0.1:4201
</code>```

With a blank preview

答:
It seems to be still an issue with angular-CLI and webpack (using 1.0.3).

If you add the asset folder to the angular-cli.json and define the path relatively, the build still fails, not finding the ressources url('someRelativeLink').

I used a work around and put all CSS definitions in:

```<code>@Component({
  styles: [...]
})
</code>```

Instead of a styleUrls file.

After doinig that everything was fine.

Body:
Have setup an angular app using the angular CLI and have created a component that has an image in the components directory.

For example:

app/
---/common-components
------/header
---------/header.component.ts
---------/header.component.css
---------/images
--------------/image.png

Within the CSS file I am using the following style:

.image {
    background-url: url('images/image.png');
}

When I run the application it gives me a 304 Not Modified and the image does not show up int he preview.  If I use an absolute path '/src/app/common-components/header/images' the file loads properly.  However, this is not ideal since I would like the component to be self sufficient.

The response that is given is:

Request URL:http://localhost:4201/images/test-image.jpeg
Request Method:GET
Status Code:304 Not Modified
Remote Address:127.0.0.1:4201

With a blank preview

Body:
It seems to be still an issue with angular-CLI and webpack (using 1.0.3).

If you add the asset folder to the angular-cli.json and define the path relatively, the build still fails, not finding the ressources url('someRelativeLink').

I used a work around and put all CSS definitions in:

@Component({
  styles: [...]
})

Instead of a styleUrls file.

After doinig that everything was fine.


答: You have integer division, 10/100 will be truncated to zero. Use 10.0 / 100.0 (or plain 0.1) instead.


问:
how to convert latitude and longitude to pixels
I have two sets of Lat and Long values corresponding to two corners of a rectangle (top left and bottom right). I want to load a image in the rectangle and as the user clicks on the locations on the rectangle/image, it should return a latitude and longitude (from the detected pixel's coordinates). What should be the calculation to convert pixels to lat and long, given the above spot of inputs.

答:
Assuming linear interpolation is good enough for your purposes, you can use following formula:

```<code>out = (in - inMin) * (outMax - outMin) / (inMax - inMin) + outMin
</code>```

where in* are image coordinates and out* are map coordinates.

You have to use formula twice; once for horizontal and once for vertical coordinate.

Body:
Assuming linear interpolation is good enough for your purposes, you can use following formula:

out = (in - inMin) * (outMax - outMin) / (inMax - inMin) + outMin

where in* are image coordinates and out* are map coordinates.

You have to use formula twice; once for horizontal and once for vertical coordinate.


问:
async Volley StringRequest in RxJava2?
I want to fetch data from server through Volley StringRequest in RxJava2, But I could not find that how create an Observable for it.

In some articles I found that Observable.fromCallable is useful without any sample.

Please tell me How can I call an async Volley stringRequest with RxJava2 ??

mention:I don't want to use Future.

答: Reading the doc, http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Single.html#fromCallable(java.util.concurrent.Callable) is for wrapping synchronous request. Since StringRequest is asynchronous, you are looking for Observable.create or better in your case Single.create. Since it's an little advanced part of RxJava, I suggest you to look to already existing wrapper like VolleyX or RxVolley or even native RxJava alternatives to Volley.

Title: async Volley StringRequest in RxJava2?


问:
Black screen when executing test app on Tizen Emulator
I'm starting to work with Tizen and I'm following its tutorials. When I test my apps, they only get with a black screen when I open them on the emulator, and I don't know why is that.

Would someone know what can cause this, and how to solve it?
I'm using Windows 7 64bits, I've installed the Intel Haxm and enabled the virtualization. The emulator seems to work fine, but, I still get this problem with my apps.

Thank you for the help.

答:
I have similar issue. In my case the root cause was incorrect work of CPU virtualization.
My Lenovo laptop had Intel Core i7 on board which supports virtualization. But it worked incorrectly. To fix the issue I did the following steps:

Disabled virtualization in BIOS and restarted Windows.

Enabled virtualization in BIOS.

Created new Emulator.

Hope this will be useful.


问:
jquery/javascript - hide div if containing image is broken
i have a div with the class 'userFeatureProductImage'. this div is repeated however occasionally a broken image might come through so i want to hide the div as a precaution if this does happen. how can i do this?</p>

答: jQuery equivalent of PHP's file_exists()?</p>