问:
NSTableview inside NSPopover looks different as standalone
I created a class ListView, that is a very simple Tableview.

If I instantiate it with IB everything looks fine.
The same if I instantiate it programmatically.

If I instantiate it programmatically inside a NSPopover, I get a light grey background for every row of my table.

Where does this come from?

Here the code:

```<code>class ViewController: NSViewController {
    let popover = NSPopover()

    @IBOutlet weak var label: NSTextField!
    @IBAction func bu1(_ sender: Any) {
        popover.show(relativeTo: label.visibleRect, of: label, preferredEdge: NSRectEdge.maxY)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let scrollListView = NSScrollView()
        let listView = ListView(frame: NSRect(x:100, y: 100, width: 100, height: 100))
        scrollListView.documentView = listView

        let viewController = NSViewController()
        viewController.view = scrollListView

        popover.appearance = NSAppearance(named: NSAppearance.Name.vibrantLight)
        popover.animates = false
        popover.contentViewController = viewController
    }
}

class ListView: NSTableView, NSTableViewDataSource, NSTableViewDelegate {
    private var list = ["Tom","Jack","Susi"]

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setup()
    }

    private func setup() {
        selectionHighlightStyle = NSTableView.SelectionHighlightStyle.regular
        rowSizeStyle = NSTableView.RowSizeStyle.small
        intercellSpacing = NSMakeSize(10.0, 0.0)
        headerView = nil
        target = self

        backgroundColor = NSColor.white
        for column in tableColumns {
            removeTableColumn(column)
        }
        let column1 = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "text"))
        column1.isEditable = false
        column1.width = 200
        addTableColumn(column1)

        delegate = self
        dataSource = self

        self.reloadData()
    }

    func numberOfRows(in tableView: NSTableView) -> Int {
        return list.count
    }

    func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
        return NSTableRowView()
    }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var cellView = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "MyView"), owner: self) as? NSTableCellView
        if cellView == nil {
            cellView = NSTableCellView(frame: NSZeroRect)
            let textField = NSTextField(frame: NSZeroRect)
            textField.isBezeled = false
            textField.drawsBackground = false
            textField.isEditable = false
            textField.isSelectable = false
            cellView!.addSubview(textField)
            cellView!.textField = textField
            cellView!.identifier = NSUserInterfaceItemIdentifier(rawValue: "MyView")
        }
        cellView!.textField!.stringValue = list[row]

        return cellView
    }
}
</code>```

答:
I have the same problem. The issue appears in fact in all items I place inside a NSPopover.
Setting the appearance to aqua, popover.appearance = NSAppearance(named: NSAppearance.Name.aqua), resolves the issue a bit.
But now the popover isn't updated when you change between light and dark mode...

Body:
I created a class ListView, that is a very simple Tableview.

If I instantiate it with IB everything looks fine.
The same if I instantiate it programmatically.

If I instantiate it programmatically inside a NSPopover, I get a light grey background for every row of my table.

Where does this come from?

Here the code:

class ViewController: NSViewController {
    let popover = NSPopover()

    @IBOutlet weak var label: NSTextField!
    @IBAction func bu1(_ sender: Any) {
        popover.show(relativeTo: label.visibleRect, of: label, preferredEdge: NSRectEdge.maxY)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let scrollListView = NSScrollView()
        let listView = ListView(frame: NSRect(x:100, y: 100, width: 100, height: 100))
        scrollListView.documentView = listView

        let viewController = NSViewController()
        viewController.view = scrollListView

        popover.appearance = NSAppearance(named: NSAppearance.Name.vibrantLight)
        popover.animates = false
        popover.contentViewController = viewController
    }
}

class ListView: NSTableView, NSTableViewDataSource, NSTableViewDelegate {
    private var list = ["Tom","Jack","Susi"]

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setup()
    }

    private func setup() {
        selectionHighlightStyle = NSTableView.SelectionHighlightStyle.regular
        rowSizeStyle = NSTableView.RowSizeStyle.small
        intercellSpacing = NSMakeSize(10.0, 0.0)
        headerView = nil
        target = self

        backgroundColor = NSColor.white
        for column in tableColumns {
            removeTableColumn(column)
        }
        let column1 = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "text"))
        column1.isEditable = false
        column1.width = 200
        addTableColumn(column1)

        delegate = self
        dataSource = self

        self.reloadData()
    }

    func numberOfRows(in tableView: NSTableView) -> Int {
        return list.count
    }

    func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
        return NSTableRowView()
    }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var cellView = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "MyView"), owner: self) as? NSTableCellView
        if cellView == nil {
            cellView = NSTableCellView(frame: NSZeroRect)
            let textField = NSTextField(frame: NSZeroRect)
            textField.isBezeled = false
            textField.drawsBackground = false
            textField.isEditable = false
            textField.isSelectable = false
            cellView!.addSubview(textField)
            cellView!.textField = textField
            cellView!.identifier = NSUserInterfaceItemIdentifier(rawValue: "MyView")
        }
        cellView!.textField!.stringValue = list[row]

        return cellView
    }
}


来源: stackexchange

问:
Trying to write `map` using `foldr`
I had an exam where I was forced to create the function map using foldr
I know by now there is a wirde and short way to do it which is map f = foldr ((:) . f) [].
My shot was

```<code>map' :: (a->b) -> [a] ->[b]
map' f [] = []
map' f [x] = foldr f x [] : []
map' f (x:xs) (foldr f x []) ++ map' f xs
</code>```

my problem is that f need to be of type a->b->b and it is a->b.
How can i force it to work? how can i change f to fit this implemention?

答:
It seems that you want to apply foldr on one element, then recursively adds up the result.

It seems the ability of foldr to accumulate is not used.

To implement map by foldr, you will want the accumulated result by foldr to be like a mapped list.

So that's why in the short way foldr fold (:).f (a->[b]->[b]) instead of f (a->b).

After you apply f onto an element x, then you will want to make it as an accumulated result (:) (f x) [] => (f x):[] => [f x]

```<code>foldr ((:).f) [] [x1,x2,x3] = (f x1):(f x2):(f x3):[] = [f x1, f x2, f x3] = map f [x1,x2,x3].
</code>```

Edit:

Recursion without foldr

```<code>map' f [] = []
map' f [x] = [f x]
map' f (x:xs) = map' f [x] ++ map' f xs
</code>```

So if you really want to use both recursion and foldr:

```<code>map' :: (a->b) -> [a] ->[b]
map' f [] = []
map' f [x] = foldr ((:).f) [] [x]
map' f (x:xs) = (foldr ((:).f) [] [x]) ++ map' f xs

f :: a -> b
(:).f :: a -> [b] -> [b]
</code>```

Then every time foldr will only be applied to one element. It will just be like [f x].

ContentLicense: CC BY-SA 3.0

Title: Trying to write `map` using `foldr`

Body:
I had an exam where I was forced to create the function map using foldr
I know by now there is a wirde and short way to do it which is map f = foldr ((:) . f) [].
My shot was

map' :: (a->b) -> [a] ->[b]
map' f [] = []
map' f [x] = foldr f x [] : []
map' f (x:xs) (foldr f x []) ++ map' f xs

my problem is that f need to be of type a->b->b and it is a->b.
How can i force it to work? how can i change f to fit this implemention?

Body:
It seems that you want to apply foldr on one element, then recursively adds up the result.

It seems the ability of foldr to accumulate is not used.

To implement map by foldr, you will want the accumulated result by foldr to be like a mapped list.

So that's why in the short way foldr fold (:).f (a->[b]->[b]) instead of f (a->b).

After you apply f onto an element x, then you will want to make it as an accumulated result (:) (f x) [] => (f x):[] => [f x]

foldr ((:).f) [] [x1,x2,x3] = (f x1):(f x2):(f x3):[] = [f x1, f x2, f x3] = map f [x1,x2,x3].

Edit:

Recursion without foldr

map' f [] = []
map' f [x] = [f x]
map' f (x:xs) = map' f [x] ++ map' f xs

So if you really want to use both recursion and foldr:

map' :: (a->b) -> [a] ->[b]
map' f [] = []
map' f [x] = foldr ((:).f) [] [x]
map' f (x:xs) = (foldr ((:).f) [] [x]) ++ map' f xs

f :: a -> b
(:).f :: a -> [b] -> [b]

Then every time foldr will only be applied to one element. It will just be like [f x].


问:
Match node with specific Ancestor Xpath Xslt
So my question will seems fairly simple to any XSLT/XPATH veteran but I didn't found any post about it so here it is.

What is the correct XPATH syntax to select nodes with specific ancestor ?

Let say I want all "country" nodes that have "europe" as ancestor (not direct parent), I've tried many different syntaxes but can't find the right one neither the ressources to help me resolve this.

Thanks a lot for your time.

答: match="europe//country" will match country elements with a europe ancestor.


问:
Angular 4 multiple dropdown selected
What I want to do is selected of multiple select.

Below is my HTML

```<code><div class="form-group"  *ngIf="edituserForm">
   <label for="exampleFormControlSelect2">User</label>
   <select multiple  class="form-control" id="exampleFormControlSelect1" name="user_id" #user_id="ngModel" [(ngModel)]="this.edituser_id" required>
       <option *ngFor="let user of users;" [value]="user.user_id" [selected]="this.edituser_id == user.user_id">{{user.employee_no}}</option>
   </select>
</div>

{{this.edituser_id}}

<button type="button" (click)="edit()">Edit</button>
</code>```

My Component

```<code>edituser_id: any = [];
edituserForm: boolean = false;

edit(){
 this.edituserForm = true;
 this.edituser_id = ["1","2"];
}
</code>```

Below is the screen which always selected the 1st user without the 2nd user

And below is what I want in my screen

I already try a lot of ways, but still cannot make it. Hope you guys can help and really appreciate it.

答:
You can do this in your template:</p>

```<code><div class="form-group"  *ngIf="edituserForm">
    <label for="exampleFormControlSelect2">User</label>
    <select multiple  class="form-control" id="exampleFormControlSelect1" name="user_id" #user_id="ngModel" [(ngModel)]="edituser_id" required>
        <option *ngFor="let user of users;" [value]="user.user_id" [selected]="edituser_id.includes(user.user_id)">{{user.employee_no}}</option>
    </select>
</div>
</code>```

Title: Angular 4 multiple dropdown selected

Body:
What I want to do is selected of multiple select.

Below is my HTML

   User
   <select multiple  class="form-control" id="exampleFormControlSelect1" name="user_id" #user_id="ngModel" [(ngModel)]="this.edituser_id" required>
       <option *ngFor="let user of users;" [value]="user.user_id" [selected]="this.edituser_id == user.user_id">{{user.employee_no}}</option>
   </select>

{{this.edituser_id}}

<button type="button" (click)="edit()">Edit</button>

My Component

edituser_id: any = [];
edituserForm: boolean = false;

edit(){
 this.edituserForm = true;
 this.edituser_id = ["1","2"];
}

Below is the screen which always selected the 1st user without the 2nd user

And below is what I want in my screen

I already try a lot of ways, but still cannot make it. Hope you guys can help and really appreciate it.

Body:
You can do this in your template:

<div class="form-group"  *ngIf="edituserForm">
    <label for="exampleFormControlSelect2">User</label>
    <select multiple  class="form-control" id="exampleFormControlSelect1" name="user_id" #user_id="ngModel" [(ngModel)]="edituser_id" required>
        <option *ngFor="let user of users;" [value]="user.user_id" [selected]="edituser_id.includes(user.user_id)">{{user.employee_no}}</option>
    </select>
</div>


问:
Parse CSV file of links to php array, feed these links to simplehtmldom
I have a php code that will read and parse csv files into a multiline array, what i need to do next is to take this array and let simplehtmldom fire off a crawler to return some company stocks info.

The php code for the CSV parser is

```<code>$arrCSV = array();
// Opening up the CSV file
if (($handle = fopen("NASDAQ.csv", "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
   // Count the total keys in each row $data is the variable for each line of the array
$c = count($data);
   //Populate the array
   for ($x=0;$x<$c;$x++) {
   $arrCSV[$key][$x] = $data[$x];
   }
   $key++;
} // end while
// Close the CSV file
fclose($handle);
} // end if
echo "```";
echo print_r($arrCSV);
echo "```";
</code>```

This works great and parses the array line by line, $data being the variable for each line. What i need to do now is to get this to be read via simplehtmldom, which is where it breaks down, im looking at using this code or something very similar, im pretty inexperienced at this but guess i would be needing a foreach statement somewhere along the line.

This is the simplehtmldom code

```<code>$html = file_get_html($data);
$html->find('div[class="detailsDataContainerLt"]');
$tickerdetails = ("$es[0]");
$FileHandle2 = fopen($data, 'w') or die("can't open file");
fwrite($FileHandle2, $tickerdetails);
fclose($FileHandle2);
fclose($handle);
</code>```

So my qyestion is how can i get them both working together, i jave checked out simplehtmldom manual page several times and find it a littlebit vague in this area, the simplehtmldom code above is what i use in another function but by direclty linking so i know that it works.

regards
Martin

答:
Your loop could be reduced to (yes, it's the same):

```<code>while ($data = fgetcsv($handle, 0, ',')) {
    $arrCSV[] = $data;
}
</code>```

Using SimpleXML instead of SimpleDom (Since it's standard PHP):

```<code>foreach ($arrCSV as $row) {
    $xml = simplexml_load_file($row[0]); // Change 0 to the index of the url
    $result = $xml->xpath('//div[contains(concat(" ", @class, " "), " detailsDataContainerLt")]');
    if ($result->length > 0) {
        $file = fopen($row[1], '2'); // Change 1 to the filename you want to write to
        if ($file) {
            fwrite($file, (string) $result->item(0));
            fclose($file);
        }
    }
}
</code>```

that should do it if I understood correctly...

ContentLicense: CC BY-SA 2.5

Body:
I have a php code that will read and parse csv files into a multiline array, what i need to do next is to take this array and let simplehtmldom fire off a crawler to return some company stocks info.

The php code for the CSV parser is

$arrCSV = array();
// Opening up the CSV file
if (($handle = fopen("NASDAQ.csv", "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
   // Count the total keys in each row $data is the variable for each line of the array
$c = count($data);
   //Populate the array
   for ($x=0;$x<$c;$x++) {
   $arrCSV[$key][$x] = $data[$x];
   }
   $key++;
} // end while
// Close the CSV file
fclose($handle);
} // end if
echo "
";
echo print_r($arrCSV);
echo "
";

This works great and parses the array line by line, $data being the variable for each line. What i need to do now is to get this to be read via simplehtmldom, which is where it breaks down, im looking at using this code or something very similar, im pretty inexperienced at this but guess i would be needing a foreach statement somewhere along the line.

This is the simplehtmldom code

$html = file_get_html($data);
$html->find('div[class="detailsDataContainerLt"]');
$tickerdetails = ("$es[0]");
$FileHandle2 = fopen($data, 'w') or die("can't open file");
fwrite($FileHandle2, $tickerdetails);
fclose($FileHandle2);
fclose($handle);

So my qyestion is how can i get them both working together, i jave checked out simplehtmldom manual page several times and find it a littlebit vague in this area, the simplehtmldom code above is what i use in another function but by direclty linking so i know that it works.

regards
Martin

Body:
Your loop could be reduced to (yes, it's the same):

while ($data = fgetcsv($handle, 0, ',')) {
    $arrCSV[] = $data;
}

Using SimpleXML instead of SimpleDom (Since it's standard PHP):

foreach ($arrCSV as $row) {
    $xml = simplexml_load_file($row[0]); // Change 0 to the index of the url
    $result = $xml->xpath('//div[contains(concat(" ", @class, " "), " detailsDataContainerLt")]');
    if ($result->length > 0) {
        $file = fopen($row[1], '2'); // Change 1 to the filename you want to write to
        if ($file) {
            fwrite($file, (string) $result->item(0));
            fclose($file);
        }
    }
}

that should do it if I understood correctly...


问:
Why are these semicolumns in this for loop?
I was just looking at W3schools, and was looking at the "for loops". I saw this code example:

```<code>var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
for (;cars[i];) {
    text += cars[i] + "<br>";
    i++;
}
document.getElementById("demo").innerHTML = text;
</code>```

I saw these semicolumns in the "for loop", I removed them and tried running it again. And as you expect, I got an error. Why are these semicolumns there? This is the first time I saw this and I'm really curious why these need to be there.

Thanks if you can give me some information about this because I couldn't find anything about it...

答:
The idea structure of for loop should be:

for(<init>;<condition>;<operation after each iteration>)

where as:

init: will be perform once before the loop

condition: will be checked as truthness to enter every time

operation after each iteration: will be perform after every iteration

and they are optional.

For the particular example, init operation you are doing before with var i=0 and operation after each iteration you are doing manually as i++ so it is expected to run properly.

Body:
I was just looking at W3schools, and was looking at the "for loops". I saw this code example:

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
for (;cars[i];) {
    text += cars[i] + "
";
    i++;
}
document.getElementById("demo").innerHTML = text;

I saw these semicolumns in the "for loop", I removed them and tried running it again. And as you expect, I got an error. Why are these semicolumns there? This is the first time I saw this and I'm really curious why these need to be there.

Thanks if you can give me some information about this because I couldn't find anything about it...


问:
How to change course owner using Classroom.Courses.patch()
I'm trying to use Apps Script to change the owner of a Google Classroom course.

According to the documentation I can do it using .patch(). This is the relevant script:

```<code>   var body = {
     ownerId: owner
   }
   var mask={
     mask:'ownerId'
   }
       var optArgs = (mask, body);

    var course = {
      name: classname,
      courseState: state,
      description: desc,
      descriptionHeading: descHead,
      room: room,
      section: section
    };
       Classroom.Courses.patch(course, courseId,  optArgs )
</code>```

When I run it to update the owner I get the following error message

Could not be updated Invalid JSON payload received. Unknown name "ownerId": Cannot bind query parameter. Field 'ownerId' could not be found in request message.

Just to demonstrate a contrast, when I run .update() instead:

```<code>Classroom.Courses.update(course, courseId)
</code>```

...the rest of the course details are updated perfectly, however .update() doesn't allow you to change the owner; it has to be a .patch() to do that.

答:
Based on documentation, this is working as intended.

courses.update has no ownerId parameters, only id.

But if you check courses.patch it has the updateMask parameter which accepts ownerId as a valid field.

For detailed information on this service, see the reference documentation for the Classroom API.

Body:
I'm trying to use Apps Script to change the owner of a Google Classroom course.

According to the documentation I can do it using .patch(). This is the relevant script:

   var body = {
     ownerId: owner
   }
   var mask={
     mask:'ownerId'
   }
       var optArgs = (mask, body);

    var course = {
      name: classname,
      courseState: state,
      description: desc,
      descriptionHeading: descHead,
      room: room,
      section: section
    };
       Classroom.Courses.patch(course, courseId,  optArgs )

When I run it to update the owner I get the following error message

Could not be updated Invalid JSON payload received. Unknown name "ownerId": Cannot bind query parameter. Field 'ownerId' could not be found in request message.

Just to demonstrate a contrast, when I run .update() instead:

Classroom.Courses.update(course, courseId)

...the rest of the course details are updated perfectly, however .update() doesn't allow you to change the owner; it has to be a .patch() to do that.


问:
Exception in main class in Spring Boot Application
I am trying to make a simple spring boot application following this tutorial...
https://www.javatpoint.com/spring-maven-project

But getting this error when I finally run it. I have no idea what is going on. I updated the dependencies and then this happened.

```<code>  Exception in thread "main" java.lang.StackOverflowError
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:269)
        at org.apache.log4j.Category.<init>(Category.java:57)
        at org.apache.log4j.Logger.<init>(Logger.java:37)
        at org.apache.log4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:43)
        at org.apache.log4j.LogManager.getLogger(LogManager.java:45)
        at org.slf4j.impl.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:66)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:270)
</code>```

And the list goes on and on.
Please help.

答:
You have mistakenly added slf4j-log4j12 to the application. Log4j replaced by log4j-over-slf4j and slf4j implemented by log4j, so they call each other.

You should get the following message before StackOverflowError:

```<code>Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting the StackOverflowError.
</code>```

Body:
I am trying to make a simple spring boot application following this tutorial...
https://www.javatpoint.com/spring-maven-project

But getting this error when I finally run it. I have no idea what is going on. I updated the dependencies and then this happened.

  Exception in thread "main" java.lang.StackOverflowError
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:269)
        at org.apache.log4j.Category.<init>(Category.java:57)
        at org.apache.log4j.Logger.<init>(Logger.java:37)
        at org.apache.log4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:43)
        at org.apache.log4j.LogManager.getLogger(LogManager.java:45)
        at org.slf4j.impl.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:66)
        at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:270)

And the list goes on and on.
Please help.

Body:
You have mistakenly added slf4j-log4j12 to the application. Log4j replaced by log4j-over-slf4j and slf4j implemented by log4j, so they call each other.

You should get the following message before StackOverflowError:

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting the StackOverflowError.


问:
React Native Modal With Status Bar Show
I using react-native 0.48.4 and using react-native-phone-input for phone number input. I found the module have using Modal. When Modal show, StatusBar are hidden, I tried to set StatusBar.setHidden(false); , StatusBar still hidden. How do make the StatusBar show when Modal called.

```<code><Modal
  animationType={'slide'}
  transparent
  visible={this.state.modalVisible}
  onRequestClose={() => {console.log("Country picker has been closed.")}}
>

</Modal>
</code>```

答:
Personally i'm using the react-native modal repository provided by the react community for my modals implementation.

It handles a lot of default behaviour and provides a lot of feature, fully hackable.

When using this lib, to solve your problem, it would be a simple :

```<code><Modal style={style.modal}>
  <View style={{ flex: 1 }}>
    <Text>Hello!</Text>
  </View>
</Modal>
</code>```

I personally apply this styling

```<code>modal: {
 backgroundColor: 'white',
 marginHorizontal: 0,
 marginBottom: 0,
 borderBottomLeftRadius: 0,
 borderBottomRightRadius: 0,
 borderTopLeftRadius: 10,
 borderTopRightRadius: 10,
 overflow: 'hidden',
}
</code>```

To have something like:

I hope this answer will help you. Do not hesitate to ask more questions if you need further details.

Title: React Native Modal With Status Bar Show

Body:
I using react-native 0.48.4 and using react-native-phone-input for phone number input. I found the module have using Modal. When Modal show, StatusBar are hidden, I tried to set StatusBar.setHidden(false); , StatusBar still hidden. How do make the StatusBar show when Modal called.

<Modal
  animationType={'slide'}
  transparent
  visible={this.state.modalVisible}
  onRequestClose={() => {console.log("Country picker has been closed.")}}
>

</Modal>

Body:
Personally i'm using the react-native modal repository provided by the react community for my modals implementation.

It handles a lot of default behaviour and provides a lot of feature, fully hackable.

When using this lib, to solve your problem, it would be a simple :

<Modal style={style.modal}>
  <View style={{ flex: 1 }}>
    <Text>Hello!</Text>
  </View>
</Modal>

I personally apply this styling

modal: {
 backgroundColor: 'white',
 marginHorizontal: 0,
 marginBottom: 0,
 borderBottomLeftRadius: 0,
 borderBottomRightRadius: 0,
 borderTopLeftRadius: 10,
 borderTopRightRadius: 10,
 overflow: 'hidden',
}

To have something like:

I hope this answer will help you. Do not hesitate to ask more questions if you need further details.


问:
Input as number in JavaScript prompt
Can we customize a prompt box in JavaScript so it takes time as input?</p>

```<code>var r = prompt("ENTER THE NUMBER OF SECONDS AFTER WHICH YOU WANT TO BE REMINDED");
</code>```

答:
Maybe some beginner code will help</p>

```<code>function input() {
   var n = Number(prompt("ENTER THE NUMBER OF SECONDS AFTER WHICH YOU WANT TO BE REMINDED"));
   if (isNaN(n)) //Check what number it is
       return input();
   }

   input(); // Your prompt
}
</code>```

Title: Input as number in JavaScript prompt

Body:
Can we customize a prompt box in JavaScript so it takes time as input?

var r = prompt("ENTER THE NUMBER OF SECONDS AFTER WHICH YOU WANT TO BE REMINDED");

Body:
Maybe some beginner code will help

function input() {
   var n = Number(prompt("ENTER THE NUMBER OF SECONDS AFTER WHICH YOU WANT TO BE REMINDED"));
   if (isNaN(n)) //Check what number it is
       return input();
   }

   input(); // Your prompt
}


问:
Mysql, Hibernate - When insert to table, it says Field doesn't have a default values
I'm using Hibernate, MySQL, Spring MVC.

My current job is booking a flight ticket.

I got a flight schedule entity from path variable. And, I got a passenger entity from HttpSession.

Below is the controller code:

```<code>@RequestMapping("/booking/{results[0].flightscheduleId}")
public String bookBoardingPass
    (@PathVariable("results[0].flightscheduleId") Integer flightId, HttpSession session) {

    Passenger passenger = (Passenger) session.getAttribute("user");
    FlightSchedule flightSchedule = this.flightScheduleService.get(flightId);

    this.boardingPassService.booking(flightSchedule, passenger);

    return "search";
}
</code>```

Below is booking method code:

```<code>@Override
public void booking (FlightSchedule flightSchedule, Passenger passenger) {

    BoardingPass ticket = new BoardingPass();
    ticket.setFlightschedule(flightSchedule);
    ticket.setPassenger(passenger);

    System.out.println("flight id: "+flightSchedule.getFlightscheduleId());
    System.out.println("passenger id: "+passenger.getPassengerId());

    this.persist(ticket);
    //sessionFactory.getCurrentSession().saveOrUpdate(ticket);
}
</code>```

in booking method, I can print both flightSchedule's id and passenger's id.

But, when I execute 'persist' method, it says Field 'flightschedule_id' doesn't have a default value

In the persist method, it runs sessionFactory.getCurrentSession().saveOrUpdate(ticket);

flightschedule_id is a primary key, auto-increment, not-null.

I cannot give it a default value. Also, I check STRICT mode(?) on phpmyadmin through googling search result. (I am not sure I do well. Anyway it didn't work).

How can I solve this problem?

EDIT:

Below is BoardingPass class:

```<code>@Entity
@Table
public class BoardingPass implements java.io.Serializable {

private Integer boardingpassId;
private FlightSchedule flightschedule;
private Passenger passenger;

public BoardingPass() {
}

public BoardingPass(FlightSchedule flightschedule, Passenger passenger) {
    this.flightschedule = flightschedule;
    this.passenger = passenger;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getBoardingpassId() {
    return this.boardingpassId;
}

public void setBoardingpassId(Integer boardingpassId) {
    this.boardingpassId = boardingpassId;
}

@ManyToOne
@MapsId("flightscheduleId")
public FlightSchedule getFlightschedule() {
    return this.flightschedule;
}

public void setFlightschedule(FlightSchedule flightschedule) {
    this.flightschedule = flightschedule;
}

@ManyToOne
@MapsId("passengerId")
public Passenger getPassenger() {
    return this.passenger;
}

public void setPassenger(Passenger passenger) {
    this.passenger = passenger;
}

}
</code>```

Just in case, I add part of FlightSchedule and Passenger class.

Below is FlightSchedule.java :

```<code>@Entity
@Table
public class FlightSchedule implements java.io.Serializable {

private Integer flightscheduleId;
private Date depDay;
private Date depTime;
private Date arrDay;
private Date arrTime;
private Double flightTime;
private Integer price;
private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);
private Airplane airplane;
private Airport depAirport;
private Airport arrAirport;

public FlightSchedule() {
}

public FlightSchedule(Date depDay, Date depTime, Date arrDay, Date arrTime, Integer price) {
    this.depDay = depDay;
    this.depTime = depTime;
    this.arrDay = arrDay;
    this.arrTime = arrTime;
    this.price = price;
}

public FlightSchedule(Date depDay, Date depTime, Date arrDay, Date arrTime, Double flightTime, Integer price,
        Set<BoardingPass> boardingPasses, Airplane airplane, Airport depAirport, Airport arrAirport) {
    this.depDay = depDay;
    this.depTime = depTime;
    this.arrDay = arrDay;
    this.arrTime = arrTime;
    this.flightTime = flightTime;
    this.price = price;
    this.boardingPasses = boardingPasses;
    this.airplane = airplane;
    this.depAirport = depAirport;
    this.arrAirport = arrAirport;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getFlightscheduleId() {
    return this.flightscheduleId;
}

public void setFlightscheduleId(Integer flightscheduleId) {
    this.flightscheduleId = flightscheduleId;
}

@OneToMany(mappedBy = "flightschedule", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BoardingPass> getBoardingPasses() {
    return this.boardingPasses;
}

public void setBoardingPasses(Set<BoardingPass> boardingPasses) {
    this.boardingPasses = boardingPasses;
}

.... getters and setters...

}
</code>```

Below is Passenger.java:

```<code>@Entity
@Table
public class Passenger implements java.io.Serializable {

private Integer passengerId;
private String password;
private String passportNo;
private String passengerName;
private Date birth;
private Integer mileage;
private String contact;
private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);

public Passenger() {
}

public Passenger(String password, String passportNo, Date birth, Integer mileage) {
    this.password = password;
    this.passportNo = passportNo;
    this.birth = birth;
    this.mileage = mileage;
}

public Passenger(String password, String passportNo, String passengerName, Date birth, Integer mileage, String contact, Set<BoardingPass> boardingPasses) {
    this.password = password;
    this.passportNo = passportNo;
    this.passengerName = passengerName;
    this.birth = birth;
    this.mileage = mileage;
    this.contact = contact;
    this.boardingPasses = boardingPasses;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getPassengerId() {
    return this.passengerId;
}

public void setPassengerId(Integer passengerId) {
    this.passengerId = passengerId;
}

@OneToMany(mappedBy = "passenger", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BoardingPass> getBoardingPasses() {
    return this.boardingPasses;
}

public void setBoardingPasses(Set<BoardingPass> boardingPasses) {
    this.boardingPasses = boardingPasses;
}

.... getters and setters...

}
</code>```

答:
If you didn't specify PRIMARY KEY column as AUTO_INCREMENT then you have to give values manually in your Database. Make your flightschedule_id column which is the Primary key as AUTO_INCREMENT then it should work.
Hope this will help. Thank you.

Body:
I'm using Hibernate, MySQL, Spring MVC.

My current job is booking a flight ticket.

I got a flight schedule entity from path variable. And, I got a passenger entity from HttpSession.

Below is the controller code:

@RequestMapping("/booking/{results[0].flightscheduleId}")
public String bookBoardingPass
    (@PathVariable("results[0].flightscheduleId") Integer flightId, HttpSession session) {

    Passenger passenger = (Passenger) session.getAttribute("user");
    FlightSchedule flightSchedule = this.flightScheduleService.get(flightId);

    this.boardingPassService.booking(flightSchedule, passenger);

    return "search";
}

Below is booking method code:

@Override
public void booking (FlightSchedule flightSchedule, Passenger passenger) {

    BoardingPass ticket = new BoardingPass();
    ticket.setFlightschedule(flightSchedule);
    ticket.setPassenger(passenger);

    System.out.println("flight id: "+flightSchedule.getFlightscheduleId());
    System.out.println("passenger id: "+passenger.getPassengerId());

    this.persist(ticket);
    //sessionFactory.getCurrentSession().saveOrUpdate(ticket);
}

in booking method, I can print both flightSchedule's id and passenger's id.

But, when I execute 'persist' method, it says Field 'flightschedule_id' doesn't have a default value

In the persist method, it runs sessionFactory.getCurrentSession().saveOrUpdate(ticket);

flightschedule_id is a primary key, auto-increment, not-null.

I cannot give it a default value. Also, I check STRICT mode(?) on phpmyadmin through googling search result. (I am not sure I do well. Anyway it didn't work).

How can I solve this problem?

EDIT:

Below is BoardingPass class:

@Entity
@Table
public class BoardingPass implements java.io.Serializable {

private Integer boardingpassId;
private FlightSchedule flightschedule;
private Passenger passenger;

public BoardingPass() {
}

public BoardingPass(FlightSchedule flightschedule, Passenger passenger) {
    this.flightschedule = flightschedule;
    this.passenger = passenger;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getBoardingpassId() {
    return this.boardingpassId;
}

public void setBoardingpassId(Integer boardingpassId) {
    this.boardingpassId = boardingpassId;
}

@ManyToOne
@MapsId("flightscheduleId")
public FlightSchedule getFlightschedule() {
    return this.flightschedule;
}

public void setFlightschedule(FlightSchedule flightschedule) {
    this.flightschedule = flightschedule;
}

@ManyToOne
@MapsId("passengerId")
public Passenger getPassenger() {
    return this.passenger;
}

public void setPassenger(Passenger passenger) {
    this.passenger = passenger;
}

}

Just in case, I add part of FlightSchedule and Passenger class.

Below is FlightSchedule.java :

@Entity
@Table
public class FlightSchedule implements java.io.Serializable {

private Integer flightscheduleId;
private Date depDay;
private Date depTime;
private Date arrDay;
private Date arrTime;
private Double flightTime;
private Integer price;
private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);
private Airplane airplane;
private Airport depAirport;
private Airport arrAirport;

public FlightSchedule() {
}

public FlightSchedule(Date depDay, Date depTime, Date arrDay, Date arrTime, Integer price) {
    this.depDay = depDay;
    this.depTime = depTime;
    this.arrDay = arrDay;
    this.arrTime = arrTime;
    this.price = price;
}

public FlightSchedule(Date depDay, Date depTime, Date arrDay, Date arrTime, Double flightTime, Integer price,
        Set<BoardingPass> boardingPasses, Airplane airplane, Airport depAirport, Airport arrAirport) {
    this.depDay = depDay;
    this.depTime = depTime;
    this.arrDay = arrDay;
    this.arrTime = arrTime;
    this.flightTime = flightTime;
    this.price = price;
    this.boardingPasses = boardingPasses;
    this.airplane = airplane;
    this.depAirport = depAirport;
    this.arrAirport = arrAirport;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getFlightscheduleId() {
    return this.flightscheduleId;
}

public void setFlightscheduleId(Integer flightscheduleId) {
    this.flightscheduleId = flightscheduleId;
}

@OneToMany(mappedBy = "flightschedule", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BoardingPass> getBoardingPasses() {
    return this.boardingPasses;
}

public void setBoardingPasses(Set<BoardingPass> boardingPasses) {
    this.boardingPasses = boardingPasses;
}

.... getters and setters...

}

Below is Passenger.java:

@Entity
@Table
public class Passenger implements java.io.Serializable {

private Integer passengerId;
private String password;
private String passportNo;
private String passengerName;
private Date birth;
private Integer mileage;
private String contact;
private Set<BoardingPass> boardingPasses = new HashSet<BoardingPass>(0);

public Passenger() {
}

public Passenger(String password, String passportNo, Date birth, Integer mileage) {
    this.password = password;
    this.passportNo = passportNo;
    this.birth = birth;
    this.mileage = mileage;
}

public Passenger(String password, String passportNo, String passengerName, Date birth, Integer mileage, String contact, Set<BoardingPass> boardingPasses) {
    this.password = password;
    this.passportNo = passportNo;
    this.passengerName = passengerName;
    this.birth = birth;
    this.mileage = mileage;
    this.contact = contact;
    this.boardingPasses = boardingPasses;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getPassengerId() {
    return this.passengerId;
}

public void setPassengerId(Integer passengerId) {
    this.passengerId = passengerId;
}

@OneToMany(mappedBy = "passenger", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BoardingPass> getBoardingPasses() {
    return this.boardingPasses;
}

public void setBoardingPasses(Set<BoardingPass> boardingPasses) {
    this.boardingPasses = boardingPasses;
}

.... getters and setters...

}


问:
Assign function arguments to `self`
I've noticed that a common pattern I use is to assign SomeClass.__init__() arguments to self attributes of the same name. Example:

```<code>class SomeClass():
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
</code>```

In fact it must be a common task for others as well as PyDev has a shortcut for this - if you place the cursor on the parameter list and click Ctrl+1 you're given the option to Assign parameters to attributes which will create that boilerplate code for you.

Is there a different, short and elegant way to perform this assignment?

答:
One of the problems with @user3638162's answer is that locals() contain the 'self' variable. Hence, you end up with an extra self.self. If one doesn't mind the extra self, that solution can simply be

```<code>class X:
    def __init__(self, a, b, c):
        self.__dict__.update(locals())

x = X(1, 2, 3)
print(x.a, x.__dict__)
</code>```

The self can be removed after construction by del self.__dict__['self']

Alternatively, one can remove the self during construction using dictionary comprehensions introduced in Python3

```<code>class X:
    def __init__(self, a, b, c):
        self.__dict__.update(l for l in locals().items() if l[0] != 'self')

x = X(1, 2, 3)
print(x.a, x.__dict__)
</code>```

Title: Assign function arguments to `self`

Body:
I've noticed that a common pattern I use is to assign SomeClass.__init__() arguments to self attributes of the same name. Example:

class SomeClass():
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

In fact it must be a common task for others as well as PyDev has a shortcut for this - if you place the cursor on the parameter list and click Ctrl+1 you're given the option to Assign parameters to attributes which will create that boilerplate code for you.

Is there a different, short and elegant way to perform this assignment?

Body:
One of the problems with @user3638162's answer is that locals() contain the 'self' variable. Hence, you end up with an extra self.self. If one doesn't mind the extra self, that solution can simply be

class X:
    def __init__(self, a, b, c):
        self.__dict__.update(locals())

x = X(1, 2, 3)
print(x.a, x.__dict__)

The self can be removed after construction by del self.__dict__['self']

Alternatively, one can remove the self during construction using dictionary comprehensions introduced in Python3

class X:
    def __init__(self, a, b, c):
        self.__dict__.update(l for l in locals().items() if l[0] != 'self')

x = X(1, 2, 3)
print(x.a, x.__dict__)


问:
Load async images in tableview with different cell height. Swift
The thing is i am making a request that brings me back some images with different height that i want to autoresize each cell according to each image, but when i paint them in the tableview, show wrong cell height ias all of them has same size, until i scroll them. The matter is that i had put UITableViewAutomaticDimension, estimate, autolayout constraints are ok.. and so on. But as images are receiving 2 or 3 secs after tableview has been loaded, i cannot refresh tableview nor reload it.

Any idea how can i fix this problem?

答:
The table view needs to refresh the cell heights now. Calling beginUpdates() and endUpdates() will force the table view to refresh the heights.

```<code>tableView.beginUpdates()
// set your image in cell here
tableView.endUpdates()
</code>```

There is also pretty nice tutorial:
Self-sizing Table View Cells

Body:
The table view needs to refresh the cell heights now. Calling beginUpdates() and endUpdates() will force the table view to refresh the heights.

tableView.beginUpdates()
// set your image in cell here
tableView.endUpdates()

There is also pretty nice tutorial:
Self-sizing Table View Cells


问:
How to sum up elements of a C++ vector?
What are the good ways of finding the sum of all the elements in a std::vector?

Suppose I have a vector std::vector<int> vector with a few elements in it. Now I want to find the sum of all the elements. What are the different ways for the same?

答:
One can also use std::valarray<T> like this

```<code>#include<iostream>
#include<vector>
#include<valarray>

int main()
{
    std::vector<int> seq{ 1,2,3,4,5,6,7,8,9,10 };
    std::valarray<int> seq_add{ seq.data(), seq.size() };
    std::cout << "sum = " << seq_add.sum() << "\n";

    return 0;
}
</code>```

Some may not find this way efficient since the size of valarray needs to be as big as the size of the vector and initializing valarray will also take time.

In that case, don't use it and take it as yet another way of summing up the sequence.

Title: How to sum up elements of a C++ vector?

Body:
One can also use std::valarray<T> like this

#include<iostream>
#include<vector>
#include<valarray>

int main()
{
    std::vector<int> seq{ 1,2,3,4,5,6,7,8,9,10 };
    std::valarray<int> seq_add{ seq.data(), seq.size() };
    std::cout << "sum = " << seq_add.sum() << "\n";

    return 0;
}

Some may not find this way efficient since the size of valarray needs to be as big as the size of the vector and initializing valarray will also take time.

In that case, don't use it and take it as yet another way of summing up the sequence.

ContentLicense: CC BY-SA 4.0


问:
Wordpress API, React : this.state.project.title is undefined
I work on a project with a Backend Wordpress and a front-end react.

But when I'm trying to get the title.rendered from the Json Data I have this :

TypeError: this.state.project.title is undefined

I can see that the data exist in the react web extension :

screenshot:

So I don't why I have this error.

Here's my code, thanks for help ;) :

```<code>import React, { Component } from 'react';
import {LoadingSpin} from "./LoadingSpin";

export class Project extends Component {
constructor(){
    super();
    this.state = {
        project: [],
        loading: true
    }
}
componentDidMount() {
    let dataURL = "http://api.florentbruziaux.com/wp-json/wp/v2/portefolio_projects/"+ this.props.match.params.id + "?_embed";
    fetch(dataURL)
        .then(res => res.json())
        .then(res => {
            this.setState({
                project: res,
                loading:false
            })
        });

}
render(){
    let ahah = this.state.project.title.rendered;
    console.log(ahah);

    return (
        <div>
            { (this.state.loading) ? <LoadingSpin/> : null}
            <h1 className="title"> </h1>
        </div>
    );
}
</code>```

}

答: componentDidMount() is called after the component is mounted, so there is an initial render before it gets called. project will not have been loaded in this first call to render. You need to handle this case. You already have state.loading, so don't try and access anything on project while loading is true.

Body:
I work on a project with a Backend Wordpress and a front-end react.

But when I'm trying to get the title.rendered from the Json Data I have this :

TypeError: this.state.project.title is undefined

I can see that the data exist in the react web extension :

screenshot:

So I don't why I have this error.

Here's my code, thanks for help ;) :

import React, { Component } from 'react';
import {LoadingSpin} from "./LoadingSpin";

export class Project extends Component {
constructor(){
    super();
    this.state = {
        project: [],
        loading: true
    }
}
componentDidMount() {
    let dataURL = "http://api.florentbruziaux.com/wp-json/wp/v2/portefolio_projects/"+ this.props.match.params.id + "?_embed";
    fetch(dataURL)
        .then(res => res.json())
        .then(res => {
            this.setState({
                project: res,
                loading:false
            })
        });

}
render(){
    let ahah = this.state.project.title.rendered;
    console.log(ahah);

    return (

            { (this.state.loading) ? <LoadingSpin/> : null}

    );
}

}


问:
Google Apps Script - App is not verified, @OnlyCurrentDoc slows down script massively
Since a few months ago, users who make a copy are confronted by a "This app is not verified" screen when authorising the App Script to run. I understand that this is due to Google changing the security, but I can't figure out a way to properly get rid of the unverified status. This is what I tried:

Verify my project as the developer. This did not work, since when people make a copy of the spreadsheet it is a new project which they own themselves - and naturally other users haven't verified the project when they just created it by copying it.

Add @OnlyCurrentDoc to the top of the spreadsheet. This technically works, but only adding @OnlyCurrentDoc causes the run-time of the script to go from 4 seconds to 180 seconds.

A copy of the spreadsheet can be made at https://wowaudit.com/copy, and this is the code of the script that triggers the "Unverified App" message and takes so much longer to run with the @OnlyCurrentDoc snippet added:

```<code>/**
 * @OnlyCurrentDoc
 */

function CreateTrigger() {
  // First delete old triggers
  var allTriggers = ScriptApp.getProjectTriggers();
  for (var i = 0; i < allTriggers.length; i++) {
    ScriptApp.deleteTrigger(allTriggers[i]);
  }

  // Then create new triggers
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var interval = sheet.getRange("RefreshSetting").getValue().slice(0,2);
  ScriptApp.newTrigger("Fetch").timeBased().everyMinutes(interval).create();
  ScriptApp.newTrigger("Refresh").forSpreadsheet(sheet).onEdit().create();

  // Then give user feedback of success
  if (ScriptApp.getProjectTriggers().length == 2) {
    sheet.getRange('Settings!B24').setValue('The sheet is automatically refreshing!');
    sheet.getRange('Settings!B24').setBackground('#b6d7a8');
  } else {
    sheet.getRange('Settings!B24').setValue('Click here to start automatic refreshing!');
    sheet.getRange('Settings!B24').setBackground('#ea9999');
  }
}
</code>```

Does anyone know of a method to stop the "Unverified App" message from appearing in my scenario, or why the @OnlyCurrentDoc flag would slow down the script so much (basically making it unusable)?

Details:

I have a spreadsheet that fetches data from an API through an App Script on a time-based trigger, which other users can make a copy of to see their own data (thousands of people are using it). The script is very simple, it fetches data through UrlFetchApp.fetch() and puts it in the spreadsheet, and it has a function that people can invoke to set up the time-based trigger after they first copy the spreadsheet (triggers can't be copied).

答:
This is the intended behavior when you're just testing your app. If you want to get rid of this message, you can:

Publishing your app as an Add-on

Own a domain and have verified ownership with Google

Body:
Since a few months ago, users who make a copy are confronted by a "This app is not verified" screen when authorising the App Script to run. I understand that this is due to Google changing the security, but I can't figure out a way to properly get rid of the unverified status. This is what I tried:

Verify my project as the developer. This did not work, since when people make a copy of the spreadsheet it is a new project which they own themselves - and naturally other users haven't verified the project when they just created it by copying it.

Add @OnlyCurrentDoc to the top of the spreadsheet. This technically works, but only adding @OnlyCurrentDoc causes the run-time of the script to go from 4 seconds to 180 seconds.

A copy of the spreadsheet can be made at https://wowaudit.com/copy, and this is the code of the script that triggers the "Unverified App" message and takes so much longer to run with the @OnlyCurrentDoc snippet added:

/**
 * @OnlyCurrentDoc
 */

function CreateTrigger() {
  // First delete old triggers
  var allTriggers = ScriptApp.getProjectTriggers();
  for (var i = 0; i < allTriggers.length; i++) {
    ScriptApp.deleteTrigger(allTriggers[i]);
  }

  // Then create new triggers
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var interval = sheet.getRange("RefreshSetting").getValue().slice(0,2);
  ScriptApp.newTrigger("Fetch").timeBased().everyMinutes(interval).create();
  ScriptApp.newTrigger("Refresh").forSpreadsheet(sheet).onEdit().create();

  // Then give user feedback of success
  if (ScriptApp.getProjectTriggers().length == 2) {
    sheet.getRange('Settings!B24').setValue('The sheet is automatically refreshing!');
    sheet.getRange('Settings!B24').setBackground('#b6d7a8');
  } else {
    sheet.getRange('Settings!B24').setValue('Click here to start automatic refreshing!');
    sheet.getRange('Settings!B24').setBackground('#ea9999');
  }
}

Does anyone know of a method to stop the "Unverified App" message from appearing in my scenario, or why the @OnlyCurrentDoc flag would slow down the script so much (basically making it unusable)?

Details:

I have a spreadsheet that fetches data from an API through an App Script on a time-based trigger, which other users can make a copy of to see their own data (thousands of people are using it). The script is very simple, it fetches data through UrlFetchApp.fetch() and puts it in the spreadsheet, and it has a function that people can invoke to set up the time-based trigger after they first copy the spreadsheet (triggers can't be copied).


问:
C# modifying instance variables of a class in another form
For a project of mine I am building the game of life in visual studio forms. The problem I am currently facing is that I am not sure where to initialize my class objects so that their values can be modified by other forms.

This is my base form class where I am displaying the board game and current stats of the players:

```<code>public partial class Life : Form
{
    public Game game;

    public Life()
    {
        game = new Game();
        InitializeComponent();
    }

    private void Life_Load(object sender, EventArgs e)
    {
        Txt_BlueMoney.Text = game.player1.money.ToString();
        Txt_RedMoney.Text = game.player2.money.ToString();
    }

    private void Btn_Start_Click(object sender, EventArgs e)
    {
        StartGame sg = new StartGame();
        sg.Show();

    }
}
</code>```

My Game class is just a class that contains instances of other classes:

```<code>public class Game
{
    public Board board;
    public BoardSpaceEvent boardEvent;
    public Player player1;
    public Player player2;

    public Game()
        : base()
    {
        board = new Board();
        boardEvent = new BoardSpaceEvent();
        player1 = new Player();
        player2 = new Player();
    }

}
</code>```

and here is an example of one of the classes that Game initializes in case its of any importance:

```<code>public class Player : BoardSpaceEvent
{
    // might need to add getter and setter to access these variables
    public bool endOfTurn;
    public int currentSpace;
    public int numChildren;
    public int money;
    public int advanceSpaces;
    public List<int> playerLifeCards;
    public string career; // superstar, agent, teacher, athlete, salesperson, doctor, accountant, artist, police
    public int salary;
    public int taxes;
    public bool autoInsurance;
    public bool houseInsurance;

    public Player()
        : base()
    {
        endOfTurn = false; // might need to switch this
        currentSpace = 0;
        money = 10000; // will have to change this to whatever you start with
        numChildren = 0;
        advanceSpaces = 0; // make sure to pass this as reference
        playerLifeCards = new List<int> { };
        career = "";
        salary = 0;
        taxes = 0;
        autoInsurance = false;
        houseInsurance = false;
    }
}
</code>```

now what I am trying to do is open another form in which the user must pick between two buttons, and each of these buttons will modify the classes instance variables. What is the best way to do this? Here is what I have so far (my comment shows what I want to do):

```<code>public partial class StartGame : Form
{
    public StartGame()
    {
        InitializeComponent();
    }

    private void Btn_College_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You've chosen college");
        // this is where I want to update a players money variable in the Player class
        this.Close();
    }

    private void Btn_Job_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You've chosen job");
    }
}
</code>```

I have tried passing as reference and it did not work. Maybe I did it wrong though. I also tried inheriting from the main form, but the problem with that is the background is also inherited. I have looked into using static instances, but isn't this bad practice? Thanks in advance!

答:
Give the class StartGame a second constructor which can take a Game object as parameter and a local variable of type Game localGame;.

Then you can pass the public Game game; from the class Life when you open the StartGame Form:

```<code>private void Btn_Start_Click(object sender, EventArgs e)
{
    StartGame sg = new StartGame(game);
    sg.Show();
}
</code>```

Simply assign the passed parameter in the StartGame constructor to the local variable and you will be able to use it in your Btn_College_Click method.

Hope this helps. If it is not clear drop me a comment

EDIT:

I also tried inheriting from the main form, but the problem with that is the background is also inherited.

Even if inheritance would be possible it would not solve your problem. Each child would have its own personal instance ofGame` which is different from the object that the parent has. So changing the childs object would not influence the object of the parent.

Imagine your child inherits your hair colour. Now if you colour the hair of your child to a different on what will happen to your hair ?=!

Body:
For a project of mine I am building the game of life in visual studio forms. The problem I am currently facing is that I am not sure where to initialize my class objects so that their values can be modified by other forms.

This is my base form class where I am displaying the board game and current stats of the players:

public partial class Life : Form
{
    public Game game;

    public Life()
    {
        game = new Game();
        InitializeComponent();
    }

    private void Life_Load(object sender, EventArgs e)
    {
        Txt_BlueMoney.Text = game.player1.money.ToString();
        Txt_RedMoney.Text = game.player2.money.ToString();
    }

    private void Btn_Start_Click(object sender, EventArgs e)
    {
        StartGame sg = new StartGame();
        sg.Show();

    }
}

My Game class is just a class that contains instances of other classes:

public class Game
{
    public Board board;
    public BoardSpaceEvent boardEvent;
    public Player player1;
    public Player player2;

    public Game()
        : base()
    {
        board = new Board();
        boardEvent = new BoardSpaceEvent();
        player1 = new Player();
        player2 = new Player();
    }

}

and here is an example of one of the classes that Game initializes in case its of any importance:

public class Player : BoardSpaceEvent
{
    // might need to add getter and setter to access these variables
    public bool endOfTurn;
    public int currentSpace;
    public int numChildren;
    public int money;
    public int advanceSpaces;
    public List<int> playerLifeCards;
    public string career; // superstar, agent, teacher, athlete, salesperson, doctor, accountant, artist, police
    public int salary;
    public int taxes;
    public bool autoInsurance;
    public bool houseInsurance;

    public Player()
        : base()
    {
        endOfTurn = false; // might need to switch this
        currentSpace = 0;
        money = 10000; // will have to change this to whatever you start with
        numChildren = 0;
        advanceSpaces = 0; // make sure to pass this as reference
        playerLifeCards = new List<int> { };
        career = "";
        salary = 0;
        taxes = 0;
        autoInsurance = false;
        houseInsurance = false;
    }
}

now what I am trying to do is open another form in which the user must pick between two buttons, and each of these buttons will modify the classes instance variables. What is the best way to do this? Here is what I have so far (my comment shows what I want to do):

public partial class StartGame : Form
{
    public StartGame()
    {
        InitializeComponent();
    }

    private void Btn_College_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You've chosen college");
        // this is where I want to update a players money variable in the Player class
        this.Close();
    }

    private void Btn_Job_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You've chosen job");
    }
}

I have tried passing as reference and it did not work. Maybe I did it wrong though. I also tried inheriting from the main form, but the problem with that is the background is also inherited. I have looked into using static instances, but isn't this bad practice? Thanks in advance!

Body:
Give the class StartGame a second constructor which can take a Game object as parameter and a local variable of type Game localGame;.

Then you can pass the public Game game; from the class Life when you open the StartGame Form:

private void Btn_Start_Click(object sender, EventArgs e)
{
    StartGame sg = new StartGame(game);
    sg.Show();
}

Simply assign the passed parameter in the StartGame constructor to the local variable and you will be able to use it in your Btn_College_Click method.

Hope this helps. If it is not clear drop me a comment

EDIT:

I also tried inheriting from the main form, but the problem with that is the background is also inherited.

Even if inheritance would be possible it would not solve your problem. Each child would have its own personal instance ofGame` which is different from the object that the parent has. So changing the childs object would not influence the object of the parent.

Imagine your child inherits your hair colour. Now if you colour the hair of your child to a different on what will happen to your hair ?=!


问:
precompiled static library
I want to add a pre-compiled static C library (it was not compiled by the Android toolchain) to my Android project and give the library file rwx permissions. can this be done without root access?</p>

答: There is absolutely no reason to change file permissions for a static library. This file only exists on your build machine. You must build a shared library (file with .so extension) and make sure it is packed into your APK. You don't need to worry about file permissions for the shared library: the system installer will unpack this file into the expected location on the device, and apply appropriate permissions there. This file will be globally readable, but neither the file nor its directory will be writeable, even from your app.

Title: precompiled static library


问:
webRTC one to one audio call examples
I am trying to make a one to one audio call using webRTC.
I have been looking through some of the source code on https://github.com/shanet/WebRTC-Example/blob/master/client/webrtc.js but I realized it has a middle man "iceServers" located at.

```<code>var peerConnectionConfig = {
    'iceServers': [
        {'urls': 'stun:stun.services.mozilla.com'},
        {'urls': 'stun:stun.l.google.com:19302'},
    ]
};
</code>```

I need my software to work when two peers are connected on the same network without internet connection. Could someone help me locate some examples or ideas if webRTC is possible?

Thank you.

答:
Yes. It is possible. Just set the ice servers to an empty array (remove the stun and the turn servers) and all should be fine on a local network.

Take care about Chrome HTTPS/WSS requirements (Chrome will not allow the media permission if your website is not on HTTPS which is a bit difficult to setup on a local LAN without any internet connection). Firefox and Edge doesn't have such requirements.

Title: webRTC one to one audio call examples

Body:
I am trying to make a one to one audio call using webRTC.
I have been looking through some of the source code on https://github.com/shanet/WebRTC-Example/blob/master/client/webrtc.js but I realized it has a middle man "iceServers" located at.

var peerConnectionConfig = {
    'iceServers': [
        {'urls': 'stun:stun.services.mozilla.com'},
        {'urls': 'stun:stun.l.google.com:19302'},
    ]
};

I need my software to work when two peers are connected on the same network without internet connection. Could someone help me locate some examples or ideas if webRTC is possible?

Thank you.


问:
Python installation issue
When I type the command  which -a python to locate what versions of Python that it is. I get the following message:

```<code>$ which -a python
/Applications/MAMP/Library/bin//python
/usr/bin/python
</code>```

Now I am not sure where the "/Applications/MAMP/Library/bin//python" is being read from.

I really like to remove this reference but I can't find out where to change this.

I have tried checking the bash_profile but don't see any reference to the /Applications/MAMP/Library/bin//python

I am using mac OS 10.9.5

答:
I ran into the same problem, and finally fixed it.

In my .zshrc, I have this:

```<code>export PATH=/Applications/MAMP/Library/bin:$PATH
</code>```

change it to:

```<code>export PATH=$PATH:/Applications/MAMP/Library/bin
</code>```

fixed!

Title: Python installation issue

Body:
When I type the command  which -a python to locate what versions of Python that it is. I get the following message:

$ which -a python
/Applications/MAMP/Library/bin//python
/usr/bin/python

Now I am not sure where the "/Applications/MAMP/Library/bin//python" is being read from.

I really like to remove this reference but I can't find out where to change this.

I have tried checking the bash_profile but don't see any reference to the /Applications/MAMP/Library/bin//python

I am using mac OS 10.9.5

Body:
I ran into the same problem, and finally fixed it.

In my .zshrc, I have this:

export PATH=/Applications/MAMP/Library/bin:$PATH

change it to:

export PATH=$PATH:/Applications/MAMP/Library/bin

fixed!


问:
Is it possible to register dependencies by convention in .NET Core?
Some containers allow for registration by name. Ninject is one as an example.

Does the .NET Core DI container support this? And if not, are there plans or third party libraries to support this?

答:
And if not, are there plans or third party libraries to support this?

Try this https://github.com/khellang/Scrutor


答:
This worked when I just tried it:</p>

```<code>public partial class Life : Form
{
    private int _money;

    public void AddMoney(int amount)
    {
        _money += amount;
        label1.Text = _money.ToString();
    }

    public Life()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        var startGame = new StartGame(this);
        startGame.Show();
    }
}

public partial class StartGame : Form
{
    private readonly Life _life;

    public StartGame(Life life)
    {
        InitializeComponent();

        _life = life;
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        _life.AddMoney(5);
    }
}
</code>```

Title: C# modifying instance variables of a class in another form

Body:
This worked when I just tried it:

public partial class Life : Form
{
    private int _money;

    public void AddMoney(int amount)
    {
        _money += amount;
        label1.Text = _money.ToString();
    }

    public Life()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        var startGame = new StartGame(this);
        startGame.Show();
    }
}

public partial class StartGame : Form
{
    private readonly Life _life;

    public StartGame(Life life)
    {
        InitializeComponent();

        _life = life;
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        _life.AddMoney(5);
    }
}


问:
How to run visual studio 2017 API Project via IP address with windows 10 operating system, I am facing lot of problems
I have to try so many solutions but no one solves my problem, I need to run my visual studio API project in IP address( like 192.168.1.8:7832/), but at the same time this same project working as well in localhost:7832

I have to follow this following steps...

Change my applicationhost.config file like this

```<code><bindings>
  <binding protocol="http" bindingInformation="*:1407:192.168.1.8" />
</bindings>
</code>```

Then run the following comments cmd promt

netsh http add urlacl url=http://192.168.1.8:1407/ user=everyone

This just tells OK

Finally, run the following comment

```<code>netsh advfirewall firewall add rule name="IISExpressWeb" dir=in protocol=tcp localport=1234 profile=private remoteip=localsubnet action=allow
</code>```

but response is Service UnAvailable

Please help me someone, Thanks in Advance...

答:
I have found one solution,
If you want to run the project from both localhost and Ip-address,

Follow these steps:

1) Click on IIS site for that project and click on Bindings in the rightmost-pane, and click on Add....

2) Type the IP address you wish to bind it to, and then add a port you wish to use to access it on local network, Leave the Host Name blank.

3) Click ok and try to run that project through that IP-address and the port in the browser. The project should load as expected.

4) If you want to allow that port through firewall for local network, add it as a Inbound-Rule in Firewall.

NOTE: No changes required in application.config.

Hope this helps !

Body:
I have to try so many solutions but no one solves my problem, I need to run my visual studio API project in IP address( like 192.168.1.8:7832/), but at the same time this same project working as well in localhost:7832

I have to follow this following steps...

Change my applicationhost.config file like this

<bindings>
  <binding protocol="http" bindingInformation="*:1407:192.168.1.8" />
</bindings>

Then run the following comments cmd promt

netsh http add urlacl url=http://192.168.1.8:1407/ user=everyone

This just tells OK

Finally, run the following comment

netsh advfirewall firewall add rule name="IISExpressWeb" dir=in protocol=tcp localport=1234 profile=private remoteip=localsubnet action=allow

but response is Service UnAvailable

Please help me someone, Thanks in Advance...


问:
How to add the Cover image of your iOS App in the App store

As, shown in the picture the picture a cover image of instagram app has displayed but on most of the app we have not seen this. So how can i add this kind of cover image in my app for app store

答:
Only featured apps can have customized cover image or header. These applications are selected by Apple. This isn't a setting that we can control.

Here is an article on how to get featured in the App Store:
https://thenextweb.com/dd/2013/10/29/get-featured-app-store/


问:
Woocommerce, get products by category with wp query
I tried many methods, but I can't show products with category name or id</p>

```<code>                  $args = array(
                       'post_type'             => 'product',
                       'post_status'           => 'publish',
                       'ignore_sticky_posts'   => 1,
                       'cat'                   => 40,
                       'posts_per_page'        => '12',
                   );

                  $loop = new WP_Query( $args );
</code>```

答:
Try this,

```<code><?php
  $args     = array( 'post_type' => 'product', 'post_status' => 'publish','category' => 34, 'ignore_sticky_posts' => 1, 'posts_per_page' => '12',);
  $products = get_posts( $args );
?>
</code>```

Hope this will helps you. for more info.

Body:
I tried many methods, but I can't show products with category name or id

                  $args = array(
                       'post_type'             => 'product',
                       'post_status'           => 'publish',
                       'ignore_sticky_posts'   => 1,
                       'cat'                   => 40,
                       'posts_per_page'        => '12',
                   );

                  $loop = new WP_Query( $args );

Body:
Try this,

<?php
  $args     = array( 'post_type' => 'product', 'post_status' => 'publish','category' => 34, 'ignore_sticky_posts' => 1, 'posts_per_page' => '12',);
  $products = get_posts( $args );
?>

Hope this will helps you. for more info.


问:
Change Visibility of Grid on Button Click in Xaml
I am trying to find some way to when a button (Menu) is clicked, it changes the visibility of a Grid (Submenu) with a Trigger in XAML. I made it in vb.net but I wonder if it's easier to do in XAML?

Private Sub ShowSubmenu(SubmenuSettings e As Grid)
        Dim bk As Integer = VisualTreeHelper.GetChildrenCount(MainGrid)
        For i = 0 To bk - 1
            Dim g As Object = VisualTreeHelper.GetChild(MainGrid, i)
            If TypeOf g Is Grid Then g.Visibility = Visibility.Hidden
        Next
        SubmenuSettings.Visibility = Visibility.Visible
    End Sub

Private Sub Visibility(sender As Object)
        If sender Is btn1 Then
            ShowSubmenu(pdm1)
        End If
End Sub
```

答: You can give your Grid a " x:Name="gridName" ", then from code when clicking on button, do "gridName.Visibility = Visibility.Collapsed" (Collapsed or Hidden, as you wish). "</p>


答:
this.state.project.fieldName will say undefined each time because there is no project/project is not an object (you made it an array in constructor). It will be available after the data is fetched but component mounts before that.

try checking the result after fetching and only use the project data if !loading

Title: Wordpress API, React : this.state.project.title is undefined


问:
Google Maps API Search Using Geolocator AND local search
I'm using this resource guide to establish a dynamic map location default based on the user's IP address: https://developers.google.com/maps/documentation/javascript/geolocation

What I'd also like to do is pass search terms into this API query so that it produces results for "nail salon".

I'm not sure how to do this. Does anyone have any suggestions?

答:
In your case, I would suggest using Google Places API. It can be easily implemented with different kinds of applications. But right now, we'll use it for a web application and we are going to use Places JavaScript Library.

First, create a simple map. You can just copy the code here. Just make sure to use your own API key. To learn more on how to create a simple map, you can check Getting Started.

On the script that loads the Maps Javascript API, add "libraries=places".

Libraries are modules of code that provide additional functionality to
  the main Maps JavaScript API but are not loaded unless you
  specifically request them.

To learn more about Places Library, you can check this link. Your script now looks something like this:

```<code><script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
</code>```

We need to get your current location, so we'll be using Geolcation.

Geolocation is an HTML5 feature, that displays the geographic location
  of a user or device on a Google map.

Below is the code for geolocation. What it does is to check if HTML5 Geolocation is true. If so, we'll use getCurrentPosition to acquire the user's current coordinates for later use.

```<code>   if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          // add your map and Places API here.
        });
    } else {
      // Browser doesn't support Geolocation
    }
  }
</code>```

getCurrentPosition is a method that accepts an argument(s). The argument returns an object that has cool properties like: latitude, longitude. These properties will play an important role for creating our map and for our Places API. The ideal thing to do is to create a variable object and then use it for the acquired coordinates. Something like this:

```<code>var coordinatesObj = {
   lat: position.coords.latitude,
   lng: position.coords.longitude
};
</code>```

And then use it to 'center' property for our map.

```<code> map = new google.maps.Map(document.getElementById('map'), {
       center: coordinatesObj,
       zoom: 14
 });
</code>```

Create a variable 'service'. In this variable, we'll create a new instance of PlacesService. This object accepts an argument, which is the map ID.

```<code>var service = new google.maps.places.PlacesService(map);
</code>```

With Place service, you can perform four kinds of searches:

Nearby Search returns a list of nearby places based on a user's location

Text Search returns a list of nearby places based on a search string, eg. "Pizza".

Radar Search (deprecated) returns a large list of places within a specified search radius, but with less detail than either Nearby Search or Text Search.

Place Details requests return more detailed information about a specific place, including user reviews.

In your case, Nearby Search seems to be the best choice.

A Nearby Search lets you search for places within a specified area by
  keyword or type.

A Places Nearby search is initiated with a call to the PlacesService's nearbySearch() method, which will return an array of PlaceResult objects.

```<code>service.nearbySearch({
  location: , // place the coordinates here
  radius: 500,
  type: ['beauty_salon']
}, callback);
</code>```

On the 'location' property, use the coordinates that we acquired from the Geolocations's getCurrentPosition method.

```<code>service.nearbySearch({
 location: coordinatesObj,
 radius: 500,
 type: ['beauty_salon']
}, callback);
</code>```

Just be aware that when using 'location', you need to add a 'radius' property and supply a number from 500 to 50000 meters. To learn more, checking this documentation would be very helpful.

You must also pass a callback method to nearbySearch(), to handle the results object and google.maps.places.PlacesServiceStatus response.

```<code>function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}
</code>```

This callback function adds a marker when the 'status' is google.maps.places.PlacesServiceStatus.OK. In other words, if the status is successful.

You will also notice createMarker() function. This function accepts an argument and creates a marker on every location returned.

```<code>function createMarker(place) {
 var placeLoc = place.geometry.location;
 var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
 });
 google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
 });
}
</code>```

You will also notice this google.maps.event.addListener. It responds to user events such as mouse or keyboard events with the map.

These events may look like standard DOM events, but they are actually part of the Maps JavaScript API. Because different browsers implement different DOM event models, the Maps JavaScript API provides these mechanisms to listen for and respond to DOM events without needing to handle the various cross-browser peculiarities. These events also typically pass arguments within the event noting some UI state (such as the mouse position). To learn more, you can check Events.

One more thing, currently, we don't have type 'nail_salon'. So that's why we used 'beauty_salon' in the type property. For the list of supported types, you can check Place Types to learn more.

Bonus stuff:

An InfoWindow displays content (usually text or images) in a popup window above the map, at a given location. The info window has a content area and a tapered stem. The tip of the stem is attached to a specified location on the map.

```<code>var infowindow = new google.maps.InfoWindow();
</code>```

Whole code below:

      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infowindow;
      function initMap() {
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var coordinatesObj = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                map = new google.maps.Map(document.getElementById('map'), {
                  center: coordinatesObj,
                  zoom: 14
                });
                infowindow = new google.maps.InfoWindow();
                var service = new google.maps.places.PlacesService(map);
                service.nearbySearch({
                    location: coordinatesObj,
                    radius: 500,
                    type: ['beauty_salon']
                }, callback);
            });
        } else {
          // Browser doesn't support Geolocation
        }
      }
      function callback(results, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          for (var i = 0; i < results.length; i++) {
            createMarker(results[i]);
          }
        }
      }

      function createMarker(place) {
        var placeLoc = place.geometry.location;
        var marker = new google.maps.Marker({
          map: map,
          position: place.geometry.location
        });

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
        });
      }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
        height: 100%;
}
      /* Optional: Makes the sample page fill the window. */
html, body {
        height: 100%;
        margin: 0;
        padding: 0;
}</code>```

```

And that's it!

Hope this helps and happy coding!

Body:
In your case, I would suggest using Google Places API. It can be easily implemented with different kinds of applications. But right now, we'll use it for a web application and we are going to use Places JavaScript Library.

First, create a simple map. You can just copy the code here. Just make sure to use your own API key. To learn more on how to create a simple map, you can check Getting Started.

On the script that loads the Maps Javascript API, add "libraries=places".

Libraries are modules of code that provide additional functionality to
  the main Maps JavaScript API but are not loaded unless you
  specifically request them.

To learn more about Places Library, you can check this link. Your script now looks something like this:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>

We need to get your current location, so we'll be using Geolcation.

Geolocation is an HTML5 feature, that displays the geographic location
  of a user or device on a Google map.

Below is the code for geolocation. What it does is to check if HTML5 Geolocation is true. If so, we'll use getCurrentPosition to acquire the user's current coordinates for later use.

   if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          // add your map and Places API here.
        });
    } else {
      // Browser doesn't support Geolocation
    }
  }

getCurrentPosition is a method that accepts an argument(s). The argument returns an object that has cool properties like: latitude, longitude. These properties will play an important role for creating our map and for our Places API. The ideal thing to do is to create a variable object and then use it for the acquired coordinates. Something like this:

var coordinatesObj = {
   lat: position.coords.latitude,
   lng: position.coords.longitude
};

And then use it to 'center' property for our map.

 map = new google.maps.Map(document.getElementById('map'), {
       center: coordinatesObj,
       zoom: 14
 });

Create a variable 'service'. In this variable, we'll create a new instance of PlacesService. This object accepts an argument, which is the map ID.

var service = new google.maps.places.PlacesService(map);

With Place service, you can perform four kinds of searches:

Nearby Search returns a list of nearby places based on a user's location

Text Search returns a list of nearby places based on a search string, eg. "Pizza".

Radar Search (deprecated) returns a large list of places within a specified search radius, but with less detail than either Nearby Search or Text Search.

Place Details requests return more detailed information about a specific place, including user reviews.

In your case, Nearby Search seems to be the best choice.

A Nearby Search lets you search for places within a specified area by
  keyword or type.

A Places Nearby search is initiated with a call to the PlacesService's nearbySearch() method, which will return an array of PlaceResult objects.

service.nearbySearch({
  location: , // place the coordinates here
  radius: 500,
  type: ['beauty_salon']
}, callback);

On the 'location' property, use the coordinates that we acquired from the Geolocations's getCurrentPosition method.

service.nearbySearch({
 location: coordinatesObj,
 radius: 500,
 type: ['beauty_salon']
}, callback);

Just be aware that when using 'location', you need to add a 'radius' property and supply a number from 500 to 50000 meters. To learn more, checking this documentation would be very helpful.

You must also pass a callback method to nearbySearch(), to handle the results object and google.maps.places.PlacesServiceStatus response.

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

This callback function adds a marker when the 'status' is google.maps.places.PlacesServiceStatus.OK. In other words, if the status is successful.

You will also notice createMarker() function. This function accepts an argument and creates a marker on every location returned.

function createMarker(place) {
 var placeLoc = place.geometry.location;
 var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
 });
 google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
 });
}

You will also notice this google.maps.event.addListener. It responds to user events such as mouse or keyboard events with the map.

These events may look like standard DOM events, but they are actually part of the Maps JavaScript API. Because different browsers implement different DOM event models, the Maps JavaScript API provides these mechanisms to listen for and respond to DOM events without needing to handle the various cross-browser peculiarities. These events also typically pass arguments within the event noting some UI state (such as the mouse position). To learn more, you can check Events.

One more thing, currently, we don't have type 'nail_salon'. So that's why we used 'beauty_salon' in the type property. For the list of supported types, you can check Place Types to learn more.

Bonus stuff:

An InfoWindow displays content (usually text or images) in a popup window above the map, at a given location. The info window has a content area and a tapered stem. The tip of the stem is attached to a specified location on the map.

var infowindow = new google.maps.InfoWindow();

Whole code below:

      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infowindow;
      function initMap() {
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var coordinatesObj = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                map = new google.maps.Map(document.getElementById('map'), {
                  center: coordinatesObj,
                  zoom: 14
                });
                infowindow = new google.maps.InfoWindow();
                var service = new google.maps.places.PlacesService(map);
                service.nearbySearch({
                    location: coordinatesObj,
                    radius: 500,
                    type: ['beauty_salon']
                }, callback);
            });
        } else {
          // Browser doesn't support Geolocation
        }
      }
      function callback(results, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          for (var i = 0; i < results.length; i++) {
            createMarker(results[i]);
          }
        }
      }

      function createMarker(place) {
        var placeLoc = place.geometry.location;
        var marker = new google.maps.Marker({
          map: map,
          position: place.geometry.location
        });

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
        });
      }

#map {
        height: 100%;
}
      /* Optional: Makes the sample page fill the window. */
html, body {
        height: 100%;
        margin: 0;
        padding: 0;
}

<div id="map"></div>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&libraries=places&callback=initMap">
    </script>

And that's it!

Hope this helps and happy coding!


问:
Switching classes onClick toggle
I am learning by doing and have hit a road block while developing a website. I have a menu with 4 options, there is an active state and off state in css as well as the first option is active by default. When clicking any option it toggles it to the active state but does not change the previous one to the off state.

Code:

function myFunc(e) {
  if (e.className == 'channel') {
    e.className = 'channel active';
  } else {
    e.className = 'channel';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li id="test" class="channel active" data-v-a3c933a2="" onclick="openPlayer('option1'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option1
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option2'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option2
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option3'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option3
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option4'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option4
</li></code>```

How do I go about having all nonactive options actually display in the off state instead of just toggling per-click?

Thank you for your time!

答:
You can easily do it using jquery like this</p>

```<code>$(document).ready(function(){
  var items = $(".item");
  items.on("click",function(){
    $(".item").removeClass("selected");
    $(this).addClass("selected");
  });
});
</code>```

Title: Switching classes onClick toggle

Body:
I am learning by doing and have hit a road block while developing a website. I have a menu with 4 options, there is an active state and off state in css as well as the first option is active by default. When clicking any option it toggles it to the active state but does not change the previous one to the off state.

Code:

function myFunc(e) {
  if (e.className == 'channel') {
    e.className = 'channel active';
  } else {
    e.className = 'channel';
  }
}

Offline 0

Option1

Offline 0

Option2

Offline 0

Option3

Offline 0

Option4

How do I go about having all nonactive options actually display in the off state instead of just toggling per-click?

Thank you for your time!

Body:
You can easily do it using jquery like this

$(document).ready(function(){
  var items = $(".item");
  items.on("click",function(){
    $(".item").removeClass("selected");
    $(this).addClass("selected");
  });
});


问:
Pandas reshape columns to time-series rows
I have a pandas dataframe (unhappily with duplicates...)

```<code>Date        Partner   Value
2017-02-01  Partner1  150
2017-03-01  Partner1  170
2017-02-01  Partner2  160
2017-03-01  Partner2  185
2017-02-01  Partner1  40
2017-03-01  Partner1  90
</code>```

Which I want to reshape by partners, looking like this:

```<code>Partner    2017-02-01   2017-03-01
Partner1   150          170
Partner2   160          185
Partner1   40           90
</code>```

How would I go about this?

答:
Here is an alternative solution:

Source DF:

```<code>In [143]: df
Out[143]:
         Date   Partner  Value
0  2017-02-01  Partner1    150
1  2017-02-01  Partner1    199   # NOTE: duplicated `Date` & `Partner`
2  2017-03-01  Partner1    170
3  2017-02-01  Partner2    160
4  2017-03-01  Partner2    185
</code>```

Solution:

```<code>In [144]: df.groupby(['Partner','Date'])['Value'].mean().unstack().rename_axis(None).rename_axis(None, 1)
Out[144]:
          2017-02-01  2017-03-01
Partner1       174.5       170.0
Partner2       160.0       185.0
</code>```

Body:
I have a pandas dataframe (unhappily with duplicates...)

Date        Partner   Value
2017-02-01  Partner1  150
2017-03-01  Partner1  170
2017-02-01  Partner2  160
2017-03-01  Partner2  185
2017-02-01  Partner1  40
2017-03-01  Partner1  90

Which I want to reshape by partners, looking like this:

Partner    2017-02-01   2017-03-01
Partner1   150          170
Partner2   160          185
Partner1   40           90

How would I go about this?

Body:
Here is an alternative solution:

Source DF:

In [143]: df
Out[143]:
         Date   Partner  Value
0  2017-02-01  Partner1    150
1  2017-02-01  Partner1    199   # NOTE: duplicated `Date` & `Partner`
2  2017-03-01  Partner1    170
3  2017-02-01  Partner2    160
4  2017-03-01  Partner2    185

Solution:

In [144]: df.groupby(['Partner','Date'])['Value'].mean().unstack().rename_axis(None).rename_axis(None, 1)
Out[144]:
          2017-02-01  2017-03-01
Partner1       174.5       170.0
Partner2       160.0       185.0