问:
Databinding a ObservableCollection<T> in MVVM
I have a ListView with a Datatemplate that holds a list of Movies. It is databinded to a ObservableColection but whenever I edit the Movie.Name it does not update the ListView even though "Name" is called in my PropertyChangedEventHandler is called with "Name".

I add 2 "Movie"s to my collection in my initializer and these are shown correct (Klovn the Movie, Taken)

So when I click Edit it should change the text of the selected movie and change the Name of it to "Test" and is is changed but the change is not shown in the ListView but if I output Collection with a foreach then Name is Test.

View.xaml

<Window x:Class="MovieDB3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Edit" Click="MenuEditClick"/>
            </MenuItem>
        </Menu>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <ListView VerticalAlignment="Stretch" Name="ListViewMovies" ItemsSource="{Binding Path=Collection}" IsSynchronizedWithCurrentItem="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </DockPanel>
</Window>
```

<p>View.cs</p>

```using System;
using System.Windows;
using MovieDB3.Models;
using MovieDB3.ViewModels;

namespace MovieDB3
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private MainViewModel MVM;
        public MainWindow()
        {
            InitializeComponent();
            MVM = new MainViewModel();
            DataContext = MVM;
        }

        private void MenuEditClick(object sender, RoutedEventArgs e)
        {
            MVM.setMovieName((Movie)ListViewMovies.SelectedItem, "test");
        }
    }
}
```

<p>The ViewModel</p>

```using System;
using System.ComponentModel;
using MovieDB3.Models;
using System.Collections.ObjectModel;

namespace MovieDB3.ViewModels
{
    class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Movie> Collection {get; set;}

        public MainViewModel()
        {
            Collection = new ObservableCollection<Movie>();

            //Test kode
            Movie movie = new Movie();
            movie.Name = "Klovn The Movie";
            Collection.Add(movie);
            movie = new Movie();
            movie.Name = "Taken";
            Collection.Add(movie);
        }

        public void setMovieName(Movie movie, string newName)
        {
            //movie.Name = newName;
            Console.WriteLine("CurrentName: " + movie.Name);
            int i = Collection.IndexOf(movie);
            Collection[i].Name = newName;
            Console.WriteLine("NewName: " + movie.Name);
            NotifyPropertyChanged("Name");
        }

        public void setMovieName(string currentName, string newName)
        {
            foreach (Movie movie in Collection)
            {
                if (movie.Name.Equals(currentName))
                {
                    movie.Name = newName;
                    NotifyPropertyChanged("Name");
                    return;
                }
            }
        }

        //public string MovieName
        //{
        //    set
        //    {

        //        NotifyPropertyChanged("MovieName");
        //    }
        //}

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}
```

<p>Movie.cs</p>

```using System;

namespace MovieDB3.Models
{
    class Movie
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public double Rating { get; set; }
        public DateTime Release { get; set; }
        public TimeSpan Runtime { get; set; }
        public String Trailer { get; set; }
    }
}
```

答:
You need to implement INotifyPropertyChanged on your Movie class as well.

The notification that you are sending in the setMovieName method does not really mean anything - it's just a "property" name.  It could just as well be "Foo," and your event handler will say "Foo".

What you need, instead, is for the Movie object itself to be updated.

Probably the best implementation will be for you to create an abstract class that notifies INotifyPropertyChanged, and then derive your ViewModel and your Movie classes from it, because both should implement it.

You will be binding properties from the ViewModel, and you will also be binding observable objects (i.e. Movie) inside that ViewModel.

Body:
I have a ListView with a Datatemplate that holds a list of Movies. It is databinded to a ObservableColection but whenever I edit the Movie.Name it does not update the ListView even though "Name" is called in my PropertyChangedEventHandler is called with "Name".

I add 2 "Movie"s to my collection in my initializer and these are shown correct (Klovn the Movie, Taken)

So when I click Edit it should change the text of the selected movie and change the Name of it to "Test" and is is changed but the change is not shown in the ListView but if I output Collection with a foreach then Name is Test.

View.xaml

<Window x:Class="MovieDB3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Edit" Click="MenuEditClick"/>
            </MenuItem>
        </Menu>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <ListView VerticalAlignment="Stretch" Name="ListViewMovies" ItemsSource="{Binding Path=Collection}" IsSynchronizedWithCurrentItem="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </DockPanel>
</Window>

View.cs

using System;
using System.Windows;
using MovieDB3.Models;
using MovieDB3.ViewModels;

namespace MovieDB3
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private MainViewModel MVM;
        public MainWindow()
        {
            InitializeComponent();
            MVM = new MainViewModel();
            DataContext = MVM;
        }

        private void MenuEditClick(object sender, RoutedEventArgs e)
        {
            MVM.setMovieName((Movie)ListViewMovies.SelectedItem, "test");
        }
    }
}

The ViewModel

using System;
using System.ComponentModel;
using MovieDB3.Models;
using System.Collections.ObjectModel;

namespace MovieDB3.ViewModels
{
    class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Movie> Collection {get; set;}

        public MainViewModel()
        {
            Collection = new ObservableCollection<Movie>();

            //Test kode
            Movie movie = new Movie();
            movie.Name = "Klovn The Movie";
            Collection.Add(movie);
            movie = new Movie();
            movie.Name = "Taken";
            Collection.Add(movie);
        }

        public void setMovieName(Movie movie, string newName)
        {
            //movie.Name = newName;
            Console.WriteLine("CurrentName: " + movie.Name);
            int i = Collection.IndexOf(movie);
            Collection[i].Name = newName;
            Console.WriteLine("NewName: " + movie.Name);
            NotifyPropertyChanged("Name");
        }

        public void setMovieName(string currentName, string newName)
        {
            foreach (Movie movie in Collection)
            {
                if (movie.Name.Equals(currentName))
                {
                    movie.Name = newName;
                    NotifyPropertyChanged("Name");
                    return;
                }
            }
        }

        //public string MovieName
        //{
        //    set
        //    {

        //        NotifyPropertyChanged("MovieName");
        //    }
        //}

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}

Movie.cs

using System;

namespace MovieDB3.Models
{
    class Movie
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public double Rating { get; set; }
        public DateTime Release { get; set; }
        public TimeSpan Runtime { get; set; }
        public String Trailer { get; set; }
    }
}

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
JMeter extract link using regular expression pass into next request with blank values
This is how I have Test Plan set up:

HTTP Request -> Regular Expression Extractor to extract multiple links  - This is extracting correctly -- But some of the links are Blank
RegularExpressionExtractor ---

BeanShell Sampler - to filter blank or null values -- This works fine

BeanShell Sampler

```<code>log.info("Enter Beanshell Sampler");
matches = vars.get("url_matchNr");
log.info(matches);

for (Integer i=1; i < Integer.parseInt(matches); i++)
{
    String url = vars.get("url_"+i);
    //log.info(url1);
    if(url != null @and url.length() > 0)
    {
        log.info(i+"->" + url);
        //return url;
        //vars.put("url2", url);
        vars.put("url2", url);
        //props.put("url2", url);
        log.info("URL2:" + vars.get("url2"));
    }
}
</code>```

ForEach Controller
ForEach Controller

href="https://i.stack.imgur.com/Knomw.png" rel="nofollow noreferrer">Test Plan

The problem I am facing is ForEach Controller runs through all the values including Blank or NULL -- How can I run the loop only for the non null blank values

答:
You should change your regular expression to exclude empty value

Instead of using any value including empty using * sign

```<code> <a href="(.*)" class="product-link">
</code>```

Find only not empty strings using + sign:

```<code> <a href="(.+)" class="product-link">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is how I have Test Plan set up:

HTTP Request -> Regular Expression Extractor to extract multiple links  - This is extracting correctly -- But some of the links are Blank
RegularExpressionExtractor ---

BeanShell Sampler - to filter blank or null values -- This works fine

BeanShell Sampler

log.info("Enter Beanshell Sampler");
matches = vars.get("url_matchNr");
log.info(matches);

for (Integer i=1; i < Integer.parseInt(matches); i++)
{
    String url = vars.get("url_"+i);
    //log.info(url1);
    if(url != null @and url.length() > 0)
    {
        log.info(i+"->" + url);
        //return url;
        //vars.put("url2", url);
        vars.put("url2", url);
        //props.put("url2", url);
        log.info("URL2:" + vars.get("url2"));
    }
}

ForEach Controller
ForEach Controller

Test Plan

The problem I am facing is ForEach Controller runs through all the values including Blank or NULL -- How can I run the loop only for the non null blank values

Body:
You should change your regular expression to exclude empty value

Instead of using any value including empty using * sign

 <a href="(.*)" class="product-link">

Find only not empty strings using + sign:

 <a href="(.+)" class="product-link">


问:
Does Android Studio 3 support Java 9 for Android development? If so, what features of Java 9 are supported?
I'm going to install Android Studio 3 in order to develop an Android application.

I'd like to know if it is possible to use Java 9 for Android development? If so, does it support all of the Java 9 features?

答:
As far as I know, the IDE itself supports Java 9. This means you can write a Java 9 desktop program, or run the IDE with JDK 9.

However, Android itself does not support Java 9 (yet). You can still download JDK 9, although I have seen some questions on problems related to Android Studio and Java 9. Personally, I have Java 9 and Android Studio runs without problems.

The Android SDK is the development kit you'll be dealing with, and with source compatibility you'll get language features similar to Java 6, 7, or 8, depending on your settings. So you can download JDK 9 and use that most likely without issues, but you can't use any of the language features in any Android apps.

As for differences between the JDK and the Android SDK, you should read this. Android currently supports a subset of Java 8 features, but not everything. It might never support everything, or leave out some parts of Java 8, even if it later supports some parts on Java 9 or higher.

ContentLicense: CC BY-SA 4.0


问:
How to create a dictionary from a text file in python?
I want to create a dictionary from a text file in python. My text file is:

```<code>John Doe
Apples
Bananas
Oranges

Jane Dear
Apples
Bananas
Peaches
</code>```

The format of the text file is:

```<code>Name
Fruit
Fruit
.....
Fruit
empty line
Name
Fruit
.....
</code>```

I want to return a dictionary with the fruits as the key and the names as the values such as:

```<code>{"Apples":["John Doe", "Jane Dear"], "Bananas":["John Doe", "Jane Dear"], "Peaches":["Jane Dear"], "Oranges":["John Doe"]}
</code>```

I'm just not entirely sure on how to format the text file. Thanks in advance!

EDIT: What I have done so far

```<code>def common(text):
x = open(text, "r")
a = {}
b = []
line = x.readline()
while line != "":
    b.append(line)
    line = courses.readline()
return b

def create_dict(lst):
a = []
b = {}
names = []
fruits = []
while lst != []:
   if " " in lst[1]:
      names += lst[1]
   else:
      fruits += lst[1]
</code>```

This is where I'm sort of lost...

答:
A little more clarity is needed on the format of the text file. For the sake of this answer I am assuming the format of the text file is something like this.

```<code>NAME_1
FRUIT_1
FRUIT_2
FRUIT_3

NAME_2
FRUIT_1
FRUIT_2
FRUIT_3
.
.

NAME_3
.
.
.
</code>```

Now if this is the case, i.e there's always a double line break('\n\n') after name of fruits and the sequence always starts with the name of person, then here is a way of getting this dictionary populated.

```<code>with open('/path/to/file', 'r') as handle:
    text = handle.read()
text = text.split('\n\n')
result = dict()
for item in text:
    item = item.split('\n')
    for fruit in item[1:]:
        if fruit in result.keys():
            result[fruit].append(item[0])
        else:
            result[fruit] = [item[0]]
</code>```

Hope this helps

Body:
I want to create a dictionary from a text file in python. My text file is:

John Doe
Apples
Bananas
Oranges

Jane Dear
Apples
Bananas
Peaches

The format of the text file is:

Name
Fruit
Fruit
.....
Fruit
empty line
Name
Fruit
.....

I want to return a dictionary with the fruits as the key and the names as the values such as:

{"Apples":["John Doe", "Jane Dear"], "Bananas":["John Doe", "Jane Dear"], "Peaches":["Jane Dear"], "Oranges":["John Doe"]}

I'm just not entirely sure on how to format the text file. Thanks in advance!

EDIT: What I have done so far

def common(text):
x = open(text, "r")
a = {}
b = []
line = x.readline()
while line != "":
    b.append(line)
    line = courses.readline()
return b

def create_dict(lst):
a = []
b = {}
names = []
fruits = []
while lst != []:
   if " " in lst[1]:
      names += lst[1]
   else:
      fruits += lst[1]

This is where I'm sort of lost...

Body:
A little more clarity is needed on the format of the text file. For the sake of this answer I am assuming the format of the text file is something like this.

NAME_1
FRUIT_1
FRUIT_2
FRUIT_3

NAME_2
FRUIT_1
FRUIT_2
FRUIT_3
.
.

NAME_3
.
.
.

Now if this is the case, i.e there's always a double line break('\n\n') after name of fruits and the sequence always starts with the name of person, then here is a way of getting this dictionary populated.

with open('/path/to/file', 'r') as handle:
    text = handle.read()
text = text.split('\n\n')
result = dict()
for item in text:
    item = item.split('\n')
    for fruit in item[1:]:
        if fruit in result.keys():
            result[fruit].append(item[0])
        else:
            result[fruit] = [item[0]]

Hope this helps


问:
Returning/using PreparedStatement from utility class
I have a piece of code which uses JDBC "Statement" to perform CRUD operations. Now, I need to replace all the Statement with "PreparedStatement" but I am confused about how to return/use it like below code. Please help.

MyDao.java

```<code>    public class MyDao extends BaseDao{

    public MyDao() {
        super();
    }

    public void search(){
        ResultSet rs = null;

        try {
            statement.executeQuery("SELECT * FROM testTable");
            rs = statement.getResultSet();
            reset();
        }
        catch (Exception e) {
         e.printStackTrace();
        }
    }

}
</code>```

BaseDao

```<code>  public class BaseDao {

Connection connection=null;
Statement statement = null;

public BaseDao() {
        try {
            Class.forName("org.postgresql.Driver");
            connection = (Connection) DriverManager.getConnection("url","user","password");
            statement = connection.createStatement();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void reset(){
        try{
            statement.close();
            connection.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

答: First check the connection parameters for the database, i assume that you are using a local database so test it with localhost, user, password. If the connection is ok print a console message and then do the CRUD. </p>

Body:
I have a piece of code which uses JDBC "Statement" to perform CRUD operations. Now, I need to replace all the Statement with "PreparedStatement" but I am confused about how to return/use it like below code. Please help.

MyDao.java

    public class MyDao extends BaseDao{

    public MyDao() {
        super();
    }

    public void search(){
        ResultSet rs = null;

        try {
            statement.executeQuery("SELECT * FROM testTable");
            rs = statement.getResultSet();
            reset();
        }
        catch (Exception e) {
         e.printStackTrace();
        }
    }

}

BaseDao

  public class BaseDao {

Connection connection=null;
Statement statement = null;

public BaseDao() {
        try {
            Class.forName("org.postgresql.Driver");
            connection = (Connection) DriverManager.getConnection("url","user","password");
            statement = connection.createStatement();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void reset(){
        try{
            statement.close();
            connection.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}


问:
Entity framework Modify multiple records with common data
I have an "Apps" Table which consists of multiple apps data
Now I wanted to delete (soft delete means making isDelete = true)

I'm deleting records by the following code.

```<code>var deletingISVCSPRecord = await db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId).ToListAsync();
foreach (var item in deletingISVCSPRecord)
{
    item.IsDeleted = true;
    await db.SaveChangesAsync();
}
</code>```

is there any good way to do this.

Appreciate your help.

答:
Better way means if you updating around 10k record this is the better way.. it will reduce each single file updating into one shot updating.</p>

```<code>foreach (var item in db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId))
{
    item.IsDeleted = true;
}
await db.SaveChangesAsync();
</code>```

Body:
I have an "Apps" Table which consists of multiple apps data
Now I wanted to delete (soft delete means making isDelete = true)

I'm deleting records by the following code.

var deletingISVCSPRecord = await db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId).ToListAsync();
foreach (var item in deletingISVCSPRecord)
{
    item.IsDeleted = true;
    await db.SaveChangesAsync();
}

is there any good way to do this.

Appreciate your help.

Body:
Better way means if you updating around 10k record this is the better way.. it will reduce each single file updating into one shot updating.

foreach (var item in db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId))
{
    item.IsDeleted = true;
}
await db.SaveChangesAsync();


问:
Ubuntu 14.04:Export mysql database failed with command line
I am using Ubuntu 14.04 and Vagrant, And I want to export the database with mysql command line,But always failed with this message:

you have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysqldump -u root -p hockey_development>/home/jason/Documents/Projects/hockey_development1.sql'

I think there is no problems in this command line and the database;

error message

答: mysqldump is a command meant to be run directly from the command line -- not while logged into mysql.


问:
WPF - How to duplicate Controls / a whole grid by pressing a button?
I am new to WPF and I am trying to make a control that will expand my form with a specific controls each time i hit it until it reaches maximum of 7 times.

this is the form:
https://i.imgur.com/50tzCSy.png

```<code><Border Padding="10">
    <StackPanel>
        <TextBlock Text="Insert a file or expand to insert more file at once." Margin="0 10"/>

        <!-- Add File -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="4*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Column="0" Text="File Name:" FontWeight="Bold"  Margin="0 10" />
            <TextBox Grid.Column="1" Height="20" Margin="10 0 0 0" />
            <Button Grid.Column="2" Content="Test" Height="20" Width="50" />
        </Grid>

        <ItemsControl ItemsSource="{Binding AllChildren}" ItemTemplate="{StaticResource ChildTemplate}" />

        <!-- Buttons -->
        <Grid Margin="0 10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Button Grid.Column="0" Margin="0 0 10 0" Content="Save"   />
            <Button Grid.Column="1" Content="Expand" Grid.ColumnSpan="2" Margin="0.2,0,123.6,0.2" Click="Button_Click"   />
            <Button Grid.Column="2" Margin="10 0 0 0" Content="Cancel"  />
        </Grid>

    </StackPanel>
</Border>
</code>```

I try to duplicate the  grid until it reaches maximum of 7 duplications.

how do I make this through the Button Event handler code ?

答:
Here is an illustration of my comment. I try to kept the ViewModel as simple and generic as possible, so it should look empty. It is up to you to modify it, and eventually put some DataBinding (I would recommend it).

Let us know if you need something more specific. The XAML:

```<code><Border Padding="10">
    <StackPanel>
        <TextBlock Text="Insert a file or expand to insert more file at once." Margin="0 10"/>

        <ListBox  Name="DynamicList" HorizontalContentAlignment="Stretch" >
            <ListBox.Resources>
                <DataTemplate DataType="{x:Type local:FileM}">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="4*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>

                        <TextBlock Grid.Column="0" Text="File Name:" FontWeight="Bold"  Margin="0 10" />
                        <TextBox Grid.Column="1" Height="20" Margin="10 0 0 0" />
                        <Button Grid.Column="2" Content="Test" Height="20" Width="50" />
                    </Grid>
                </DataTemplate>
            </ListBox.Resources>
        </ListBox>
        <!--Since I don'T have any information about it, I removed the ItemsControl part-->
        <Grid Margin="0 10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Button Grid.Column="0" Margin="0 0 10 0" Content="Save"   />
            <Button Grid.Column="1" Content="Expand" Click="Button_Click"   />
            <Button Grid.Column="2" Margin="10 0 0 0" Content="Cancel"  />
        </Grid>
    </StackPanel>
</Border>
</code>```

And the code behind:

```<code>public class FileM
{
}

public partial class MainWindow : Window
{
    public ObservableCollection<FileM> ListFiles = new ObservableCollection<FileM>();

    public MainWindow()
    {
        InitializeComponent();
        DynamicList.ItemsSource = ListFiles;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if(ListFiles.Count<7){ListFiles.Add(new FileM());}
    }

}
</code>```

Body:
I am new to WPF and I am trying to make a control that will expand my form with a specific controls each time i hit it until it reaches maximum of 7 times.

this is the form:
https://i.imgur.com/50tzCSy.png

<Border Padding="10">
    <StackPanel>
        <TextBlock Text="Insert a file or expand to insert more file at once." Margin="0 10"/>

        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="4*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Column="0" Text="File Name:" FontWeight="Bold"  Margin="0 10" />
            <TextBox Grid.Column="1" Height="20" Margin="10 0 0 0" />
            <Button Grid.Column="2" Content="Test" Height="20" Width="50" />
        </Grid>

        <ItemsControl ItemsSource="{Binding AllChildren}" ItemTemplate="{StaticResource ChildTemplate}" />

        <Grid Margin="0 10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Button Grid.Column="0" Margin="0 0 10 0" Content="Save"   />
            <Button Grid.Column="1" Content="Expand" Grid.ColumnSpan="2" Margin="0.2,0,123.6,0.2" Click="Button_Click"   />
            <Button Grid.Column="2" Margin="10 0 0 0" Content="Cancel"  />
        </Grid>

    </StackPanel>
</Border>

I try to duplicate the  grid until it reaches maximum of 7 duplications.

how do I make this through the Button Event handler code ?

Body:
Here is an illustration of my comment. I try to kept the ViewModel as simple and generic as possible, so it should look empty. It is up to you to modify it, and eventually put some DataBinding (I would recommend it).

Let us know if you need something more specific. The XAML:

<Border Padding="10">
    <StackPanel>
        <TextBlock Text="Insert a file or expand to insert more file at once." Margin="0 10"/>

        <ListBox  Name="DynamicList" HorizontalContentAlignment="Stretch" >
            <ListBox.Resources>
                <DataTemplate DataType="{x:Type local:FileM}">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="4*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>

                        <TextBlock Grid.Column="0" Text="File Name:" FontWeight="Bold"  Margin="0 10" />
                        <TextBox Grid.Column="1" Height="20" Margin="10 0 0 0" />
                        <Button Grid.Column="2" Content="Test" Height="20" Width="50" />
                    </Grid>
                </DataTemplate>
            </ListBox.Resources>
        </ListBox>
        <!--Since I don'T have any information about it, I removed the ItemsControl part-->
        <Grid Margin="0 10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Button Grid.Column="0" Margin="0 0 10 0" Content="Save"   />
            <Button Grid.Column="1" Content="Expand" Click="Button_Click"   />
            <Button Grid.Column="2" Margin="10 0 0 0" Content="Cancel"  />
        </Grid>
    </StackPanel>
</Border>

And the code behind:

public class FileM
{
}

public partial class MainWindow : Window
{
    public ObservableCollection<FileM> ListFiles = new ObservableCollection<FileM>();

    public MainWindow()
    {
        InitializeComponent();
        DynamicList.ItemsSource = ListFiles;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if(ListFiles.Count<7){ListFiles.Add(new FileM());}
    }

}


答: As stated, you can't. You would have to supply the SQL to be prepared. But the whole design is incorrect. You should not carry around Connections and Statements as instance members of a class. Connections can be closed by the database server any time, especially long-lived ones, at which point you need a new one anyway. Don't give it the chance. You should obtain both as required, and use a connection pool to amortise the costs. </p>

Title: Returning/using PreparedStatement from utility class


问:
How to display error display message for few seconds - Laravel
This might be a very simple question but i can't seem to find this. How can
make my redirect flash an error and it should also disappear after few seconds

```<code> return redirect('admin/all')->with('error','Failed.');
</code>```

I changed the status to error but i didnt do the trick.

答:
You can add a id where you showing your displaying your error and write a jquery like this:

```<code>setTimeout(function() {
    $('#successMessage').fadeOut('fast');
}, 30000);
</code>```

Body:
This might be a very simple question but i can't seem to find this. How can
make my redirect flash an error and it should also disappear after few seconds

 return redirect('admin/all')->with('error','Failed.');

I changed the status to error but i didnt do the trick.

Body:
You can add a id where you showing your displaying your error and write a jquery like this:

setTimeout(function() {
    $('#successMessage').fadeOut('fast');
}, 30000);


问:
How to Store Log Data in Json format in android?
I am logging events in the android application.

Now I need to store the Log data that is generated by the application in JSON format.How can I do this... any suggestion for this?

this is the code for logging various events of the Android application using AppEventLogger class

```<code>public  class AppEventLogger {

private static final String TAG = AppEventsLogger.class.getCanonicalName();

public void Loginlog(Long id,  boolean result, int failedattempts, int attempts,long eventTime, long mLastInteractionTime) {
    final long eventTime = System.currentTimeMillis();

    logLogin(
        id,
        result,
        failedattempts,
        attempts,
        eventTime,
        mLastInteractionTime);

}

public void Logoutlog(long eventTime ,boolean isLoggedOut,){
    final long eventTime = System.currentTimeMillis();

    logLogout(
        eventTime,
        isLoggedOut);
}
</code>```

答:
Try this

Changes in your class:

```<code>package com.nct.dhruv.demotest;

import android.content.Context;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by user31 on 4/12/17.
 */

public class AppEventLogger {

    private Context mContext;
    private String appContextName = "AppEventLogger";

    public AppEventLogger(Context context) {
        mContext = context;
        Loginlog(1, true, 11, 112, 121, 12);
        Logoutlog(2, false);

    }

    //private static final String TAG = AppEventsLogger.class.getCanonicalName();
    JSONArray jsonArray = new JSONArray();

    public void Loginlog(long id, boolean result, int failedattempts, int attempts, long eventTime, long mLastInteractionTime) {
        eventTime = System.currentTimeMillis();

        createJson(appContextName , " ID : " + id + " Result : " + result + " failedattempts : " + failedattempts + " attempts : " + attempts + " eventTime : " + " mLastInteractionTime : " + mLastInteractionTime);

                    /*logLogin(id,
                    result,
                    failedattempts,
                    attempts,
                    eventTime,
                    mLastInteractionTime);*/

    }

    public void Logoutlog(long eventTime, boolean isLoggedOut) {
        eventTime = System.currentTimeMillis();

        createJson(appContextName, " eventTime : " + eventTime + " isLoggedOut : " + isLoggedOut);

    }

    private void createJson(String context, String logData) {
        try {
            Log.d("data", logData);

            JSONObject jsonObjOne = new JSONObject();
            jsonObjOne.put("context", context);
            jsonObjOne.put("logData", logData);

            jsonArray.put(jsonObjOne);

            JSONObject json = new JSONObject();
            json.put("JsonData", jsonArray);

           // Log.e("Your_JSON", json.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Out Put:

```<code>{
    "JsonData": [{
        "context": "AppEventLogger",
        "logData": " ID : 1 Result : true failedattempts : 11 attempts : 112 eventTime :  mLastInteractionTime : 12"
    }, {
        "context": "AppEventLogger",
        "logData": " eventTime : 1512374548115 isLoggedOut : false"
    }]
}
</code>```

Old answer

Your LOG string goes here:

```<code> private void createJson(String logData) {
        try {
            Log.d("data", logData);
            JSONArray jsonArray = new JSONArray();

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("log", logData);

            jsonArray.put(jsonObj);
            Log.e("Your_JSON",jsonObj.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
</code>```

call this method from where you want to store  LOG data

```<code>createJson("12343434");
</code>```

Output:

```<code>{"log":"12343434"}
</code>```

New code to convert String to JSON

StringToJson.java file

```<code>/**
 * Created by dhruv on 18/12/17.
 */

public class StringToJson {

    private Context context;

    //Crating constructor
    public StringToJson(Context context) {

        this.context = context;
    }

    public String getJson(String name, String sport, String age, String id, ArrayList lastScores) {

        String result = "";
        JSONObject json = new JSONObject();
        JSONObject mainJson = new JSONObject();
        JSONArray jsonArr = new JSONArray();

        try {

            mainJson.put("name", name);
            mainJson.put("sport", sport);
            mainJson.put("age", age);
            mainJson.put("id", id);

            if (!lastScores.isEmpty()) {

                for (int i = 0; i < lastScores.size(); i++) {
                    jsonArr.put(lastScores.get(i));
                }

            }

            mainJson.put("lastScores", jsonArr);

            json.put("result", mainJson);

            result = json.get("result").toString();

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return result;
    }
}
</code>```

MainActivity.java (simple class that call method)

```<code>public class StringToJs extends AppCompatActivity {

    private StringToJson stringToJson;
    private ArrayList jsonArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_string_to_js);

        jsonArray = new ArrayList();
        for (int i = 0; i < 10; i++) {
            jsonArray.add(i);
        }

        stringToJson = new StringToJson(StringToJs.this);

        Log.e("JSON: ", stringToJson.getJson("my_name", "Cricket", "23", "1", jsonArray));

    }
}
</code>```

OUTPUT

```<code>{
    "name": "my_name",
    "sport": "Cricket",
    "age": "23",
    "id": "1",
    "lastScores": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
</code>```

Body:
I am logging events in the android application.

Now I need to store the Log data that is generated by the application in JSON format.How can I do this... any suggestion for this?

this is the code for logging various events of the Android application using AppEventLogger class

public  class AppEventLogger {

private static final String TAG = AppEventsLogger.class.getCanonicalName();

public void Loginlog(Long id,  boolean result, int failedattempts, int attempts,long eventTime, long mLastInteractionTime) {
    final long eventTime = System.currentTimeMillis();

    logLogin(
        id,
        result,
        failedattempts,
        attempts,
        eventTime,
        mLastInteractionTime);

}

public void Logoutlog(long eventTime ,boolean isLoggedOut,){
    final long eventTime = System.currentTimeMillis();

    logLogout(
        eventTime,
        isLoggedOut);
}

Body:
Try this

Changes in your class:

package com.nct.dhruv.demotest;

import android.content.Context;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by user31 on 4/12/17.
 */

public class AppEventLogger {

    private Context mContext;
    private String appContextName = "AppEventLogger";

    public AppEventLogger(Context context) {
        mContext = context;
        Loginlog(1, true, 11, 112, 121, 12);
        Logoutlog(2, false);

    }

    //private static final String TAG = AppEventsLogger.class.getCanonicalName();
    JSONArray jsonArray = new JSONArray();

    public void Loginlog(long id, boolean result, int failedattempts, int attempts, long eventTime, long mLastInteractionTime) {
        eventTime = System.currentTimeMillis();

        createJson(appContextName , " ID : " + id + " Result : " + result + " failedattempts : " + failedattempts + " attempts : " + attempts + " eventTime : " + " mLastInteractionTime : " + mLastInteractionTime);

                    /*logLogin(id,
                    result,
                    failedattempts,
                    attempts,
                    eventTime,
                    mLastInteractionTime);*/

    }

    public void Logoutlog(long eventTime, boolean isLoggedOut) {
        eventTime = System.currentTimeMillis();

        createJson(appContextName, " eventTime : " + eventTime + " isLoggedOut : " + isLoggedOut);

    }

    private void createJson(String context, String logData) {
        try {
            Log.d("data", logData);

            JSONObject jsonObjOne = new JSONObject();
            jsonObjOne.put("context", context);
            jsonObjOne.put("logData", logData);

            jsonArray.put(jsonObjOne);

            JSONObject json = new JSONObject();
            json.put("JsonData", jsonArray);

           // Log.e("Your_JSON", json.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Out Put:

{
    "JsonData": [{
        "context": "AppEventLogger",
        "logData": " ID : 1 Result : true failedattempts : 11 attempts : 112 eventTime :  mLastInteractionTime : 12"
    }, {
        "context": "AppEventLogger",
        "logData": " eventTime : 1512374548115 isLoggedOut : false"
    }]
}

Old answer

Your LOG string goes here:

 private void createJson(String logData) {
        try {
            Log.d("data", logData);
            JSONArray jsonArray = new JSONArray();

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("log", logData);

            jsonArray.put(jsonObj);
            Log.e("Your_JSON",jsonObj.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

call this method from where you want to store  LOG data

createJson("12343434");

Output:

{"log":"12343434"}

New code to convert String to JSON

StringToJson.java file

/**
 * Created by dhruv on 18/12/17.
 */

public class StringToJson {

    private Context context;

    //Crating constructor
    public StringToJson(Context context) {

        this.context = context;
    }

    public String getJson(String name, String sport, String age, String id, ArrayList lastScores) {

        String result = "";
        JSONObject json = new JSONObject();
        JSONObject mainJson = new JSONObject();
        JSONArray jsonArr = new JSONArray();

        try {

            mainJson.put("name", name);
            mainJson.put("sport", sport);
            mainJson.put("age", age);
            mainJson.put("id", id);

            if (!lastScores.isEmpty()) {

                for (int i = 0; i < lastScores.size(); i++) {
                    jsonArr.put(lastScores.get(i));
                }

            }

            mainJson.put("lastScores", jsonArr);

            json.put("result", mainJson);

            result = json.get("result").toString();

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return result;
    }
}

MainActivity.java (simple class that call method)

public class StringToJs extends AppCompatActivity {

    private StringToJson stringToJson;
    private ArrayList jsonArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_string_to_js);

        jsonArray = new ArrayList();
        for (int i = 0; i < 10; i++) {
            jsonArray.add(i);
        }

        stringToJson = new StringToJson(StringToJs.this);

        Log.e("JSON: ", stringToJson.getJson("my_name", "Cricket", "23", "1", jsonArray));

    }
}

OUTPUT

{
    "name": "my_name",
    "sport": "Cricket",
    "age": "23",
    "id": "1",
    "lastScores": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}


答:
You can use boolean indexing with isin and month &
day or numpy.in1d with strftime:

Notice: datetimes are indices in both DataFrames

```<code>df = df_b[df_b.index.month.isin(df_a.index.month) & df_b.index.day.isin(df_a.index.day)]
print (df)
                   var
datetime
2000-10-15  114.232790
2000-10-16  113.020661
</code>```

Or:

```<code>df = df_b[np.in1d(df_b.index.strftime('%m%d'), df_a.index.strftime('%m%d'))]
print (df)
                   var
datetime
2000-10-15  114.232790
2000-10-16  113.020661
</code>```

Title: rearrange dataframe based on day and month from another dataframe index

Body:
I have 2 dataframes:

df_a

datetime      var
2016-10-15    110.232790
2016-10-16    111.020661
2016-10-17    112.193496
2016-10-18    113.638143
2016-10-19    115.241448

and df_b

datetime      var
2000-01-01    165.792185
2000-01-02    166.066959
2000-01-03    166.411669
2000-01-04    167.816046
2000-01-05    169.777814
2000-10-15    114.232790
2000-10-16    113.020661

df_a has information for the year 2016 and df_b has information for years from 2000 to 2015 (there is no overlap in the years).

Can I arrange the df_b dataframe to have the same order in terms of day of year as df_a?

Body:
You can use boolean indexing with isin and month &
day or numpy.in1d with strftime:

Notice: datetimes are indices in both DataFrames

df = df_b[df_b.index.month.isin(df_a.index.month) & df_b.index.day.isin(df_a.index.day)]
print (df)
                   var
datetime
2000-10-15  114.232790
2000-10-16  113.020661

Or:

df = df_b[np.in1d(df_b.index.strftime('%m%d'), df_a.index.strftime('%m%d'))]
print (df)
                   var
datetime
2000-10-15  114.232790
2000-10-16  113.020661


问:
Google BigQuery - Bug using WITH and RAND()
I came upon an interesting behaviour when I use RAND() within WITH:

```<code>WITH
  t0 AS ( SELECT rand() AS c ),
  t1 AS ( SELECT c FROM t0 ),
  t2 AS ( SELECT c FROM t0 )

SELECT c FROM t1
   UNION ALL
SELECT c FROM t2

--
-- returns:
-- 1    0.229810680294245
-- 2    0.5750437237982657
-- instead of:
-- 1    0.229810680294245
-- 2    0.229810680294245
--
</code>```

The same thing even happens when I do this:

```<code>WITH
  t0 AS ( SELECT rand() AS c )

SELECT c FROM t0
   UNION ALL
SELECT c FROM t0
</code>```

Any clues why that happens?

答:
Surfacing this reply from Elliott Brossard as a comment to a deleted answer:

RAND() is supposed to run only once when used in a WITH clause. WITH
  clauses are similar to macros--they are inlined into the query
  plan--and this is a known bug in that RAND() will be evaluated using
  different seeds when run on different tasks, but the fix is somewhat
  complicated.

Body:
I came upon an interesting behaviour when I use RAND() within WITH:

WITH
  t0 AS ( SELECT rand() AS c ),
  t1 AS ( SELECT c FROM t0 ),
  t2 AS ( SELECT c FROM t0 )

SELECT c FROM t1
   UNION ALL
SELECT c FROM t2

--
-- returns:
-- 1    0.229810680294245
-- 2    0.5750437237982657
-- instead of:
-- 1    0.229810680294245
-- 2    0.229810680294245
--

The same thing even happens when I do this:

WITH
  t0 AS ( SELECT rand() AS c )

SELECT c FROM t0
   UNION ALL
SELECT c FROM t0

Any clues why that happens?


问:
Run a function returning a set on a set, and get back a larger set
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

```<code>ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }
</code>```

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

答:
Using set.union + reduce + map

```<code>In [27]: reduce(set.union,map(doubleIt,q))
Out[27]: {1, 2, 3, 4, 9, 16}
</code>```

Just apply map function will apply the function into all elements and that will return a list of set. Then combine the set.

Body:
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

Body:
Using set.union + reduce + map

In [27]: reduce(set.union,map(doubleIt,q))
Out[27]: {1, 2, 3, 4, 9, 16}

Just apply map function will apply the function into all elements and that will return a list of set. Then combine the set.


问:
Populating a pages html div elements using javascript
I am completing the project: https://googlecreativelab.github.io/coder-projects/projects/pop_up_penguins/ which allows a user to click on 8 penguins within a page. However i'm trying to populate the page in javascript rather than html such that a player can easily adjust the number of penguins within the game.

I was thinking to first build an array from some user selected number.

```<code>penguinarray[count];
</code>```

Then use a for loop to repeatedly place each penguin based on the size of the array.

```<code>for(var i = 0; i < penguinarray.length; i++) {
    document.createElement("penguin1");
}
</code>```

Im not sure however how I can still randomize all the different types of penguins and the snow mounds from the 8 available, or allow the page to change given a different number of penguins.

答:
https://jsfiddle.net/sudarpochong/f1n0190a/1/

Since you deleted the other post, I will just post the answer here, because the question is similar anyway :)

You should practically handle dropdown change event and/or have another button to create those penguins.

```<code>$("#create-penguin").on("click", function() {

  $(".penguin-list").empty();

  // create penguin
  var numberSelected = $("#penguinsSelected").val();
  for(var i = 0; i < numberSelected; i++) {
    var penguinNo = Math.ceil(Math.random() * 8);
    var penguin = $("<div>").addClass("penguin" + penguinNo).html("penguin" + penguinNo);
    $(".penguin-list").append(penguin);
  }

});
</code>```

  var maxPenguin = 64;

  //This code will run after page loads
  $(function() {

    // dropdown 2-64 possible elements
    for (var i = 2; i < maxPenguin; i++) {
      $("#penguinsSelected").append('<option value="' + i + '">' + i + '</option>');
    }

  });

    $(".yeti").mousedown(function() {
        alert("Yaaaarrrr!");
        // yetiClicked();
    });

  $("#create-penguin").on("click", function() {

      $(".penguin-list").empty();

   // create penguin
      var numberSelected = $("#penguinsSelected").val();
      for(var i = 0; i < numberSelected; i++) {
       var penguinNo = Math.ceil(Math.random() * 8);
        var penguin = $("
").addClass("penguin" + penguinNo).html("penguin" + penguinNo);
        $(".penguin-list").append(penguin);
      }

  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*This style  gives the body element in our HTML a cool blue background color*/

body {
  background-color: #ccf5f5;
}

/*This styles the div in the HTML that contains and centers our penguin game*/

#gameholder {
  width: 600px;
  margin-left: auto;
  margin-right: auto;
}

/*This styles the title div in or HTML*/

#title {
  width: 600px;
  height: 150px;
  /*This property embeds an image into the background of our div*/
  background-image: url('media/penguin_title.png');
}

/*This pseudo class is applied when the mouse hovers over the 1st penguin div*/

.penguin1:hover {
  background-image: url('media/mound_1_hover.png');
  /*This property changes our cursor to a pointer indicating an interactive element*/
  cursor: pointer;
}

/*This pseudo class is applied when our 1st penguin div is clicked by the mouse button*/

.penguin1:active {
  background-image: url('media/penguin_1.png');
}

/*This is the style for our 1st penguin div*/

.penguin1 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_1.png');
}

/*These are the styles for our 2nd penguin div.*/

.penguin2:hover {
  background-image: url('media/mound_2_hover.png');
  cursor: pointer;
}

.penguin2:active {
  background-image: url('media/penguin_2.png');
}

.penguin2 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_2.png');
}

/*These are the styles for our 3rd penguin div.*/

.penguin3:hover {
  background-image: url('media/mound_3_hover.png');
  cursor: pointer;
}

.penguin3:active {
  background-image: url('media/penguin_3.png');
}

.penguin3 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_3.png');
}

/*These are the styles for our 4th penguin div.*/

.penguin4:hover {
  background-image: url('media/mound_4_hover.png');
  cursor: pointer;
}

.penguin4:active {
  background-image: url('media/penguin_4.png');
}

.penguin4 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_4.png');
}

/*These are the styles for our 5th penguin div.*/

.penguin5:hover {
  background-image: url('media/mound_5_hover.png');
  cursor: pointer;
}

.penguin5:active {
  background-image: url('media/penguin_5.png');
}

.penguin5 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_5.png');
}

/*These are the styles for our 6th penguin div.*/

.penguin6:hover {
  background-image: url('media/mound_6_hover.png');
  cursor: pointer;
}

.penguin6:active {
  background-image: url('media/penguin_6.png');
}

.penguin6 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_6.png');
}

/*These are the styles for our 7th penguin div.*/

.penguin7:hover {
  background-image: url('mound_7_hover.png');
  cursor: pointer;
}

.penguin7:active {
  background-image: url('media/penguin_7.png');
}

.penguin7 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_7.png');
}

/*These are the styles for our 8th penguin div.*/

.penguin8:hover {
  background-image: url('media/mound_8_hover.png');
  cursor: pointer;
}

.penguin8:active {
  background-image: url('media/penguin_8.png');
}

.penguin8 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_8.png');
}

/*These are the styles for our yeti div.*/

.yeti:hover {
  background-image: url('media/mound_9_hover.png');
  cursor: pointer;
}

.yeti:active {
  background-image: url('media/yeti.png');
}

.yeti {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_9.png');
}</code>```

Number of Penguins
<select id="penguinsSelected" name="Number of Penguins"></select>
<button id="create-penguin">Create</button>

PENGUIN

YETI

```

Body:
I am completing the project: https://googlecreativelab.github.io/coder-projects/projects/pop_up_penguins/ which allows a user to click on 8 penguins within a page. However i'm trying to populate the page in javascript rather than html such that a player can easily adjust the number of penguins within the game.

I was thinking to first build an array from some user selected number.

penguinarray[count];

Then use a for loop to repeatedly place each penguin based on the size of the array.

for(var i = 0; i < penguinarray.length; i++) {
    document.createElement("penguin1");
}

Im not sure however how I can still randomize all the different types of penguins and the snow mounds from the 8 available, or allow the page to change given a different number of penguins.

Body:
https://jsfiddle.net/sudarpochong/f1n0190a/1/

Since you deleted the other post, I will just post the answer here, because the question is similar anyway :)

You should practically handle dropdown change event and/or have another button to create those penguins.

$("#create-penguin").on("click", function() {

  $(".penguin-list").empty();

  // create penguin
  var numberSelected = $("#penguinsSelected").val();
  for(var i = 0; i < numberSelected; i++) {
    var penguinNo = Math.ceil(Math.random() * 8);
    var penguin = $("<div>").addClass("penguin" + penguinNo).html("penguin" + penguinNo);
    $(".penguin-list").append(penguin);
  }

});

  var maxPenguin = 64;

  //This code will run after page loads
  $(function() {

    // dropdown 2-64 possible elements
    for (var i = 2; i < maxPenguin; i++) {
      $("#penguinsSelected").append('<option value="' + i + '">' + i + '</option>');
    }

  });

    $(".yeti").mousedown(function() {
        alert("Yaaaarrrr!");
        // yetiClicked();
    });

  $("#create-penguin").on("click", function() {

      $(".penguin-list").empty();

   // create penguin
      var numberSelected = $("#penguinsSelected").val();
      for(var i = 0; i < numberSelected; i++) {
       var penguinNo = Math.ceil(Math.random() * 8);
        var penguin = $("<div>").addClass("penguin" + penguinNo).html("penguin" + penguinNo);
        $(".penguin-list").append(penguin);
      }

  });

/*This style  gives the body element in our HTML a cool blue background color*/

body {
  background-color: #ccf5f5;
}

/*This styles the div in the HTML that contains and centers our penguin game*/

#gameholder {
  width: 600px;
  margin-left: auto;
  margin-right: auto;
}

/*This styles the title div in or HTML*/

#title {
  width: 600px;
  height: 150px;
  /*This property embeds an image into the background of our div*/
  background-image: url('media/penguin_title.png');
}

/*This pseudo class is applied when the mouse hovers over the 1st penguin div*/

.penguin1:hover {
  background-image: url('media/mound_1_hover.png');
  /*This property changes our cursor to a pointer indicating an interactive element*/
  cursor: pointer;
}

/*This pseudo class is applied when our 1st penguin div is clicked by the mouse button*/

.penguin1:active {
  background-image: url('media/penguin_1.png');
}

/*This is the style for our 1st penguin div*/

.penguin1 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_1.png');
}

/*These are the styles for our 2nd penguin div.*/

.penguin2:hover {
  background-image: url('media/mound_2_hover.png');
  cursor: pointer;
}

.penguin2:active {
  background-image: url('media/penguin_2.png');
}

.penguin2 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_2.png');
}

/*These are the styles for our 3rd penguin div.*/

.penguin3:hover {
  background-image: url('media/mound_3_hover.png');
  cursor: pointer;
}

.penguin3:active {
  background-image: url('media/penguin_3.png');
}

.penguin3 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_3.png');
}

/*These are the styles for our 4th penguin div.*/

.penguin4:hover {
  background-image: url('media/mound_4_hover.png');
  cursor: pointer;
}

.penguin4:active {
  background-image: url('media/penguin_4.png');
}

.penguin4 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_4.png');
}

/*These are the styles for our 5th penguin div.*/

.penguin5:hover {
  background-image: url('media/mound_5_hover.png');
  cursor: pointer;
}

.penguin5:active {
  background-image: url('media/penguin_5.png');
}

.penguin5 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_5.png');
}

/*These are the styles for our 6th penguin div.*/

.penguin6:hover {
  background-image: url('media/mound_6_hover.png');
  cursor: pointer;
}

.penguin6:active {
  background-image: url('media/penguin_6.png');
}

.penguin6 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_6.png');
}

/*These are the styles for our 7th penguin div.*/

.penguin7:hover {
  background-image: url('mound_7_hover.png');
  cursor: pointer;
}

.penguin7:active {
  background-image: url('media/penguin_7.png');
}

.penguin7 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_7.png');
}

/*These are the styles for our 8th penguin div.*/

.penguin8:hover {
  background-image: url('media/mound_8_hover.png');
  cursor: pointer;
}

.penguin8:active {
  background-image: url('media/penguin_8.png');
}

.penguin8 {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_8.png');
}

/*These are the styles for our yeti div.*/

.yeti:hover {
  background-image: url('media/mound_9_hover.png');
  cursor: pointer;
}

.yeti:active {
  background-image: url('media/yeti.png');
}

.yeti {
  width: 200px;
  height: 200px;
  float: left;
  background-image: url('media/mound_9.png');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Number of Penguins</span>
<select id="penguinsSelected" name="Number of Penguins"></select>
<button id="create-penguin">Create</button>
<!--This is the frame for our game. It holds and centers all our other elements-->
<div id="gameholder">
  <!--This holds the title image-->
  <div id="title"></div>
  <!--This holds our penguins and yeti-->
  <div class="penguin">PENGUIN</div>
  <div class="yeti">YETI</div>
  <div class="penguin-list">
  </div>
</div>


问:
postgres server not running in flask
I am trying to put command python run.py but it is always showing this error. What should I do?enter image description here</p>

答:
I'm not a progreSql user but I faced the same problem with mysql some days ago and I just run a command to start mysql and it works!

it looks like your database is not started.

I found this in progres documentation for starting the database :

```<code>postgres -D /usr/local/pgsql/data
</code>```

the path can be changed with the exact path of your progess installation folder

Title: postgres server not running in flask

Body:
I'm not a progreSql user but I faced the same problem with mysql some days ago and I just run a command to start mysql and it works!

it looks like your database is not started.

I found this in progres documentation for starting the database :

postgres -D /usr/local/pgsql/data

the path can be changed with the exact path of your progess installation folder


问:
difference between serial event value and serial port value
i am using jssc to read values from serial ports.once i write to the serial port the following callback is getting called . within that callback i can get values from the event and from serial port itself both contains different values. i want to know the difference between serial port values and serial event values does the event contain the values from serial ports?.</p>

```<code>public class PortReader implements SerialPortEventListener {

SerialPort serialPort;
public PortReader(SerialPort serialPort) {
    this.serialPort = serialPort;
}

@Override
public void serialEvent(SerialPortEvent event) {
    System.out.println("started");
    if (event.isRXCHAR() && event.getEventValue() > 0) {
        try {
            String receivedData =  serialPort.readString(event.getEventValue());
            System.out.println("Received response: " + receivedData);
            receivedData = serialPort.readString();
            System.out.println("Received response: " + receivedData);
        } catch (SerialPortException ex) {
            System.out.println("Error in receiving string from COM-port: " + ex);
        }
    }
}
}
</code>```

答: According to the documentation of JSSC event values are jssc specific while the data that event carries is from serial port.</p>

Body:
i am using jssc to read values from serial ports.once i write to the serial port the following callback is getting called . within that callback i can get values from the event and from serial port itself both contains different values. i want to know the difference between serial port values and serial event values does the event contain the values from serial ports?.

public class PortReader implements SerialPortEventListener {

SerialPort serialPort;
public PortReader(SerialPort serialPort) {
    this.serialPort = serialPort;
}

@Override
public void serialEvent(SerialPortEvent event) {
    System.out.println("started");
    if (event.isRXCHAR() && event.getEventValue() > 0) {
        try {
            String receivedData =  serialPort.readString(event.getEventValue());
            System.out.println("Received response: " + receivedData);
            receivedData = serialPort.readString();
            System.out.println("Received response: " + receivedData);
        } catch (SerialPortException ex) {
            System.out.println("Error in receiving string from COM-port: " + ex);
        }
    }
}
}


问:
How to export jar file using android studio?
Sorry for my English. I am new in android. How to export jar file using the android studio. I searched some code. Here the code:

```<code>task deleteJar(type: Delete) {
   delete 'release/libss.jar'
}

task createJar(type: Copy) {
   from('build/intermediates/bundles/release/')
   into('release/')
   include('classes.jar')
   rename('classes.jar', 'libss.jar')
}

 createJar.dependsOn(deleteJar, build)
</code>```

I will try that  code but jar file not created in the specfic location only empty folder .

Its not work for me.......... Please help me.

答:
First,Build, Select build variants  and you can change the app's build variant. to release. Second, you might use like this code to gradl
look the path "from" carefully.
and set the path include 'classes.jar'
Wish it could be help..</p>

Body:
Sorry for my English. I am new in android. How to export jar file using the android studio. I searched some code. Here the code:

task deleteJar(type: Delete) {
   delete 'release/libss.jar'
}

task createJar(type: Copy) {
   from('build/intermediates/bundles/release/')
   into('release/')
   include('classes.jar')
   rename('classes.jar', 'libss.jar')
}

 createJar.dependsOn(deleteJar, build)

I will try that  code but jar file not created in the specfic location only empty folder .

Its not work for me.......... Please help me.


问:
Display content based on group membership - OKTA + ReactJS
I'm using Okta for user authentication of my SPA (+ Express backend).
How can I use the Okta API to show/hide content based on group membership?

e.g. if I want to show some menu items if the active user is a member of a specific group.

Is there anything in the Okta React SDK?
I'm coming up short, product seems great, docs seems less so.

I've found this API https://developer.okta.com/docs/api/resources/users.html#get-member-groups

I'm however unsure of how to best use this from my app. when and where should I call it, should I store group membership in some object and then pass that to all my sub components?

Any ideas and directions are welcome

答:
By specifying the groups scope, you can return a list of active groups the user is assigned to. In your React app, use @okta/okta-react to overload the default params by passing the following into Security:

```<code><Security issuer={config.issuer}
          client_id={config.client_id}
          redirect_uri={window.location.origin + '/implicit/callback'}
          scope={['openid', 'email', 'profile', 'groups']}
          onAuthRequired={({history}) => history.push('/login')} >
</code>```

Sample code taken from the React Quickstart.

Next, use the getUser() method to return the full user object from the userInfo API.

```<code>this.props.auth.getUser().then(profile => {
  const groups = profile.groups;
  // Do your show/hide logic here
});
</code>```

This requires extra configuration in your Okta OpenID Connect app to accept groups as a scope. More info on that here (Creating Token with Groups) and here (Okta Answers).

Body:
By specifying the groups scope, you can return a list of active groups the user is assigned to. In your React app, use @okta/okta-react to overload the default params by passing the following into Security:

<Security issuer={config.issuer}
          client_id={config.client_id}
          redirect_uri={window.location.origin + '/implicit/callback'}
          scope={['openid', 'email', 'profile', 'groups']}
          onAuthRequired={({history}) => history.push('/login')} >

Sample code taken from the React Quickstart.

Next, use the getUser() method to return the full user object from the userInfo API.

this.props.auth.getUser().then(profile => {
  const groups = profile.groups;
  // Do your show/hide logic here
});

This requires extra configuration in your Okta OpenID Connect app to accept groups as a scope. More info on that here (Creating Token with Groups) and here (Okta Answers).


问:
create json array with php
I find it difficult to create JSON data.
I was wanna make out JSON like the picture below

but I'm having trouble.
I am only able to make like the picture below

The following code I created. please help me, I am really very confused

```<code>foreach ($q->result() as $row){
  $djson[] = array(
    'id' => $row->id_custome,
    'name' => $row->nama_custome
    );
}
return $djson;
</code>```

答:
You should use the key/index

```<code>        foreach ($q->result() as $key=>$row){
          $djson[ ( $key + 1 ) ] = array(
              'id' => $row->id_custome,
              'name' => $row->nama_custome
          );
        }
        return $djson;
</code>```

Note: $key + 1 because you want to start the json from 1.

Title: create json array with php

Body:
I find it difficult to create JSON data.
I was wanna make out JSON like the picture below

but I'm having trouble.
I am only able to make like the picture below

The following code I created. please help me, I am really very confused

foreach ($q->result() as $row){
  $djson[] = array(
    'id' => $row->id_custome,
    'name' => $row->nama_custome
    );
}
return $djson;

Body:
You should use the key/index

        foreach ($q->result() as $key=>$row){
          $djson[ ( $key + 1 ) ] = array(
              'id' => $row->id_custome,
              'name' => $row->nama_custome
          );
        }
        return $djson;

Note: $key + 1 because you want to start the json from 1.


问:
Where is logical error in the given code?
I am trying to add a new node to the linked list. Online tutorials(http://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/) uses a pointer to a pointer and I am not able to understand how it works. So I decided to write my own code but I am having a problem with the push() function. Here is the code.

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

struct node{
    int data;
    struct node* next;
};

void print_list(struct node *head_ptr)
{
    while(head_ptr!=NULL)
    {
        printf("%d->",head_ptr->data);
        head_ptr = head_ptr->next;
    }
}

void push(struct node *head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
}

int main()
{
    struct node *head = (struct node*)malloc(sizeof(struct node));
    struct node *second = (struct node*)malloc(sizeof(struct node));
    struct node *third = (struct node*)malloc(sizeof(struct node));

    head -> data = 1;
    head -> next = second;
    second -> data = 2;
    second -> next = third;
    third -> data = 3;
    third -> next = NULL;

    print_list(head);
    push(head,0);
    printf("\n");
    print_list(head);

    return 0;
}
</code>```

It compiles without error. However, the expected node with value 0 does not get inserted in the beginning of my linked list.

Current Output
1->2->3->
Expected Output
0->1->2->3->

Please help me get the required output without using pointer to a pointer in push() function. Also, share a link to a source which has a good explanation of pointer to a pointer and it relates to the linked list.

答:
Where is logical error in the given code?

In C function arguments are always "call by value".

A function can change the function arguments but this has no impact on the argument in the calling function. Example:

```<code>void x(int a)
{
    a = a + 10;
    printf("%d\n", a);
}

void y(void)
{
    int b = 9;
    x(b);   /* Line 1 */
    x(123); /* Line 2 */
}
</code>```

The line a = a + 10; will have the effect that 19 and 133 are printed instead of 9 and 123.

However it will not have the effect that b is changed to 19 in "line 1"; for "line 2" it should be clear that such an effect is even impossible.

In your code the line head_ptr = ... has the same effect.

Please help me get the required output ...

As the C language does not provide real "call by reference" arguments you use pointers to variables as "call by value" arguments to simulate "call by reference" arguments:

```<code>void x(int *a)
{
    (*a) = (*a) + 10;
    printf("%d\n", *a);
}

...

x(&b);
</code>```

Or, in your example:

```<code>/* Note the two "**"s in this line: */
void push(struct node **head_ptr, int data_val)
{
    ...
    *head_ptr = new_node; /* Note the "*" */
}

...

push(&head,0);
</code>```

Of course you can only pass variables to functions this way.

Body:
I am trying to add a new node to the linked list. Online tutorials(http://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/) uses a pointer to a pointer and I am not able to understand how it works. So I decided to write my own code but I am having a problem with the push() function. Here is the code.

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node* next;
};

void print_list(struct node *head_ptr)
{
    while(head_ptr!=NULL)
    {
        printf("%d->",head_ptr->data);
        head_ptr = head_ptr->next;
    }
}

void push(struct node *head_ptr, int data_val)
{
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node -> data = data_val;

    new_node->next = head_ptr;
    head_ptr = new_node;
}

int main()
{
    struct node *head = (struct node*)malloc(sizeof(struct node));
    struct node *second = (struct node*)malloc(sizeof(struct node));
    struct node *third = (struct node*)malloc(sizeof(struct node));

    head -> data = 1;
    head -> next = second;
    second -> data = 2;
    second -> next = third;
    third -> data = 3;
    third -> next = NULL;

    print_list(head);
    push(head,0);
    printf("\n");
    print_list(head);

    return 0;
}

It compiles without error. However, the expected node with value 0 does not get inserted in the beginning of my linked list.

Current Output
1->2->3->
Expected Output
0->1->2->3->

Please help me get the required output without using pointer to a pointer in push() function. Also, share a link to a source which has a good explanation of pointer to a pointer and it relates to the linked list.

Body:
Where is logical error in the given code?

In C function arguments are always "call by value".

A function can change the function arguments but this has no impact on the argument in the calling function. Example:

void x(int a)
{
    a = a + 10;
    printf("%d\n", a);
}

void y(void)
{
    int b = 9;
    x(b);   /* Line 1 */
    x(123); /* Line 2 */
}

The line a = a + 10; will have the effect that 19 and 133 are printed instead of 9 and 123.

However it will not have the effect that b is changed to 19 in "line 1"; for "line 2" it should be clear that such an effect is even impossible.

In your code the line head_ptr = ... has the same effect.

Please help me get the required output ...

As the C language does not provide real "call by reference" arguments you use pointers to variables as "call by value" arguments to simulate "call by reference" arguments:

void x(int *a)
{
    (*a) = (*a) + 10;
    printf("%d\n", *a);
}

...

x(&b);

Or, in your example:

/* Note the two "**"s in this line: */
void push(struct node **head_ptr, int data_val)
{
    ...
    *head_ptr = new_node; /* Note the "*" */
}

...

push(&head,0);

Of course you can only pass variables to functions this way.


问:
JSON output from the page
I am developing an ASP.NET website in which based on certain logic, I am getting the output in a specific format on http://localhost/menu.aspx?callback=example

On the above URL, I get the output in a specific format foo({"1":"Jeff","2":"Mic","5":"Mark"}); using this small code.

```<code>outputText += Convert.ToString(k.GetValue(0));
for (Int32 i = 1; i < k.Length; i++)
{
    outputText += "," + Convert.ToString(k.GetValue(i));
}
//
outputText += "}" +");";

Response.Write(outputText);
</code>```

The full code of menu.aspx.cs is putup here. http://pastebin.com/dxbNmais

But this the output in html form on menu.aspx page. But my requirement is that the http answer must be json too. Please help in getting this JSON output. Not only that I I haven't tried JSON earlier but I am not too much a pro in ASP.NET.

答:
```<code>Response.ContentType = "application/json";
</code>```

Title: JSON output from the page

Body:
I am developing an ASP.NET website in which based on certain logic, I am getting the output in a specific format on http://localhost/menu.aspx?callback=example

On the above URL, I get the output in a specific format foo({"1":"Jeff","2":"Mic","5":"Mark"}); using this small code.

outputText += Convert.ToString(k.GetValue(0));
for (Int32 i = 1; i < k.Length; i++)
{
    outputText += "," + Convert.ToString(k.GetValue(i));
}
//
outputText += "}" +");";

Response.Write(outputText);

The full code of menu.aspx.cs is putup here. http://pastebin.com/dxbNmais

But this the output in html form on menu.aspx page. But my requirement is that the http answer must be json too. Please help in getting this JSON output. Not only that I I haven't tried JSON earlier but I am not too much a pro in ASP.NET.


问:
SVN remains in conflict?
How do I get this directory out of conflict? I don't care if it's resolved using "theirs" or "mine" or whatever... </p>

```<code>PS C:\Users\Mark\Desktop\myproject> svn ci -m "gr"
svn: Commit failed (details follow):
svn: Aborting commit: 'C:\Users\Mark\Desktop\myproject\addons' remains in conflict

PS C:\Users\Mark\Desktop\myproject> svn resolve --accept working C:\Users\Mark\Desktop\myproject\addons
Resolved conflicted state of 'C:\Users\Mark\Desktop\myproject\addons'

PS C:\Users\Mark\Desktop\myproject> svn ci -m "grr"
svn: Commit failed (details follow):
svn: Commit item 'addons' has copy flag but an invalid revision

PS C:\Users\Mark\Desktop\myproject> svn update
   C addons
svn: Can't move 'addons\debug_toolbar\templates\debug_toolbar\.svn\tmp\entries' to 'addons\debug_toolbar\templates\debug
_toolbar\.svn\entries': The file or directory is corrupted and unreadable.

PS C:\Users\Mark\Desktop\myproject> svn cleanup

PS C:\Users\Mark\Desktop\myproject> svn update
Skipped 'addons'
At revision 51.
Summary of conflicts:
  Skipped paths: 1

PS C:\Users\Mark\Desktop\myproject> svn ci -m "grrr"
svn: Commit failed (details follow):
svn: Aborting commit: 'C:\Users\Mark\Desktop\myproject\addons' remains in conflict
</code>```

答:
I had the same issue on linux, but I couldn't fix it with the accepted answer. I was able to solve it by using cd to go to the correct folder and then executing:

```<code>svn remove --force filename
syn resolve --accept=working filename
svn up
</code>```

That's all.

Title: SVN remains in conflict?

Body:
How do I get this directory out of conflict? I don't care if it's resolved using "theirs" or "mine" or whatever...

PS C:\Users\Mark\Desktop\myproject> svn ci -m "gr"
svn: Commit failed (details follow):
svn: Aborting commit: 'C:\Users\Mark\Desktop\myproject\addons' remains in conflict

PS C:\Users\Mark\Desktop\myproject> svn resolve --accept working C:\Users\Mark\Desktop\myproject\addons
Resolved conflicted state of 'C:\Users\Mark\Desktop\myproject\addons'

PS C:\Users\Mark\Desktop\myproject> svn ci -m "grr"
svn: Commit failed (details follow):
svn: Commit item 'addons' has copy flag but an invalid revision

PS C:\Users\Mark\Desktop\myproject> svn update
   C addons
svn: Can't move 'addons\debug_toolbar\templates\debug_toolbar\.svn\tmp\entries' to 'addons\debug_toolbar\templates\debug
_toolbar\.svn\entries': The file or directory is corrupted and unreadable.

PS C:\Users\Mark\Desktop\myproject> svn cleanup

PS C:\Users\Mark\Desktop\myproject> svn update
Skipped 'addons'
At revision 51.
Summary of conflicts:
  Skipped paths: 1

PS C:\Users\Mark\Desktop\myproject> svn ci -m "grrr"
svn: Commit failed (details follow):
svn: Aborting commit: 'C:\Users\Mark\Desktop\myproject\addons' remains in conflict

Body:
I had the same issue on linux, but I couldn't fix it with the accepted answer. I was able to solve it by using cd to go to the correct folder and then executing:

svn remove --force filename
syn resolve --accept=working filename
svn up

That's all.


问:
Passing params from one controller to another AngularJS
I have a controller which fetches a list of airports, this feeds a single input component which I use for Departing and then again for Arrival. The autocomplete component works great for each case. I am trying to figure out how to pass each inputs selected airports as a individual param to another controller which fetches prices from a second url. Any ideas on how to do this with one component?

This is the controller for the initial fetch

```<code> $scope.airport_list = null;

 $http({
  url: 'someUrl.com',
  method: 'GET'
 })
  .then((response) => {
    $scope.airport_list = response.data.airports;
 });

 $scope.searchFor = function(airportName) {
  $scope.hidelist = false;
  const output = [];
  angular.forEach($scope.airport_list, function(airport) {
    if (airport.name.toLowerCase() === airportName) {
      output.push(airport);
    }
  });
  $scope.airports = output;
 };

 $scope.selectAirport = function(airportName) {
   $scope.airportSearch.name = airportName.name;
   $scope.state = !$scope.state;
 };
</code>```

This is the single input component which is used multiple times.

```<code><div class="control" ng-controller="selectCtrl">
  <div>
    <input type="text" name="airport"
      id="airport" ng-model="airportSearch.name" />
      <div class="airport-container-dropdown" ng-
        hide="!airportSearch.name">
      <div class="airport-list"
        ng-repeat="airport in airport_list | filter:airportSearch"
        ng-show="!state"
        ng-click="selectAirport(airport)">
       {{ airport.name }}
      </div>
    </div>
  </div>
</div>
</code>```

This is how the component is passed for use in the view

```<code>  <div class="control">
    <label for="from">From:</label>
    <selector-component id="from"></selector-component>
  </div>
  <div class="control">
    <label for="to">To:</label>
    <selector-component id="to"></selector-component>
  </div>
</code>```

This is the airport selector component, not anything really going on with it.

```<code>import template from './airport-selector.html';

export const AirportSelectorComponent = {
  template
};
</code>```

答:
Since, selector-component is an AngularJS component, it is capable of accepting the attribute bindings.

You can change the registration of component like this:

```<code>angular.module( ... )
  .component('selectorComponent', {
    ...
    bindings: {
      value: '<'
    },
    ...
  });
</code>```

This will automatically bind a variable value to the controller, which can be accessed in the template using $ctrl.value.

Also, the value can be passed like this:

```<code><selector-component value="bind the value here">
</code>```

Refer to the documentation for more details.

Body:
I have a controller which fetches a list of airports, this feeds a single input component which I use for Departing and then again for Arrival. The autocomplete component works great for each case. I am trying to figure out how to pass each inputs selected airports as a individual param to another controller which fetches prices from a second url. Any ideas on how to do this with one component?

This is the controller for the initial fetch

 $scope.airport_list = null;

 $http({
  url: 'someUrl.com',
  method: 'GET'
 })
  .then((response) => {
    $scope.airport_list = response.data.airports;
 });

 $scope.searchFor = function(airportName) {
  $scope.hidelist = false;
  const output = [];
  angular.forEach($scope.airport_list, function(airport) {
    if (airport.name.toLowerCase() === airportName) {
      output.push(airport);
    }
  });
  $scope.airports = output;
 };

 $scope.selectAirport = function(airportName) {
   $scope.airportSearch.name = airportName.name;
   $scope.state = !$scope.state;
 };

This is the single input component which is used multiple times.

    <input type="text" name="airport"
      id="airport" ng-model="airportSearch.name" />

       {{ airport.name }}

This is how the component is passed for use in the view

    From:
    <selector-component id="from"></selector-component>

    To:
    <selector-component id="to"></selector-component>

This is the airport selector component, not anything really going on with it.

import template from './airport-selector.html';

export const AirportSelectorComponent = {
  template
};

Body:
Since, selector-component is an AngularJS component, it is capable of accepting the attribute bindings.

You can change the registration of component like this:

angular.module( ... )
  .component('selectorComponent', {
    ...
    bindings: {
      value: '<'
    },
    ...
  });

This will automatically bind a variable value to the controller, which can be accessed in the template using $ctrl.value.

Also, the value can be passed like this:

<selector-component value="bind the value here">

Refer to the documentation for more details.


问:
Select dataframe columns based on column values in Pandas
My dataframe looks like:

```<code>A  B  C  D  ....  Y   Z
0  5  12 14       4   2
3  6  15 10       1   30
2  10 20 12       5   15
</code>```

I want to create another dataframe that only contains the columns with an average value greater than 10:

```<code>C  D  .... Z
12 14      2
15 10      30
20 12      15
</code>```

答:
Use:

```<code>df = df.loc[:, df.mean() > 10]
print (df)
    C   D   Z
0  12  14   2
1  15  10  30
2  20  12  15
</code>```

Detail:

```<code>print (df.mean())
A     1.666667
B     7.000000
C    15.666667
D    12.000000
Y     3.333333
Z    15.666667
dtype: float64

print (df.mean() > 10)
A    False
B    False
C     True
D     True
Y    False
Z     True
dtype: bool
</code>```

Alternative:

```<code>print (df[df.columns[df.mean() > 10]])
    C   D   Z
0  12  14   2
1  15  10  30
2  20  12  15
</code>```

Detail:

```<code>print (df.columns[df.mean() > 10])
Index(['C', 'D', 'Z'], dtype='object')
</code>```

Body:
My dataframe looks like:

A  B  C  D  ....  Y   Z
0  5  12 14       4   2
3  6  15 10       1   30
2  10 20 12       5   15

I want to create another dataframe that only contains the columns with an average value greater than 10:

C  D  .... Z
12 14      2
15 10      30
20 12      15

Body:
Use:

df = df.loc[:, df.mean() > 10]
print (df)
    C   D   Z
0  12  14   2
1  15  10  30
2  20  12  15

Detail:

print (df.mean())
A     1.666667
B     7.000000
C    15.666667
D    12.000000
Y     3.333333
Z    15.666667
dtype: float64

print (df.mean() > 10)
A    False
B    False
C     True
D     True
Y    False
Z     True
dtype: bool

Alternative:

print (df[df.columns[df.mean() > 10]])
    C   D   Z
0  12  14   2
1  15  10  30
2  20  12  15

Detail:

print (df.columns[df.mean() > 10])
Index(['C', 'D', 'Z'], dtype='object')


问:
Initialize and declare variable in if-else condition in JAVA
I'm trying to initialize and declare variable in if-else condition in JAVA, but it is not executing, can someone please help me in below code?

This is the method, which I'm calling from main method. But it's not executing the initialization under if condition and failing.

```<code>    public static void getData(String funct) {
            try {
                    if ("lob".equals(funct)) {
                            String sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
                    }
                    else {
                            String sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
                    }
                    Connection conn=DriverManager.getConnection
                    ("jdbc:oracle:thin:@172.23.240.41:1521:BCTOOLS","AMCOPR","AMCOPR");

                    Statement stmt = conn.createStatement();
                    ResultSet rst;

                    System.out.println(funct);

                    rst = stmt.executeQuery(sql1);

                    while (rst.next()) {
                            String lobName = rst.getString("lob_name");
                            System.out.format("%s\n",lobName);
                    }

                    conn.close();
            }
            catch (Exception e) {
                    System.err.println("Got an exception! ");
                    System.err.println(e.getMessage());
            }
    }
</code>```

}

PLEASE HELP :)
Thanks,

答:
Santosh's Answer is correct. Adding an explanation, as to WHY?

It is in fact initializing the variable sql1 (that too 2 variables), but you are unable to see that for the simple reason that, the variable is available only in the scope where it is declared.

You have declared two different variables both named sql1 but in different scopes, one inside the if block and another inside the else block

And when you try to access the variable outside the scope, it is throwing an exception.

Solution: Declare the variable, outside the if/else block, i.e. in the beginning of the getData method, and only assign the values inside the if/else blocks. This will solve your problem.

```<code>String sql1 = "";

try{
   if(condition){
      sql1= "<something>";
   }
   else{
     sql1= "<something else>";
   }
}
</code>```

Body:
I'm trying to initialize and declare variable in if-else condition in JAVA, but it is not executing, can someone please help me in below code?

This is the method, which I'm calling from main method. But it's not executing the initialization under if condition and failing.

    public static void getData(String funct) {
            try {
                    if ("lob".equals(funct)) {
                            String sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
                    }
                    else {
                            String sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
                    }
                    Connection conn=DriverManager.getConnection
                    ("jdbc:oracle:thin:@172.23.240.41:1521:BCTOOLS","AMCOPR","AMCOPR");

                    Statement stmt = conn.createStatement();
                    ResultSet rst;

                    System.out.println(funct);

                    rst = stmt.executeQuery(sql1);

                    while (rst.next()) {
                            String lobName = rst.getString("lob_name");
                            System.out.format("%s\n",lobName);
                    }

                    conn.close();
            }
            catch (Exception e) {
                    System.err.println("Got an exception! ");
                    System.err.println(e.getMessage());
            }
    }

}

PLEASE HELP :)
Thanks,

Body:
Santosh's Answer is correct. Adding an explanation, as to WHY?

It is in fact initializing the variable sql1 (that too 2 variables), but you are unable to see that for the simple reason that, the variable is available only in the scope where it is declared.

You have declared two different variables both named sql1 but in different scopes, one inside the if block and another inside the else block

And when you try to access the variable outside the scope, it is throwing an exception.

Solution: Declare the variable, outside the if/else block, i.e. in the beginning of the getData method, and only assign the values inside the if/else blocks. This will solve your problem.

String sql1 = "";

try{
   if(condition){
      sql1= "<something>";
   }
   else{
     sql1= "<something else>";
   }
}


问:
Retrieve multiple values via SELECT Option in Django Templates
I'm using Python(3.6) & Django(1.10) and need multiple values from a drop-down option selection.

Here's what I have tried:
From template:

```<code><select id="slc" name="cluster">
<option value="{{cluster.name}}#{{cluster.zone}}"> {{ cluster.name }}</option>
</select>
</code>```

From views.py:

```<code>    def post(self, request, *args, **kwargs):
      if request.method == 'POST':
         post_data = request.POST.copy()
         form = forms.ClusterForm(post_data)
         if form.is_valid():
            project = form.cleaned_data['project']
            blocks = request.POST.get('cluster').split('#')
</code>```

How can i get the values for name & zone.I already take a deep look at the existing questions but couldn't solve my issue.So, don't mark this question as a duplicate, please!

Help me, Please!
Thanks in advance!

答:
Its recommended to send id of cluster as value and fetch cluster object in your view.

<option value="{{cluster.id}}"></option>

You can do it using javascript, but not with Django form submit it will always send value attribute of <option> tag to your views.

```<code><select id="slc" name="cluster">
   <option value="{{cluster.id}}" c-name="{{cluster.name}}" c-zone="{{cluster.zone}}" > {{ cluster.name }}</option>
</select>

<script>
    $(function() {
        $("#slc").change(function(){
            var selected_option = $('option:selected', this);
            var cluster_name = selected_option.attr('c-name');
            var cluster_zone = selected_option.attr('c-zone');
        });
    });
</script>
</code>```

UPDATE

$("#slc").change(function() {
  var selected_option = $('option:selected', this);
  var cluster_name = selected_option.attr('c-name');
  console.log("cluster_name:", cluster_name);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body>
  <select id="slc">
      <option c-name="volvo" value="1">Volvo</option>
      <option c-name="saab" value="2">Saab</option>
      <option c-name="opel" value="3">Opel</option>
      <option c-name="audi" value="4">Audi</option>
    </select>
</body>

</html></code>```

Body:
I'm using Python(3.6) & Django(1.10) and need multiple values from a drop-down option selection.

Here's what I have tried:
From template:

<select id="slc" name="cluster">
<option value="{{cluster.name}}#{{cluster.zone}}"> {{ cluster.name }}</option>
</select>

From views.py:

    def post(self, request, *args, **kwargs):
      if request.method == 'POST':
         post_data = request.POST.copy()
         form = forms.ClusterForm(post_data)
         if form.is_valid():
            project = form.cleaned_data['project']
            blocks = request.POST.get('cluster').split('#')

How can i get the values for name & zone.I already take a deep look at the existing questions but couldn't solve my issue.So, don't mark this question as a duplicate, please!

Help me, Please!
Thanks in advance!

Body:
Its recommended to send id of cluster as value and fetch cluster object in your view.

<option value="{{cluster.id}}"></option>

You can do it using javascript, but not with Django form submit it will always send value attribute of <option> tag to your views.

<select id="slc" name="cluster">
   <option value="{{cluster.id}}" c-name="{{cluster.name}}" c-zone="{{cluster.zone}}" > {{ cluster.name }}</option>
</select>

<script>
    $(function() {
        $("#slc").change(function(){
            var selected_option = $('option:selected', this);
            var cluster_name = selected_option.attr('c-name');
            var cluster_zone = selected_option.attr('c-zone');
        });
    });
</script>

UPDATE

$("#slc").change(function() {
  var selected_option = $('option:selected', this);
  var cluster_name = selected_option.attr('c-name');
  console.log("cluster_name:", cluster_name);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<body>
  <select id="slc">
      <option c-name="volvo" value="1">Volvo</option>
      <option c-name="saab" value="2">Saab</option>
      <option c-name="opel" value="3">Opel</option>
      <option c-name="audi" value="4">Audi</option>
    </select>
</body>

</html>


问:
Insert unique values in Array in Javascript
I have one array. The function gets called continuously from backend service.
I want to push unique values in one object. My code is

```<code>currentValue =  pointerToVisconCtrl.MappedVariableObj.value;
var seconds = new Date().getSeconds();
seconds = parseInt(seconds);
graphDataObject.push({timestamp : seconds, value : currentValue});
</code>```

Please guide me to enter only unique currentValue and seconds value in graphDataObject

答:
```<code>var finalArr = graphDataObject.filter(function(d){
if(d.value == currentValue){ return d;}
});

if(finalArr.length == 0){
graphDataObject.push({timestamp : seconds, value : currentValue});
}
</code>```

Body:
I have one array. The function gets called continuously from backend service.
I want to push unique values in one object. My code is

currentValue =  pointerToVisconCtrl.MappedVariableObj.value;
var seconds = new Date().getSeconds();
seconds = parseInt(seconds);
graphDataObject.push({timestamp : seconds, value : currentValue});

Please guide me to enter only unique currentValue and seconds value in graphDataObject


问:
set content type header with rails and apache
I want to send a generated view as a kml file, with the necessary headers(content-type and file expires in)... the use of head gives a 500, and using response.headers has no effect...

What should i do?

答:
You'd need to register the KML mime type. In your config/initializers/mime_types.rb

```<code>Mime::Type.register "application/vnd.google-earth.kml", :kml
</code>```

Then in your action you can do:

```<code>format.kml { ... }
</code>```

KML Tutorial: http://code.google.com/apis/kml/documentation/kml_tut.html#kml_server

Body:
You'd need to register the KML mime type. In your config/initializers/mime_types.rb

Mime::Type.register "application/vnd.google-earth.kml", :kml

Then in your action you can do:

format.kml { ... }

KML Tutorial: http://code.google.com/apis/kml/documentation/kml_tut.html#kml_server