答:
That's how you can do it:

parent-form.html

<compose view-model.bind="childFormVM" view-model.ref="childFormInstance" model.bind="model"></compose>
```
<p>parent-form.js</p>
<pre class="lang-js prettyprint-override"><code>save() {
  this.childFormInstance.currentViewModel.validateRules();
}
</code>```

Helpful Notes

Only use <compose> when necessary. For example, in the app.html you should replace <compose> for:

```<code><require from="parentForm"></require>

<parent-form></parent-form>
</code>```

Use kebab-case instead of camel-case to name your files. For example, instead of parentForm.html and parentForm.js, use parent-form.html and parent-form.js. This won't change a thing in your code but you will be following nice javascript standards :)

When binding directly to a string you don't need to use .bind. For example, view-model.bind="'parentForm'" could be replaced for view-model="./parentForm"

Hope this helps!

Title: AureliaJS - Call child function from parent

Body:
That's how you can do it:

parent-form.html

<compose view-model.bind="childFormVM" view-model.ref="childFormInstance" model.bind="model"></compose>

parent-form.js

save() {
  this.childFormInstance.currentViewModel.validateRules();
}

Helpful Notes

Only use <compose> when necessary. For example, in the app.html you should replace <compose> for:

<require from="parentForm"></require>

<parent-form></parent-form>

Use kebab-case instead of camel-case to name your files. For example, instead of parentForm.html and parentForm.js, use parent-form.html and parent-form.js. This won't change a thing in your code but you will be following nice javascript standards :)

When binding directly to a string you don't need to use .bind. For example, view-model.bind="'parentForm'" could be replaced for view-model="./parentForm"

Hope this helps!


来源: stackexchange

问:
If i login with a user it logs in with any password

<?php
require 'includes/common.php';
$email=$_POST['email'];
$password=$_POST['password'];
$email= mysqli_real_escape_string($con, $email);
$password= mysqli_real_escape_string($con, $password);
//md5($password);
 $select_user_query="select id , email from users where email='$email' and password= $password";
 //removed 'email' to email//
        $select_user_result= mysqli_query($con, $select_user_query) or die (mysqli_error($con));

               if (mysqli_num_rows($select_user_result==0))
               {
                   echo 'There no such user ';
               }

               else
               {
                   $row=mysqli_fetch_array($select_user_result);
                   $_SESSION['email']=$email;
                   $_SESSION['id']= $row[0];
                   header('location:products.php');
               }

?>           ```

 here is the code

**

here i am geting

email and password from post method

From my login page

i think most of the code is right

If i login with a user it logs in with any password

**

答: Put single quotes around $password in your query and then try.</p>

ContentLicense: CC BY-SA 3.0

Body:
<?php
require 'includes/common.php';
$email=$_POST['email'];
$password=$_POST['password'];
$email= mysqli_real_escape_string($con, $email);
$password= mysqli_real_escape_string($con, $password);
//md5($password);
 $select_user_query="select id , email from users where email='$email' and password= $password";
 //removed 'email' to email//
        $select_user_result= mysqli_query($con, $select_user_query) or die (mysqli_error($con));

               if (mysqli_num_rows($select_user_result==0))
               {
                   echo 'There no such user ';
               }

               else
               {
                   $row=mysqli_fetch_array($select_user_result);
                   $_SESSION['email']=$email;
                   $_SESSION['id']= $row[0];
                   header('location:products.php');
               }

?>

 here is the code

**

here i am geting

email and password from post method

From my login page

i think most of the code is right

If i login with a user it logs in with any password

**


问:
Want to show/hide div based on dropdown box selection
I want to have jQuery show div id='business' only if 'business use' is selected in the dropdown box.

This is my code:

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$('#purpose').on('change', function() {
  if ( this.value == '1');
  {
    $("#business").show();
  }
  else
  {
    $("#business").hide();
  }
});
});
</script>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name<br/>
<br/>
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
</body>
</code>```

and the JSFiddle: http://jsfiddle.net/2kGzZ/1/

答:
try this which is working for me in my test demo</p>

```<code><script>
$(document).ready(function(){
$('#dropdown').change(function()
{
//  var selectedValue = parseInt(jQuery(this).val());
var text = $('#dropdown').val();
//alert("text");
    //Depend on Value i.e. 0 or 1 respective function gets called.
    switch(text){
        case 'Reporting':
          // alert("hello1");
   $("#td1").hide();
            break;
        case 'Buyer':
      //alert("hello");
     $("#td1").show();
            break;
        //etc...
        default:
            alert("catch default");
            break;
    }
});
});

</script>
</code>```

Body:
I want to have jQuery show div id='business' only if 'business use' is selected in the dropdown box.

This is my code:

<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>

Business Name

    <input type='text' class='text' name='business' value size='20' />

and the JSFiddle: http://jsfiddle.net/2kGzZ/1/

Body:
try this which is working for me in my test demo

<script>
$(document).ready(function(){
$('#dropdown').change(function()
{
//  var selectedValue = parseInt(jQuery(this).val());
var text = $('#dropdown').val();
//alert("text");
    //Depend on Value i.e. 0 or 1 respective function gets called.
    switch(text){
        case 'Reporting':
          // alert("hello1");
   $("#td1").hide();
            break;
        case 'Buyer':
      //alert("hello");
     $("#td1").show();
            break;
        //etc...
        default:
            alert("catch default");
            break;
    }
});
});

</script>


问:
Xamarin iOS UiPickerView tutorial
I'm trying to find just some basic instructions on using UiPickerView in Xamarin iOS. There are questions here on Stack Overflow that answer certain questions, but I'm looking for just a simple overview and hopefully walk-through of adding the UiPickerView to a ViewController, wiring up the data, and registering events. As a noob to Xamarin and iOS, I'm struggling to catalogue all the places the code for this type of control need to go.</p>

答:
```<code>// Textfield Click event
private bool OnTodeapartmentShouldBeginEditing(UITextField textField)
{

// Creating Picker view
pickerView = new UIPickerView(new CGRect(UIScreen.MainScreen.Bounds.X-UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height -230, UIScreen.MainScreen.Bounds.Width, 180));
pickerView.BackgroundColor = UIColor.From#d3d3d3;
pickerView.ShowSelectionIndicator = true;

// create done button
done = new UIButton(new CGRect(pickerView.Frame.X, pickerView.Frame.Y - 50, UIScreen.MainScreen.Bounds.Width, 50));
done.BackgroundColor = UIColor.Purple;
done.SetTitle("Department List", UIControlState.Normal);

picker = new PickerDataModel();
if (departmentList.DepartmentDetail != null)
{

foreach (var item in departmentList.DepartmentDetail)
{
picker.Items.Add(item.Name);
}
pickerView.Model = picker;

view.AddSubviews(pickerView, done);
// value change event of picker view
picker.ValueChanged += (s, e) =>
{
selectedValue = picker.SelectedItem;
txtDepartment.Text = selectedValue;

deptID = departmentList.DepartmentDetail.Find(x => x.Name == selectedValue).DepartmentId;

};
}
}
</code>```

New Class File enter image description here
   // Picker Data Model Class for picker view , this class file is using on helper section for common use

```<code>public class PickerDataModel : UIPickerViewModel
{
public event EventHandler<EventArgs> ValueChanged;

/// <summary>
/// The items to show up in the picker
/// </summary>
public List<string> Items { get; private set; }

/// <summary>
/// The current selected item
/// </summary>
public string SelectedItem
{
get { return Items[SelectedIndex]; }
}

public int SelectedIndex
{
get
{
return selectedIndex;
}

set
{
selectedIndex = value;
}
}

private int selectedIndex;

public PickerDataModel()
{
Items = new List<string>();
}

/// <summary>
/// Called by the picker to determine how many rows are in a given spinner item
/// </summary>
public override nint GetRowsInComponent(UIPickerView picker, nint component)
{
return Items.Count;
}

/// <summary>
/// called by the picker to get the text for a particular row in a particular
/// spinner item
/// </summary>
public override string GetTitle(UIPickerView picker, nint row, nint component)
{
return Items[(int)row];
}

/// <summary>
/// called by the picker to get the number of spinner items
/// </summary>
public override nint GetComponentCount(UIPickerView picker)
{
return 1;
}

/// <summary>
/// called when a row is selected in the spinner
/// </summary>
public override void Selected(UIPickerView picker, nint row, nint component)
{
SelectedIndex = (int)row;
if (ValueChanged != null)
{
ValueChanged(this, new EventArgs());
}

}
} [enter image description here][1]

  [1]: https://i.stack.imgur.com/Ld1uU.png
</code>```

Title: Xamarin iOS UiPickerView tutorial

Body:
// Textfield Click event
private bool OnTodeapartmentShouldBeginEditing(UITextField textField)
{

// Creating Picker view
pickerView = new UIPickerView(new CGRect(UIScreen.MainScreen.Bounds.X-UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height -230, UIScreen.MainScreen.Bounds.Width, 180));
pickerView.BackgroundColor = UIColor.From#d3d3d3;
pickerView.ShowSelectionIndicator = true;

// create done button
done = new UIButton(new CGRect(pickerView.Frame.X, pickerView.Frame.Y - 50, UIScreen.MainScreen.Bounds.Width, 50));
done.BackgroundColor = UIColor.Purple;
done.SetTitle("Department List", UIControlState.Normal);

picker = new PickerDataModel();
if (departmentList.DepartmentDetail != null)
{

foreach (var item in departmentList.DepartmentDetail)
{
picker.Items.Add(item.Name);
}
pickerView.Model = picker;

view.AddSubviews(pickerView, done);
// value change event of picker view
picker.ValueChanged += (s, e) =>
{
selectedValue = picker.SelectedItem;
txtDepartment.Text = selectedValue;

deptID = departmentList.DepartmentDetail.Find(x => x.Name == selectedValue).DepartmentId;

};
}
}

New Class File enter image description here
   // Picker Data Model Class for picker view , this class file is using on helper section for common use

public class PickerDataModel : UIPickerViewModel
{
public event EventHandler<EventArgs> ValueChanged;

/// <summary>
/// The items to show up in the picker
/// </summary>
public List<string> Items { get; private set; }

/// <summary>
/// The current selected item
/// </summary>
public string SelectedItem
{
get { return Items[SelectedIndex]; }
}

public int SelectedIndex
{
get
{
return selectedIndex;
}

set
{
selectedIndex = value;
}
}

private int selectedIndex;

public PickerDataModel()
{
Items = new List<string>();
}

/// <summary>
/// Called by the picker to determine how many rows are in a given spinner item
/// </summary>
public override nint GetRowsInComponent(UIPickerView picker, nint component)
{
return Items.Count;
}

/// <summary>
/// called by the picker to get the text for a particular row in a particular
/// spinner item
/// </summary>
public override string GetTitle(UIPickerView picker, nint row, nint component)
{
return Items[(int)row];
}

/// <summary>
/// called by the picker to get the number of spinner items
/// </summary>
public override nint GetComponentCount(UIPickerView picker)
{
return 1;
}

/// <summary>
/// called when a row is selected in the spinner
/// </summary>
public override void Selected(UIPickerView picker, nint row, nint component)
{
SelectedIndex = (int)row;
if (ValueChanged != null)
{
ValueChanged(this, new EventArgs());
}

}
} [enter image description here][1]

  [1]: https://i.stack.imgur.com/Ld1uU.png


问:
What is the maximum recommended number of rows that a SQL 2008 R2 standalone server should store in a single table?
I'm designing my DB for functionality and performance for realtime AJAX web applications, and I don't currently have the resources to add DB server redundancy or load-balancing.

Unfortunately, I have a table in my DB that could potentially end up storing hundreds of millions of rows, and will need to read and write quickly to prevent lagging the web-interface.

Most, if not all, of the columns in this table are individually indexed, and I'd love to know if there are other ways to ease the burden on the server when running querys on large tables. But is there eventually a cap for the size (in rows or GB) of a table before a single unclustered SQL server starts to choke?

My DB only has a dozen tables, with maybe a couple dozen foriegn key relationships. None of my tables have more than 8 or so columns, and only one or two of these tables will end up storing a large number of rows. Hopefully the simplicity of my DB will make up for the massive amounts of data in these couple tables ...

答:
My gut tells me that you will probably be okay, but you'll have to deal with performance.  It's going to depend on the acceptable time-to-retrieve results from queries.

For your table with the "hundreds of millions of rows", what percentage of the data is accessed regularly?  Is some of the data, rarely accessed?  Do some users access selected data and other users select different data?  You may benefit from data partitioning.

ContentLicense: CC BY-SA 2.5


问:
Scala: it is possible to use generic type at runtime?
i wonder if i can change the implementation of such a method:

```<code>def foo() {
   val json : String = ; // get json from somewhere
   val jsonAst = new String(json).parseJson // or JsonParser(source)
   val msg = jsonAst.convertTo[UserDetails]
</code>```

}

so i can provide the "UserDetails" as parameter

so calling foo will be something like:

```<code>foo[UserDetails]()....
</code>```

by the way:

convertTo signature is:

```<code>def convertTo[T :JsonReader]: T = jsonReader[T].read(this)

trait JsonReader[T] {
   def read(json: JsValue): T
}
</code>```

答:
You should be able to just declare your function the same way:

```<code>def foo[T : JsonReader] = {
  ...
  val msg = jsonAst.convertTo[T]
}
</code>```

UPDATE To elaborate, since there appears to be some confusion in the comments. def foo[T : JsonReader] does not mean that it accepts only subclasses of JsonReader. That declaration is actually equivalent to this: def foo[T](implicit jsonReader: JsonReader[T])

Body:
i wonder if i can change the implementation of such a method:

def foo() {
   val json : String = ; // get json from somewhere
   val jsonAst = new String(json).parseJson // or JsonParser(source)
   val msg = jsonAst.convertTo[UserDetails]

}

so i can provide the "UserDetails" as parameter

so calling foo will be something like:

foo[UserDetails]()....

by the way:

convertTo signature is:

def convertTo[T :JsonReader]: T = jsonReader[T].read(this)

trait JsonReader[T] {
   def read(json: JsValue): T
}

Body:
You should be able to just declare your function the same way:

def foo[T : JsonReader] = {
  ...
  val msg = jsonAst.convertTo[T]
}

UPDATE To elaborate, since there appears to be some confusion in the comments. def foo[T : JsonReader] does not mean that it accepts only subclasses of JsonReader. That declaration is actually equivalent to this: def foo[T](implicit jsonReader: JsonReader[T])


问:
How to get integer values from array based on first digits java
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

```<code>for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}
</code>```

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

```<code>String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}
</code>```

答:
Here is some untested java code. But very bad practice and bad performance... should work for you anyway ^^

```<code>public static ArrayList<Integer> getStartingWith(int[] numbers, int key)
{
ArrayList<Integer> matching = new ArrayList<Integer>();

String keyAsString = Integer.toString(key);

for(int i = 0; i < numbers.length; i++)
{
    if(Integer.toString(numbers[i]).startsWith(keyAsString))
        matching.add(numbers[i]);
}
return matching;
}
</code>```

Take a look at @Andreas answer. Way smarter than mine!!!

Body:
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}

Body:
Here is some untested java code. But very bad practice and bad performance... should work for you anyway ^^

public static ArrayList<Integer> getStartingWith(int[] numbers, int key)
{
ArrayList<Integer> matching = new ArrayList<Integer>();

String keyAsString = Integer.toString(key);

for(int i = 0; i < numbers.length; i++)
{
    if(Integer.toString(numbers[i]).startsWith(keyAsString))
        matching.add(numbers[i]);
}
return matching;
}

Take a look at @Andreas answer. Way smarter than mine!!!


问:
Are infinite lists useful for any real world applications?
I've been using haskell for quite a while now, and I've read most of Real World Haskell and Learn You a Haskell. What I want to know is whether there is a point to a language using lazy evaluation, in particular the "advantage" of having infinite lists, is there a task which infinite lists make very easy, or even a task that is only possible with infinite lists?</p>

答:
Sound synthesis - see this paper by Jerzy Karczmarczuk:

http://users.info.unicaen.fr/~karczma/arpap/cleasyn.pdf

Jerzy Karczmarcuk has a number of other papers using infinite lists to model mathematical objects like power series and derivatives.

I've translated the basic sound synthesis code to Haskell - enough for a sine wave unit generator and WAV file IO. The performance was just about adequate to run with GHCi on a 1.5GHz Athalon - as I just wanted to test the concept I never got round to optimizing it.


问:
Calculating the amount of time left until completion
I am wondering how to calculate the amount of time it would take to example:

Complete a brute force word list.

I know how to use the time function and measure in time,
but the problem is i need to find out how long it would take in the program itself...

Here is the code i made this yesterday

```<code>import itertools, math
import os
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") # Add or remove whatevs you think will be in the password you're cracking (example, [symbols])
counter = 1
CharLength = 1
range_num = int(raw_input("Enter range: "))
stopper = range_num + 1
filename = "bruteforce_%r.txt" % (range_num)
f = open(filename, 'a')
#n_1 = len(Alphabet)
#n_2 = n_1 - 1 # <-- total useless peice of garbage that could of been great in vurtual life
#n_3 = '0' * n_2
#n = '1' + n_3
x = range_num
y = len(Alphabet)
amount = math.pow(y, x)
total_items = math.pow(y, x)
for CharLength in range(range_num, stopper):
    passwords = (itertools.product(Alphabet, repeat = CharLength))

    for i in passwords:
        counter += 1
        percentage = (counter / total_items) * 100
        amount -= 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        f.write(i)
        f.write('\n')
        print "Password: %r\tPercentage: %r/100\tAmount left: %r" % (i, int(percentage), amount)
        if i == '0'* range_num:
            print "*Done"
            f.close()
            exit(0)
        else:
            pass
</code>```

This is my timer function i managed to make

```<code>#import winsound # Comment this out if your using linux
import os
import time
from sys import exit

print "This is the timer\nHit CTRL-C to stop the timer\nOtherwise just let         it rip untill the time's up"
hours = int(raw_input('Enter the hours.\n>>> '))
os.system('clear') # Linux
#os.system('cls')   # Windows

minutes = int(raw_input('Enter the minutes.\n>>> '))
os.system('clear') # linux
#os.system('cls')   # Windows

seconds = int(raw_input('Enter the seconds.\n>>> '))
os.system('clear') # Linux
#os.system('cls')   # Windows

stop_time = '%r:%r:%r' % (hours, minutes, seconds)

t_hours = 00
t_minutes = 00
t_seconds = 00

while t_seconds <= 60:
    try:
        os.system('clear') # Linux
        #os.system('cls') # Windows
        current_time = '%r:%r:%r' % (t_hours, t_minutes, t_seconds)
        print current_time
        time.sleep(1)
        t_seconds+=1

        if current_time == stop_time:
            print "// Done"
            #winsound.Beep(500,1000)
            #winsound.Beep(400,1000)
            break

        elif t_seconds == 60:
            t_minutes+=1
            t_seconds=0

        elif t_minutes == 60:
            t_hours+=1
            t_minutes = 00

    except KeyboardInterrupt:
        print "Stopped at: %r:%r:%r" % (t_hours, t_minutes, t_seconds)
        raw_input("Hit enter to continue\nHit CTRL-C to end")
        try:
            pass

        except KeyboardInterrupt:
            exit(0)
</code>```

Now i just cant figure out how to make this again but to calculate how long it will take rather than how long it is taking...

答:
You will never ever be able to know exactly how long it is going to take to finish. The best you can do is calculate was percentage of the work you have finished and how long that has taken you and then project that out.

For example if you are doing some work on the range of numbers from 1 to 100 you could do something such as

```<code>start_time = get the current time
for i in range(1, 101):
    # Do some work
    current_time = get the current time
    elapsed_time = current_time - start_time
    time_left = 100 * elapsed_time / i - elapsed_time
    print(time_left)
</code>```

Please understand that the above is largely pseudo-code

Body:
I am wondering how to calculate the amount of time it would take to example:

Complete a brute force word list.

I know how to use the time function and measure in time,
but the problem is i need to find out how long it would take in the program itself...

Here is the code i made this yesterday

import itertools, math
import os
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") # Add or remove whatevs you think will be in the password you're cracking (example, [symbols])
counter = 1
CharLength = 1
range_num = int(raw_input("Enter range: "))
stopper = range_num + 1
filename = "bruteforce_%r.txt" % (range_num)
f = open(filename, 'a')
#n_1 = len(Alphabet)
#n_2 = n_1 - 1 # <-- total useless peice of garbage that could of been great in vurtual life
#n_3 = '0' * n_2
#n = '1' + n_3
x = range_num
y = len(Alphabet)
amount = math.pow(y, x)
total_items = math.pow(y, x)
for CharLength in range(range_num, stopper):
    passwords = (itertools.product(Alphabet, repeat = CharLength))

    for i in passwords:
        counter += 1
        percentage = (counter / total_items) * 100
        amount -= 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        f.write(i)
        f.write('\n')
        print "Password: %r\tPercentage: %r/100\tAmount left: %r" % (i, int(percentage), amount)
        if i == '0'* range_num:
            print "*Done"
            f.close()
            exit(0)
        else:
            pass

This is my timer function i managed to make

#import winsound # Comment this out if your using linux
import os
import time
from sys import exit

print "This is the timer\nHit CTRL-C to stop the timer\nOtherwise just let         it rip untill the time's up"
hours = int(raw_input('Enter the hours.\n>>> '))
os.system('clear') # Linux
#os.system('cls')   # Windows

minutes = int(raw_input('Enter the minutes.\n>>> '))
os.system('clear') # linux
#os.system('cls')   # Windows

seconds = int(raw_input('Enter the seconds.\n>>> '))
os.system('clear') # Linux
#os.system('cls')   # Windows

stop_time = '%r:%r:%r' % (hours, minutes, seconds)

t_hours = 00
t_minutes = 00
t_seconds = 00

while t_seconds <= 60:
    try:
        os.system('clear') # Linux
        #os.system('cls') # Windows
        current_time = '%r:%r:%r' % (t_hours, t_minutes, t_seconds)
        print current_time
        time.sleep(1)
        t_seconds+=1

        if current_time == stop_time:
            print "// Done"
            #winsound.Beep(500,1000)
            #winsound.Beep(400,1000)
            break

        elif t_seconds == 60:
            t_minutes+=1
            t_seconds=0

        elif t_minutes == 60:
            t_hours+=1
            t_minutes = 00

    except KeyboardInterrupt:
        print "Stopped at: %r:%r:%r" % (t_hours, t_minutes, t_seconds)
        raw_input("Hit enter to continue\nHit CTRL-C to end")
        try:
            pass

        except KeyboardInterrupt:
            exit(0)

Now i just cant figure out how to make this again but to calculate how long it will take rather than how long it is taking...

Body:
You will never ever be able to know exactly how long it is going to take to finish. The best you can do is calculate was percentage of the work you have finished and how long that has taken you and then project that out.

For example if you are doing some work on the range of numbers from 1 to 100 you could do something such as

start_time = get the current time
for i in range(1, 101):
    # Do some work
    current_time = get the current time
    elapsed_time = current_time - start_time
    time_left = 100 * elapsed_time / i - elapsed_time
    print(time_left)

Please understand that the above is largely pseudo-code


问:
Change text of button when pressing it ReactJS
I want to change the text of a button when I press it.

This is what I want to achieve: https://codepen.io/gaearon/pen/xEmzGg?editors=0010 , but I can't get my code to work (newbie).

```<code>class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false
    }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.setState(prevState => ({
      open: prevState.open
    }))
  }

  renderInner() {
      if (!this.props.value) return <td className = "inactive" > < /td>
      if (!this.state.open && this.props.schema.type === 'belongs_to')
      return <td onClick={(e) => this.setState({open: !this.state.open})}>
        <button onClick={this.handleCLick}>
          {this.state.open ? 'OFF' : 'ON'}
        </button>
      </td>
}
</code>```

Here's my code and as you might have seen I want to toggle the text OFF and ON when pressing the button. I can add more code if needed. Really grateful for all the support I can get.

答:
The bug is in handler:

```<code>this.setState(prevState => ({
  open: !prevState.open
}))
</code>```

You are setting it to the same value, as it was before.. with !bool you can switch the value

Additionally the condition is not making any sense:

```<code>  if (!this.state.open && this.props.schema.type === 'belongs_to')
  return <td onClick={(e) => this.setState({open: !this.state.open})}>
    <button onClick={this.handleCLick}>
      {this.state.open ? 'OFF' : 'ON'}
    </button>
  </td>
</code>```

This means only if the condition is met, you component will return something..

true === (!this.state.open && this.props.schema.type === 'belongs_to')

Body:
I want to change the text of a button when I press it.

This is what I want to achieve: https://codepen.io/gaearon/pen/xEmzGg?editors=0010 , but I can't get my code to work (newbie).

class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false
    }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.setState(prevState => ({
      open: prevState.open
    }))
  }

  renderInner() {
      if (!this.props.value) return
      if (!this.state.open && this.props.schema.type === 'belongs_to')
      return  this.setState({open: !this.state.open})}>
        <button onClick={this.handleCLick}>
          {this.state.open ? 'OFF' : 'ON'}
        </button>

}

Here's my code and as you might have seen I want to toggle the text OFF and ON when pressing the button. I can add more code if needed. Really grateful for all the support I can get.

Body:
The bug is in handler:

this.setState(prevState => ({
  open: !prevState.open
}))

You are setting it to the same value, as it was before.. with !bool you can switch the value

Additionally the condition is not making any sense:

  if (!this.state.open && this.props.schema.type === 'belongs_to')
  return <td onClick={(e) => this.setState({open: !this.state.open})}>
    <button onClick={this.handleCLick}>
      {this.state.open ? 'OFF' : 'ON'}
    </button>
  </td>

This means only if the condition is met, you component will return something..

true === (!this.state.open && this.props.schema.type === 'belongs_to')


问:
[Error: EACCES: permission denied, open '/home/ubuntu/.hfc-key-store/
I am getting following error while running composer rest server. I am using aws ubuntu 16.04 server.

Hyperledger Composer

? Enter your Fabric Connection Profile Name: hlfv1

? Enter your Business Network Identifier : digitalproperty-network

? Enter your Fabric username : admin

? Enter your secret: Xurw3yU9zI0l

? Specify if you want namespaces in the generated REST API: never use namespaces

? Specify if you want the generated REST API to be secured: No

To restart the REST server using the same options, issue the following command:
   composer-rest-server -p hlfv1 -n digitalproperty-network -i admin -s Xurw3yU9zI0l -N never

Discovering types from business network definition ...

Connection fails: Error: error trying login and get user Context.
  Error: error trying to enroll user. Error: Failed to generate key for
  enrollment due to error [Error: EACCES: permission denied, open
  '/home/ubuntu/.hfc-key-store/be8405cef82cc00455de296664ccdcb35e4c707bb0e63a00d0bef76546528e13-priv']
  It will be retried for the next request. Error: error trying login and
  get user Context. Error: error trying to enroll user. Error: Failed to
  generate key for enrollment due to error [Error: EACCES: permission
  denied, open
  '/home/ubuntu/.hfc-key-store/be8405cef82cc00455de296664ccdcb35e4c707bb0e63a00d0bef76546528e13-priv']
      at client.getUserContext.then.then.catch (/home/ubuntu/.nvm/versions/node/v6.11.0/lib/node_modules/composer-rest-server/node_modules/composer-connector-hlfv1/lib/hlfconnection.js:293:34)
  ubuntu@ip-172-31-19-220:~/composer-sample-networks/packages/digitalproperty-network$

答: when connecting to the running v1.0 Fabric dev environment using hlfv1 or running the REST server (as shown above) - you need to provide the default admin password of 'adminpw' - please try running composer-rest-server again and use the correct password. cheers Paul</p>


问:
Android - How to create multiple threads to run at background?
I am new to Android, but I ran into this problem...
I need an infinite loop to run some process in the background,
while another infinite loop to accept some socket connection,
and then when a button clicked, I need to make a socket connection to some server.

Almost all the example and tutorial I can find are showing how to create one single thread.

I have try to use runnable (this seems to run at foreground?)

```<code>Runnable r=new Runnable() {
  public void run()  {
    while(true){}
  }
}; r.run();
</code>```

and I have tried to use AsyncTask (this run at background, but only one AsyncTask per activity?)

```<code>private class Run extends AsyncTask<Void, Void, Void> {
  protected Void doInBackground(Void... params) {
  }
}
</code>```

but whatever I do, my program only execute the first thread.

My question would be, is it possible to have multi-thread running multi-infinite loop within one activity? If is, how?

答:
Sometimes you want to call up the UI thread from the background thread. You can do that like this:

```<code>        Thread t = new Thread(new Runnable() {
                public void run() {
                //Do your background thing here

                 getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            //Update your GUI here
                        }
                 });
         t.start();
</code>```

And getActivity looks like this:

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

                   private Activity getActivity(){
                        return this;
                   }
                  //Rest of class here
          }
</code>```

Body:
I am new to Android, but I ran into this problem...
I need an infinite loop to run some process in the background,
while another infinite loop to accept some socket connection,
and then when a button clicked, I need to make a socket connection to some server.

Almost all the example and tutorial I can find are showing how to create one single thread.

I have try to use runnable (this seems to run at foreground?)

Runnable r=new Runnable() {
  public void run()  {
    while(true){}
  }
}; r.run();

and I have tried to use AsyncTask (this run at background, but only one AsyncTask per activity?)

private class Run extends AsyncTask<Void, Void, Void> {
  protected Void doInBackground(Void... params) {
  }
}

but whatever I do, my program only execute the first thread.

My question would be, is it possible to have multi-thread running multi-infinite loop within one activity? If is, how?

Body:
Sometimes you want to call up the UI thread from the background thread. You can do that like this:

        Thread t = new Thread(new Runnable() {
                public void run() {
                //Do your background thing here

                 getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            //Update your GUI here
                        }
                 });
         t.start();

And getActivity looks like this:

          public class YourClass extends AppCompatActivity{

                   private Activity getActivity(){
                        return this;
                   }
                  //Rest of class here
          }


问:
How to graph grid scores from GridSearchCV?
I am looking for a way to graph grid_scores_ from GridSearchCV  in sklearn. In this example I am trying to grid search for best gamma and C parameters for an SVR algorithm. My code looks as follows:

```<code>    C_range = 10.0 ** np.arange(-4, 4)
    gamma_range = 10.0 ** np.arange(-4, 4)
    param_grid = dict(gamma=gamma_range.tolist(), C=C_range.tolist())
    grid = GridSearchCV(SVR(kernel='rbf', gamma=0.1),param_grid, cv=5)
    grid.fit(X_train,y_train)
    print(grid.grid_scores_)
</code>```

After I run the code and print the grid scores I get the following outcome:

```<code>[mean: -3.28593, std: 1.69134, params: {'gamma': 0.0001, 'C': 0.0001}, mean: -3.29370, std: 1.69346, params: {'gamma': 0.001, 'C': 0.0001}, mean: -3.28933, std: 1.69104, params: {'gamma': 0.01, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 0.1, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 1.0, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 10.0, 'C': 0.0001},etc]
</code>```

I would like to visualize all the scores (mean values) depending on gamma and C parameters. The graph I am trying to obtain should look as follows:

Where x-axis is gamma, y-axis is mean score (root mean square error in this case), and different lines represent different C values.

答:
I wanted to do something similar (but scalable to a large number of parameters) and here is my solution to generate swarm plots of the output:

```<code>score = pd.DataFrame(gs_clf.grid_scores_).sort_values(by='mean_validation_score', ascending = False)
for i in parameters.keys():
    print(i, len(parameters[i]), parameters[i])
score[i] = score.parameters.apply(lambda x: x[i])
l =['mean_validation_score'] + list(parameters.keys())
for i in list(parameters.keys()):
    sns.swarmplot(data = score[l], x = i, y = 'mean_validation_score')
    #plt.savefig('170705_sgd_optimisation//'+i+'.jpg', dpi = 100)
    plt.show()
</code>```

Body:
I am looking for a way to graph grid_scores_ from GridSearchCV  in sklearn. In this example I am trying to grid search for best gamma and C parameters for an SVR algorithm. My code looks as follows:

    C_range = 10.0 ** np.arange(-4, 4)
    gamma_range = 10.0 ** np.arange(-4, 4)
    param_grid = dict(gamma=gamma_range.tolist(), C=C_range.tolist())
    grid = GridSearchCV(SVR(kernel='rbf', gamma=0.1),param_grid, cv=5)
    grid.fit(X_train,y_train)
    print(grid.grid_scores_)

After I run the code and print the grid scores I get the following outcome:

[mean: -3.28593, std: 1.69134, params: {'gamma': 0.0001, 'C': 0.0001}, mean: -3.29370, std: 1.69346, params: {'gamma': 0.001, 'C': 0.0001}, mean: -3.28933, std: 1.69104, params: {'gamma': 0.01, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 0.1, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 1.0, 'C': 0.0001}, mean: -3.28925, std: 1.69106, params: {'gamma': 10.0, 'C': 0.0001},etc]

I would like to visualize all the scores (mean values) depending on gamma and C parameters. The graph I am trying to obtain should look as follows:

Where x-axis is gamma, y-axis is mean score (root mean square error in this case), and different lines represent different C values.

Body:
I wanted to do something similar (but scalable to a large number of parameters) and here is my solution to generate swarm plots of the output:

score = pd.DataFrame(gs_clf.grid_scores_).sort_values(by='mean_validation_score', ascending = False)
for i in parameters.keys():
    print(i, len(parameters[i]), parameters[i])
score[i] = score.parameters.apply(lambda x: x[i])
l =['mean_validation_score'] + list(parameters.keys())
for i in list(parameters.keys()):
    sns.swarmplot(data = score[l], x = i, y = 'mean_validation_score')
    #plt.savefig('170705_sgd_optimisation//'+i+'.jpg', dpi = 100)
    plt.show()


问:
Upload image in Flask
I have to upload some images in static folder of my project directory, but i don't know how to say it to my code. In the follow code.py i'm able to upload an image and store it in the project directory at the same level of static folder, but i would that this image can be store INSIDE static folder.

```<code>@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']

      f.save(secure_filename(f.filename))
      return render_template('end.html')
</code>```

What i have to do?? Thanks guys

答:
you need to define the upload folder

from the flask documentation

```<code>import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
</code>```

https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

So your code would be UPLOAD_FOLDER = '/path/to/static/images' or something like that

Title: Upload image in Flask

Body:
I have to upload some images in static folder of my project directory, but i don't know how to say it to my code. In the follow code.py i'm able to upload an image and store it in the project directory at the same level of static folder, but i would that this image can be store INSIDE static folder.

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']

      f.save(secure_filename(f.filename))
      return render_template('end.html')

What i have to do?? Thanks guys

Body:
you need to define the upload folder

from the flask documentation

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

So your code would be UPLOAD_FOLDER = '/path/to/static/images' or something like that

ContentLicense: CC BY-SA 4.0


问:
"type mismatch" trying to hide rows using vba
What I want to do is hide rows so my interface is lighter but I get the following error message when I i compile my code:

Type mismatch (Error 13)

```<code>Public Function keepAdditionalRowsHidden()

Dim startRow As Long
Dim lastrow As Long

Dim startRowString As String
Dim endRowString As String

startRow = 40
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row

startRowString = CStr(startRow)
endRowString = CStr(lastrow)

ActiveSheet.Rows("startRow:endRow").EntireRow.Hidden = True

End Function
</code>```

答:
I see one issue right off the bat.  When you are doing your ActiveSheet.Rows("startRow:endRow").EntireRow.Hidden = True you are not calling those variables, you are stating them as strings.

Try this instead:

ActiveSheet.Rows(startrow & ":" & endrow).EntireRow.Hidden = True

This way, you are properly calling the variables, and the only "string" is the : (colon).

Also, next time you ask please make sure you explain if you are receiving an error, or just not achieving the results you desire.  I am guessing you are getting a type mismatch error with this, but I cannot be sure.  This helps everyone better assist you.

Body:
What I want to do is hide rows so my interface is lighter but I get the following error message when I i compile my code:

Type mismatch (Error 13)

Public Function keepAdditionalRowsHidden()

Dim startRow As Long
Dim lastrow As Long

Dim startRowString As String
Dim endRowString As String

startRow = 40
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row

startRowString = CStr(startRow)
endRowString = CStr(lastrow)

ActiveSheet.Rows("startRow:endRow").EntireRow.Hidden = True

End Function


问:
Search for string within a List with Dictionaries
-- EDIT:

Okay thanks to you guys, and especially randomir I adjusted the loop as follows:

```<code>while buy_active > 0 or balance_available > 0 or i <= 0:
        print('Selling {0} {1} for {2:.8f} {3}. Volume: {4} It {5}'.format(balance_available, currency, coinprice_sell, trade, coinvolume, i))
        api.selllimit(market, balance_available, coinprice_sell)

        open_order = api.getopenorders(market)
        buy_active = len(list(filter(partial(eq, "LIMIT_BUY"),
                                map(itemgetter("OrderType"), open_order)))) > 0

        coinbalance = api.getbalance(currency)
        balance_available = coinbalance['Available']  # You still have some coins available
        coinsummary = api.getmarketsummary(market)
        coinprice = coinsummary[0]['Last']
        coinvolume = coinsummary[0]['Volume'] * coinprice
        i += 1
else:
        print('No open Buy order or remaining quantity')
</code>```

Now this codes runs almost all the time perfectly but once in a while I receive an error (which I do not know how to replicate, since it probably depends on what the API transmits to the program.

The error says:

```<code>Traceback (most recent call last):
  File "test.py", line 76, in <module>
    while buy_active > 0 or balance_available > 0 or i <= 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'
</code>```

So I interpret the error that sometimes the variable buy_active has no type and hence cannot be interpreted with ">". However, I do not see how this can happen. It probably has something to do with the len(list(filter(... approach. I also tried to define buy_active = 1 so it enters the loop at least once. But this does not solve the problem. Hence I guess this operator sometimes deliveres a NoneType character.

Does anybody has a suggestion what the problem could be?

Best
SaltyJ

Original:

I just started programming in python 2.7 (for this particular code I would like to stay on 2.7) where I encountered a problem. Since I am very new to programming, I cannot figure out how to solve my problem. I hope you can help.

I want to handle some input from an API about my open orders at an online exchange.

Over the API I receive a list with nested dictionnaries. One Example (for 2 orders is below).

```<code>{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            "Quantity" : 5.00000000,
            "QuantityRemaining" : 5.00000000,
            "Limit" : 2.00000000,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.77",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }, {
            "Uuid" : null,
            "OrderUuid" : "8925d746-bc9f-4684-b1aa-e507467aaa99",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_BUY",
            "Quantity" : 100000.00000000,
            "QuantityRemaining" : 100000.00000000,
            "Limit" : 0.00000001,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.583",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }
    ]
}
</code>```

The API produces a list with one dictionnary for every open order.

Now I want to basically make my code go through all dic. looking for the string "LIMIT_BUY".

My current code does this for up to 2 orders. But it is probably highly inefficient and also cannot cope with orders > 2:

At the end of the loop the buy_active variable should  be "1" if there is any buy order or 0 if there is no order or only selling orders.

```<code>if len(open_order) == 2:
            order_type_1 = open_order[0]['OrderType']
            order_type_2 = open_order[1]['OrderType']
            if order_type_1 == 'LIMIT_BUY' or order_type_2 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0

        elif len(open_order) == 1:
            order_type_1 = open_order[0]['OrderType']
            if order_type_1 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0
        else:
            buy_active = 0
</code>```

What I would like is a most efficient (in terms of time) code to look through the list with any number of entries.

Can somebody help me?:)

Thanks alot! I just started coding 4 days ago, so please be nice :)

Best
SaltyJ

答:
You could use any() function and list comprehension (to filter the list).
The list comprehension, creates a new list of True values, when  "OrderType" equals "LIMIT_SELL".</p>

```<code>import json
data = json.loads("""{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            ....
""")

buy_active = any([True for item in data['result'] if item['OrderType'] == 'LIMIT_BUY' ])
</code>```

Body:
-- EDIT:

Okay thanks to you guys, and especially randomir I adjusted the loop as follows:

while buy_active > 0 or balance_available > 0 or i <= 0:
        print('Selling {0} {1} for {2:.8f} {3}. Volume: {4} It {5}'.format(balance_available, currency, coinprice_sell, trade, coinvolume, i))
        api.selllimit(market, balance_available, coinprice_sell)

        open_order = api.getopenorders(market)
        buy_active = len(list(filter(partial(eq, "LIMIT_BUY"),
                                map(itemgetter("OrderType"), open_order)))) > 0

        coinbalance = api.getbalance(currency)
        balance_available = coinbalance['Available']  # You still have some coins available
        coinsummary = api.getmarketsummary(market)
        coinprice = coinsummary[0]['Last']
        coinvolume = coinsummary[0]['Volume'] * coinprice
        i += 1
else:
        print('No open Buy order or remaining quantity')

Now this codes runs almost all the time perfectly but once in a while I receive an error (which I do not know how to replicate, since it probably depends on what the API transmits to the program.

The error says:

Traceback (most recent call last):
  File "test.py", line 76, in <module>
    while buy_active > 0 or balance_available > 0 or i <= 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

So I interpret the error that sometimes the variable buy_active has no type and hence cannot be interpreted with ">". However, I do not see how this can happen. It probably has something to do with the len(list(filter(... approach. I also tried to define buy_active = 1 so it enters the loop at least once. But this does not solve the problem. Hence I guess this operator sometimes deliveres a NoneType character.

Does anybody has a suggestion what the problem could be?

Best
SaltyJ

Original:

I just started programming in python 2.7 (for this particular code I would like to stay on 2.7) where I encountered a problem. Since I am very new to programming, I cannot figure out how to solve my problem. I hope you can help.

I want to handle some input from an API about my open orders at an online exchange.

Over the API I receive a list with nested dictionnaries. One Example (for 2 orders is below).

{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            "Quantity" : 5.00000000,
            "QuantityRemaining" : 5.00000000,
            "Limit" : 2.00000000,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.77",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }, {
            "Uuid" : null,
            "OrderUuid" : "8925d746-bc9f-4684-b1aa-e507467aaa99",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_BUY",
            "Quantity" : 100000.00000000,
            "QuantityRemaining" : 100000.00000000,
            "Limit" : 0.00000001,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.583",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }
    ]
}

The API produces a list with one dictionnary for every open order.

Now I want to basically make my code go through all dic. looking for the string "LIMIT_BUY".

My current code does this for up to 2 orders. But it is probably highly inefficient and also cannot cope with orders > 2:

At the end of the loop the buy_active variable should  be "1" if there is any buy order or 0 if there is no order or only selling orders.

if len(open_order) == 2:
            order_type_1 = open_order[0]['OrderType']
            order_type_2 = open_order[1]['OrderType']
            if order_type_1 == 'LIMIT_BUY' or order_type_2 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0

        elif len(open_order) == 1:
            order_type_1 = open_order[0]['OrderType']
            if order_type_1 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0
        else:
            buy_active = 0

What I would like is a most efficient (in terms of time) code to look through the list with any number of entries.

Can somebody help me?:)

Thanks alot! I just started coding 4 days ago, so please be nice :)

Best
SaltyJ

Body:
You could use any() function and list comprehension (to filter the list).
The list comprehension, creates a new list of True values, when  "OrderType" equals "LIMIT_SELL".

import json
data = json.loads("""{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            ....
""")

buy_active = any([True for item in data['result'] if item['OrderType'] == 'LIMIT_BUY' ])


问:
How to get a rotated linear gradient svg for use as a background image?
I've seen a few questions dancing around this, so I hope this isn't too redundant. Ideally, I'd like an image/svg+xml which scales to 100% of it's container.
Colorzilla gets me a great start with a data:image/svg+xml

```<code><?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">
  <linearGradient id="grad-ucgg-generated" gradientUnits="userSpaceOnUse" x1="0%" y1="0%" x2="100%" y2="0%">
    <stop offset="0%" stop-color="#ffffff" stop-opacity="0"/>
    <stop offset="100%" stop-color="#ff0000" stop-opacity="1"/>
  </linearGradient>
  <rect x="0" y="0" width="1" height="1" fill="url(#grad-ucgg-generated)" />
</svg>
</code>```

Note: the width="100%" height="100%" I'd like to take this gradient and rotate it by, say 65deg
The HTML5 canvas API provides a great way for me to build this image and then use .toDataURL() PNG to polyfill IE8 and IE7, but I'd like something scalable for IE9.

So the goal is to replicate this:

```<code>background: linear-gradient(bottom, rgba(239, 239, 214,0) 0%, rgba(239, 239, 214,.8) 100%),
linear-gradient(left,  rgba(239, 239, 214,0) 60%,rgba(207, 223, 144,1) 100%),
linear-gradient(right, rgba(239, 239, 214,0) 0%,rgba(239, 239, 214,1) 60%),
linear-gradient(top, rgba(239, 239, 214,0) 60%,#cfdf90 100%);
}
</code>```

with an image/svg+xml that's 100% width and height.

I did try out http://svg-edit.googlecode.com but the interface was less than intuitive for the types of editing I wanted to do.
Thanks!

Body:
I've seen a few questions dancing around this, so I hope this isn't too redundant. Ideally, I'd like an image/svg+xml which scales to 100% of it's container.
Colorzilla gets me a great start with a data:image/svg+xml

<?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">
  <linearGradient id="grad-ucgg-generated" gradientUnits="userSpaceOnUse" x1="0%" y1="0%" x2="100%" y2="0%">
    <stop offset="0%" stop-color="#ffffff" stop-opacity="0"/>
    <stop offset="100%" stop-color="#ff0000" stop-opacity="1"/>
  </linearGradient>
  <rect x="0" y="0" width="1" height="1" fill="url(#grad-ucgg-generated)" />
</svg>

Note: the width="100%" height="100%" I'd like to take this gradient and rotate it by, say 65deg
The HTML5 canvas API provides a great way for me to build this image and then use .toDataURL() PNG to polyfill IE8 and IE7, but I'd like something scalable for IE9.

So the goal is to replicate this:

background: linear-gradient(bottom, rgba(239, 239, 214,0) 0%, rgba(239, 239, 214,.8) 100%),
linear-gradient(left,  rgba(239, 239, 214,0) 60%,rgba(207, 223, 144,1) 100%),
linear-gradient(right, rgba(239, 239, 214,0) 0%,rgba(239, 239, 214,1) 60%),
linear-gradient(top, rgba(239, 239, 214,0) 60%,#cfdf90 100%);
}

with an image/svg+xml that's 100% width and height.

I did try out http://svg-edit.googlecode.com but the interface was less than intuitive for the types of editing I wanted to do.
Thanks!

Body: <linearGradient gradientTransform="rotate(65)">


问:
How do I delay an animation using my character movement script?
Below is a copy of my player movement script which contains functions to animate my character moving left and right, jumping and shooting his bow. I have also been able to get my character to transition from shooting his bow to being in an alert animation, but I am wondering how to write the code so that for 5 seconds after I shoot my bow I will be alert before going back to my default "idle" animation.

I would also like my character to be able to walk around (i.e. transition the alert animation to the walk animation) while being alert, but if he stops moving he goes back to alert. Currently my character will go back to idle if he walks during his alert stance. The script below, specifically lines 98-102 (my "playerAlert" function) present another problem in that my character cannot perform his "shoot" animation after this function has occurred, but I do not know/can't wrap my head around how to code what I mentioned above.

I am using Unity 5.6.

I appreciate any help you guys may be able to give me.

```<code>     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;

     public class player_1_controller : MonoBehaviour {

         Rigidbody2D myRB;
         Animator myAnim;
         bool facingRight;

         //movement variables
         public float maxSpeed;

         //jumping variables
         bool grounded = false;
         float groundCheckRadius = 0.2f;
         public LayerMask groundLayer;
         public Transform groundCheck;
         public float jumpHeight;

         //arrow shooting variables
         bool firing = true;
         public float arrowShoot;
         public Transform arrowTip;
         public GameObject arrow;
         public float fireRate = 0.5f;
         public float nextFire = 0f;

         // Use this for initialization
         void Start () {

             myRB = GetComponent<Rigidbody2D> ();
             myAnim = GetComponent<Animator> ();
             facingRight = true;
             }

         // Update is called once per frame
         void Update () {

             //player jump
             if (grounded && Input.GetButtonDown ("Jump")) {
                 grounded = false;
                 myAnim.SetBool ("isGrounded", grounded);
                 myRB.AddForce (new Vector2 (0, jumpHeight));
             }

             //player shooting
             if (grounded && Input.GetButtonDown ("Fire1")) {
                 myAnim.SetBool ("arrowShoot", firing);
                 Invoke ("fireArrow", 1);
             }

         }

             void FixedUpdate() {

             //player movement
             float move = Input.GetAxis ("Horizontal");
             myAnim.SetFloat ("speed", Mathf.Abs (move));

             myRB.velocity = new Vector2 (move * maxSpeed, myRB.velocity.y);

             if (move > 0 && !facingRight) {
                 flip ();
             } else if (move < 0 && facingRight) {
                 flip ();
             }

             //player jump; check if we are grounded - if not, then we are falling
             grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
             myAnim.SetBool ("isGrounded", grounded);

             myAnim.SetFloat ("verticalSpeed", myRB.velocity.y);
         }

             void flip () {
             facingRight = !facingRight;
             Vector3 theScale = transform.localScale;
             theScale.x *= -1;
             transform.localScale = theScale;

         }

         void fireArrow() {

             if (Time.time > nextFire) {
                 nextFire = Time.time + fireRate;
                 if (facingRight) {
                     Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 0)));
                 } else if (!facingRight) {
                     Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 180)));
                 }
             }
             playerAlert ();

           }

         void playerAlert () {

                 firing = false;
                 myAnim.SetBool ("arrowShoot", firing);
         }
     }
</code>```

答:
Invoke can help you here. excerpt:

```<code>void Start()
{
    Invoke("LaunchProjectile", 2);
}

void LaunchProjectile()
{
    Rigidbody instance = Instantiate(projectile);
    instance.velocity = Random.insideUnitSphere * 5;
}
</code>```

You can use that to call(invoke) the "back to idle" function after 5 seconds.

Body:
Below is a copy of my player movement script which contains functions to animate my character moving left and right, jumping and shooting his bow. I have also been able to get my character to transition from shooting his bow to being in an alert animation, but I am wondering how to write the code so that for 5 seconds after I shoot my bow I will be alert before going back to my default "idle" animation.

I would also like my character to be able to walk around (i.e. transition the alert animation to the walk animation) while being alert, but if he stops moving he goes back to alert. Currently my character will go back to idle if he walks during his alert stance. The script below, specifically lines 98-102 (my "playerAlert" function) present another problem in that my character cannot perform his "shoot" animation after this function has occurred, but I do not know/can't wrap my head around how to code what I mentioned above.

I am using Unity 5.6.

I appreciate any help you guys may be able to give me.

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;

     public class player_1_controller : MonoBehaviour {

         Rigidbody2D myRB;
         Animator myAnim;
         bool facingRight;

         //movement variables
         public float maxSpeed;

         //jumping variables
         bool grounded = false;
         float groundCheckRadius = 0.2f;
         public LayerMask groundLayer;
         public Transform groundCheck;
         public float jumpHeight;

         //arrow shooting variables
         bool firing = true;
         public float arrowShoot;
         public Transform arrowTip;
         public GameObject arrow;
         public float fireRate = 0.5f;
         public float nextFire = 0f;

         // Use this for initialization
         void Start () {

             myRB = GetComponent<Rigidbody2D> ();
             myAnim = GetComponent<Animator> ();
             facingRight = true;
             }

         // Update is called once per frame
         void Update () {

             //player jump
             if (grounded && Input.GetButtonDown ("Jump")) {
                 grounded = false;
                 myAnim.SetBool ("isGrounded", grounded);
                 myRB.AddForce (new Vector2 (0, jumpHeight));
             }

             //player shooting
             if (grounded && Input.GetButtonDown ("Fire1")) {
                 myAnim.SetBool ("arrowShoot", firing);
                 Invoke ("fireArrow", 1);
             }

         }

             void FixedUpdate() {

             //player movement
             float move = Input.GetAxis ("Horizontal");
             myAnim.SetFloat ("speed", Mathf.Abs (move));

             myRB.velocity = new Vector2 (move * maxSpeed, myRB.velocity.y);

             if (move > 0 && !facingRight) {
                 flip ();
             } else if (move < 0 && facingRight) {
                 flip ();
             }

             //player jump; check if we are grounded - if not, then we are falling
             grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);
             myAnim.SetBool ("isGrounded", grounded);

             myAnim.SetFloat ("verticalSpeed", myRB.velocity.y);
         }

             void flip () {
             facingRight = !facingRight;
             Vector3 theScale = transform.localScale;
             theScale.x *= -1;
             transform.localScale = theScale;

         }

         void fireArrow() {

             if (Time.time > nextFire) {
                 nextFire = Time.time + fireRate;
                 if (facingRight) {
                     Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 0)));
                 } else if (!facingRight) {
                     Instantiate (arrow, arrowTip.position, Quaternion.Euler (new Vector3 (0, 0, 180)));
                 }
             }
             playerAlert ();

           }

         void playerAlert () {

                 firing = false;
                 myAnim.SetBool ("arrowShoot", firing);
         }
     }

Body:
Invoke can help you here. excerpt:

void Start()
{
    Invoke("LaunchProjectile", 2);
}

void LaunchProjectile()
{
    Rigidbody instance = Instantiate(projectile);
    instance.velocity = Random.insideUnitSphere * 5;
}

You can use that to call(invoke) the "back to idle" function after 5 seconds.


问:
Responsive html layout height 100% is not according to parent div
I'm really new in html

This is my code

```<code><div class="w3-row">
    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>VISION</b></br></br>
        To become the best foundation that is able to nurture holistic global leaders</p>
    </div>

    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>MISSION</b></br></br>
        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values</p>
    </div>
</div>
</code>```

So I have 2 column in a row. This is what happened

my first column leaves empty white space below it

Is there any way to have both my columns to extend to 100% parent div's height?

答:
Use flex

.w3-row{
display: flex;
align-items: center;
}

.w3-container {
flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="w3-row">
    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>VISION</b></br></br>
        To become the best foundation that is able to nurture holistic global leaders</p>
    </div>

    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>MISSION</b></br></br>
        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values</p>
    </div>
</div></code>```

Body:
I'm really new in html

This is my code

 OUR VISION

        To become the best foundation that is able to nurture holistic global leaders

 OUR MISSION

        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values

So I have 2 column in a row. This is what happened

my first column leaves empty white space below it

Is there any way to have both my columns to extend to 100% parent div's height?

Body:
Use flex

.w3-row{
display: flex;
align-items: center;
}

.w3-container {
flex: 1;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="w3-row">
    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>VISION</b></br></br>
        To become the best foundation that is able to nurture holistic global leaders</p>
    </div>

    <div class="w3-container w3-half w3-padding-64 w3-orange w3-text-white w3-center" style="height:100%">
        <p style="font-size:calc(11px + 1vw);"> OUR <b>MISSION</b></br></br>
        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values</p>
    </div>
</div>


问:
Run background-job every hour for n number of times(ruby on rails)
I am using resque for job scheduling. I want to run a job every 1 hour and for N times only.
I also want to pass count in the job as argument

for example:

```<code>i=0
50.times do
   every 1.hour, roles: [:whenever_cron] do
     runner "Resque.enqueue(SomeJob, i+1)"
   end
end
</code>```

How can I do this?

Note : - I don't want to run 50 jobs every hour. I want to run 1 job 50 times

答:
Scheduling syntax is for recurring jobs. Those that happen over and over again, until the end of times.

For single-shot jobs, you enqueue them, with an optional delay (which is what you need here). So you can just enqueue the whole batch of your jobs all at once, with 1 hour increments:

```<code>1.upto(50).each do |x|
  Resque.enqueue_in(x.hours, SomeJob)
end
</code>```

Body:
I am using resque for job scheduling. I want to run a job every 1 hour and for N times only.
I also want to pass count in the job as argument

for example:

i=0
50.times do
   every 1.hour, roles: [:whenever_cron] do
     runner "Resque.enqueue(SomeJob, i+1)"
   end
end

How can I do this?

Note : - I don't want to run 50 jobs every hour. I want to run 1 job 50 times

Body:
Scheduling syntax is for recurring jobs. Those that happen over and over again, until the end of times.

For single-shot jobs, you enqueue them, with an optional delay (which is what you need here). So you can just enqueue the whole batch of your jobs all at once, with 1 hour increments:

1.upto(50).each do |x|
  Resque.enqueue_in(x.hours, SomeJob)
end


问:
How can i get dynamic form field values in angular?
Below i have added dynamic form add and delete after submit i want to get all the form values .how can i do this ?? anyone help me out move forward

this is my jsfiddle link

http://jsfiddle.net/rnnb32rm/1438/

below i added my cod

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}];

  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };
  $scope.OnSave = function() {
    console.log('sjs');
  };

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;
}
input[type="text"],
select{
    padding:5px;
}</code>```

   <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />

    <button class="addfields" ng-click="addNewChoice()">Add fields</button>

    name
    <input type="text" ng-model="name" name="" placeholder="Add name">

    email
    <input type="text" ng-model="email" name="" placeholder="Add emalil">

    <fieldset data-ng-repeat="choice in choices">

        Add Question

        <input type="text" ng-model="choice.name" name="" placeholder="Add Question">

        Question order
        <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

        <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
    </fieldset>

    <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>

        {{ choices }}

```
</div>
</div>
</p>

<p>my expected result :</p>

```{

    "name": "test",
    "email": "asdf@gmail.com",
    "questions": [
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "1",

        },
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "2",

        }
    ]
}
```

答:
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
  $scope.obj = {
     name: '',
     email: '',
    questions: []
 };

 var emptyObj = {
    question: "",
    questionorder: "",
    options: []
  };

  var emptyOption = {
      val: "",
      key: ""
  };

  $scope.addNewChoice = function() {
     $scope.obj.questions.push(angular.copy(emptyObj));
  };

  $scope.removeChoice = function(index) {
     $scope.obj.questions.splice(index, 1);
  };

  $scope.addOptions = function(index) {
     if($scope.obj.questions[index].options.length == 6){
       alert('maximum 6 options are allowed');
        return;
     }
     $scope.obj.questions[index].options.push(angular.copy(emptyOption));
  };

  $scope.removeOption = function(parentIdx, index) {
     $scope.obj.questions[parentIdx].options.splice(index, 1);
  };

  $scope.OnSave = function() {
    console.log('sjs');
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;
}
input[type="text"],
select{
    padding:5px;
}</code>```

   <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />

   <button class="addfields" ng-click="addNewChoice()">Add fields</button>

   name
   <input type="text" ng-model="obj.name" name="" placeholder="Add name">

   email
   <input type="text" ng-model="obj.email" name="" placeholder="Add emalil">

<fieldset  data-ng-repeat="choice in obj.questions">
  Add Question
  <input type="text" ng-model="choice.question" name="" placeholder="Add Question">

  <button type="button" ng-click="addOptions($index)">
  Add options
  </button>

  Question order
  <input type="text" ng-model="choice.questionorder" name="" placeholder="Add Question order">

  <button class="remove" ng-show="$last" ng-click="removeChoice($index)">-</button>

      <input type="text" name="val" placeholder="val" ng-model="opt.val">
      <input type="text" name="key"  placeholder="key" ng-model="opt.key">
      <button class="remove" ng-click="removeOption($parent.$index, $index)">-</button>

</fieldset>

 <button type="submit" class="btn btn-primary"  ng-
 click="OnSave()">Submit</button>

   {{obj | json}}

```

Body:
Below i have added dynamic form add and delete after submit i want to get all the form values .how can i do this ?? anyone help me out move forward

this is my jsfiddle link

http://jsfiddle.net/rnnb32rm/1438/

below i added my cod

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}];

  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };
  $scope.OnSave = function() {
    console.log('sjs');
  };

});

fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;
}
input[type="text"],
select{
    padding:5px;
}

   <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />

    <button class="addfields" ng-click="addNewChoice()">Add fields</button>

    name
    <input type="text" ng-model="name" name="" placeholder="Add name">

    email
    <input type="text" ng-model="email" name="" placeholder="Add emalil">

    <fieldset data-ng-repeat="choice in choices">

        Add Question

        <input type="text" ng-model="choice.name" name="" placeholder="Add Question">

        Question order
        <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

        <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
    </fieldset>

    <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>

        {{ choices }}

my expected result :

{

    "name": "test",
    "email": "asdf@gmail.com",
    "questions": [
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "1",

        },
        {
            "question": "Which of the following is the most important characteristic for a supervisor?",
            "questionorder": "2",

        }
    ]
}

Body:
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
  $scope.obj = {
     name: '',
     email: '',
    questions: []
 };

 var emptyObj = {
    question: "",
    questionorder: "",
    options: []
  };

  var emptyOption = {
      val: "",
      key: ""
  };

  $scope.addNewChoice = function() {
     $scope.obj.questions.push(angular.copy(emptyObj));
  };

  $scope.removeChoice = function(index) {
     $scope.obj.questions.splice(index, 1);
  };

  $scope.addOptions = function(index) {
     if($scope.obj.questions[index].options.length == 6){
       alert('maximum 6 options are allowed');
        return;
     }
     $scope.obj.questions[index].options.push(angular.copy(emptyOption));
  };

  $scope.removeOption = function(parentIdx, index) {
     $scope.obj.questions[parentIdx].options.splice(index, 1);
  };

  $scope.OnSave = function() {
    console.log('sjs');
  };
});

fieldset{
    background: #FCFCFC;
    padding: 16px;
    border: 1px solid #D5D5D5;
}
.addfields{
    margin: 10px 0;
}

#choicesDisplay {
    padding: 10px;
    background: rgb(227, 250, 227);
    border: 1px solid rgb(171, 239, 171);
    color: rgb(9, 56, 9);
}
.remove{
    background: #C76868;
    color: #FFF;
    font-weight: bold;
    font-size: 21px;
    border: 0;
    cursor: pointer;
    display: inline-block;
    padding: 4px 9px;
    vertical-align: top;
    line-height: 100%;
}
input[type="text"],
select{
    padding:5px;
}

   <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
   <button class="addfields" ng-click="addNewChoice()">Add fields</button><br>

   <label class="control-label col-sm-2">name</label>
   <input type="text" ng-model="obj.name" name="" placeholder="Add name">

   <label class="control-label col-sm-2">email</label>
   <input type="text" ng-model="obj.email" name="" placeholder="Add emalil"><br><br>

<fieldset  data-ng-repeat="choice in obj.questions">
  <label class="control-label col-sm-2">Add Question</label>
  <input type="text" ng-model="choice.question" name="" placeholder="Add Question">

  <button type="button" ng-click="addOptions($index)">
  Add options
  </button>
  <br><br>

  <label class="control-label col-sm-2">Question order</label>
  <input type="text" ng-model="choice.questionorder" name="" placeholder="Add Question order">

  <button class="remove" ng-show="$last" ng-click="removeChoice($index)">-</button>
  <br>
  <div ng-repeat="opt in choice.options track by $index">
      <input type="text" name="val" placeholder="val" ng-model="opt.val">
      <input type="text" name="key"  placeholder="key" ng-model="opt.key">
      <button class="remove" ng-click="removeOption($parent.$index, $index)">-</button>
  </div>
</fieldset><br><br>

 <button type="submit" class="btn btn-primary"  ng-
 click="OnSave()">Submit</button><br><br><br>

<div id="choicesDisplay">
   {{obj | json}}
</div>
  </div>


问:
How to get an object's methods?
Is there a method or propertie to get all methods from an object? For example:

```<code>function foo() {}
foo.prototype.a = function() {}
foo.prototype.b = function() {}

foo.get_methods(); // returns ['a', 'b'];
</code>```

UPDATE: Are there any method like that in Jquery?

Thank you.

答:
The methods can be inspected in the prototype chain of the object using the browser's developer tools (F12):

```<code>  console.log(yourJSObject);
</code>```

or more directly

```<code>  console.dir(yourJSObject.__proto__);
</code>```

Title: How to get an object's methods?

Body:
Is there a method or propertie to get all methods from an object? For example:

function foo() {}
foo.prototype.a = function() {}
foo.prototype.b = function() {}

foo.get_methods(); // returns ['a', 'b'];

UPDATE: Are there any method like that in Jquery?

Thank you.

Body:
The methods can be inspected in the prototype chain of the object using the browser's developer tools (F12):

  console.log(yourJSObject);

or more directly

  console.dir(yourJSObject.__proto__);


问:
Performance for appending large element/datasets to the dom
I am appending large amounts of table row elements at a time and experiencing some major bottlenecks.  At the moment I am using jQuery, but i'm open to a javascript based solution if it gets the job done.

I have the need to append anywhere from 0-100 table rows at a given time (it's actually potentially more, but I'll be paginating anything over 100).

Right now I am appending each table row individually to the dom...

```<code>loop {
  ..build html str...
  $("#myTable").append(row);
}
</code>```

Then I fade them all in at once

```<code>$("#myTable tr").fadeIn();
</code>```

There are a couple things to consider here...

1) I am binding data to each individual table row, which is why i switched from a mass append to appending individual rows in the first place.

2) I really like the fade effect.  Although not essential to the application I am very big on aesthetics and animations (that of course don't distract from the use of the application).  There simply has to be a good way to apply a modest fade effect to larger amounts of data.

(edit)
3) A major reason for me approaching this in the smaller chunk/recursive way is I need to bind specific data to each row.  Am I binding my data wrong? Is there a better way to keep track of this data than binding it to their respective tr?

Is it better to apply affects/dom manipulations in large chunks or smaller chunks in recursive functions?

Are there situations where the it's better to do one or the other? If so, what are the indicators for choosing the appropriate method?

答:
Take a look at this post by John Resig, it explains the benefit of using DocumentFragments when doing large additions to the DOM.

A DocumentFragment is a container that you can add nodes to without actually altering the DOM in any way. When you are ready you add the entire fragment to the DOM and this places it's content into the DOM in a single operation.

Also, doing $("#myTable") on each iteration is really not recommended - do it once before the loop.

Body:
I am appending large amounts of table row elements at a time and experiencing some major bottlenecks.  At the moment I am using jQuery, but i'm open to a javascript based solution if it gets the job done.

I have the need to append anywhere from 0-100 table rows at a given time (it's actually potentially more, but I'll be paginating anything over 100).

Right now I am appending each table row individually to the dom...

loop {
  ..build html str...
  $("#myTable").append(row);
}

Then I fade them all in at once

$("#myTable tr").fadeIn();

There are a couple things to consider here...

1) I am binding data to each individual table row, which is why i switched from a mass append to appending individual rows in the first place.

2) I really like the fade effect.  Although not essential to the application I am very big on aesthetics and animations (that of course don't distract from the use of the application).  There simply has to be a good way to apply a modest fade effect to larger amounts of data.

(edit)
3) A major reason for me approaching this in the smaller chunk/recursive way is I need to bind specific data to each row.  Am I binding my data wrong? Is there a better way to keep track of this data than binding it to their respective tr?

Is it better to apply affects/dom manipulations in large chunks or smaller chunks in recursive functions?

Are there situations where the it's better to do one or the other? If so, what are the indicators for choosing the appropriate method?


问:
Is there anyway i can give id to each recycler view which i created dynamically?
I have a integer counter which sets the number of recycler view to be created. Is there a way i can associate an id with each of the recycler view created?</p>

答:
If by “id” you refer to a simple indexing of your items than you can use ParrentView.getChildAt(i), where ParrentView is a container for your RecyclerViews.

If you need R.id for the specific member of your RecyclerViews than you can target that element by calling .findViewById() on View child.


问:
Replace shell environment variables in a string with actual values
I am reading a property file in Java.

```<code>Properties myProp = new Properties();
InputStream in = new FileInputStream(pathOfPropertyFile);
myProp.load(in);
in.close();
</code>```

The values in the property file have references to Linux shell variables.
For example, an entry in the property file might look like:

```<code>DATA_PATH=/data/${PROJECT}/${YEAR}${MONTH}${DAY}
</code>```

I have to execute a shell script from java and so I have ProcessBuilder instance and also the environment variables (envMap as given below):

```<code>List<String> command = new ArrayList<String>();
command.add(actualCommand);
command.add(param1);
command.add(param2);
ProcessBuilder processBuilder = new ProcessBuilder(command);
Map<String, String> envMap = processBuilder.environment();
</code>```

The envMap has the environment variables I require  along with over one hundred (> 100) other environment variables which I do not require.

I want to replace the ${USER},${PROJECT},etc., from the property-value string "/home/${USER}/${PROJECT}/data" with actual values from the shell.

I would consider iterating the Map as the last option(as the Map has between 100 and 200 elements to iterate) as it is not an efficient approach.

Please advise some approach that will fetch the environment variable enclosed by braces from the string, so that I can directly use the get() of the Map and replace. Or, any better approaches are most welcome.

Note:  The reference offered ( Replace String values with value in Hash Map  that made my question to look duplicate) is not the best fit in my case.

答:
If you are open to using an external library, StrSubstitutor from apache-commons will do exactly what you want:

```<code>public static void main(String[] args) {
    String input = "DATA_PATH=/data/${PROJECT}/${YEAR}${MONTH}${DAY}";
    Map<String, String> env = new HashMap<>();
    env.put("PROJECT", "myProject");
    env.put("YEAR", "2017");
    env.put("MONTH", "7");
    env.put("DAY", "5");
    env.put("OTHER_VALUE", "someOtherValue");
    System.out.println(StrSubstitutor.replace(input, env));
}
</code>```

Output:

```<code>DATA_PATH=/data/myProject/201775
</code>```

It also has a method to directly replace system properties without the need for an explicit map.

(for a non-external-library approach see vefthym's answer)

Body:
I am reading a property file in Java.

Properties myProp = new Properties();
InputStream in = new FileInputStream(pathOfPropertyFile);
myProp.load(in);
in.close();

The values in the property file have references to Linux shell variables.
For example, an entry in the property file might look like:

DATA_PATH=/data/${PROJECT}/${YEAR}${MONTH}${DAY}

I have to execute a shell script from java and so I have ProcessBuilder instance and also the environment variables (envMap as given below):

List<String> command = new ArrayList<String>();
command.add(actualCommand);
command.add(param1);
command.add(param2);
ProcessBuilder processBuilder = new ProcessBuilder(command);
Map<String, String> envMap = processBuilder.environment();

The envMap has the environment variables I require  along with over one hundred (> 100) other environment variables which I do not require.

I want to replace the ${USER},${PROJECT},etc., from the property-value string "/home/${USER}/${PROJECT}/data" with actual values from the shell.

I would consider iterating the Map as the last option(as the Map has between 100 and 200 elements to iterate) as it is not an efficient approach.

Please advise some approach that will fetch the environment variable enclosed by braces from the string, so that I can directly use the get() of the Map and replace. Or, any better approaches are most welcome.

Note:  The reference offered ( Replace String values with value in Hash Map  that made my question to look duplicate) is not the best fit in my case.

Body:
If you are open to using an external library, StrSubstitutor from apache-commons will do exactly what you want:

public static void main(String[] args) {
    String input = "DATA_PATH=/data/${PROJECT}/${YEAR}${MONTH}${DAY}";
    Map<String, String> env = new HashMap<>();
    env.put("PROJECT", "myProject");
    env.put("YEAR", "2017");
    env.put("MONTH", "7");
    env.put("DAY", "5");
    env.put("OTHER_VALUE", "someOtherValue");
    System.out.println(StrSubstitutor.replace(input, env));
}

Output:

DATA_PATH=/data/myProject/201775

It also has a method to directly replace system properties without the need for an explicit map.

(for a non-external-library approach see vefthym's answer)


问:
JPA: Store a list of integers in a single field
Is it possible to store a list of integers in a single field of the respective entity table with standard JPA 2?</p>

```<code>@Entity
@Table(name="tbl_myentities")
public class MyEntity {

@ElementaryCollection
@Column(name="vals") // in table tbl_myentities
private List<Integer> vals;
</code>```

答:
Maybe a @Lob could suit you ? (despite what it imply)

```<code>@Lob
ArrayList<String> vals;
</code>```

(note that your collection must be explicitly an ArrayList)

Body:
Is it possible to store a list of integers in a single field of the respective entity table with standard JPA 2?

@Entity
@Table(name="tbl_myentities")
public class MyEntity {

@ElementaryCollection
@Column(name="vals") // in table tbl_myentities
private List<Integer> vals;

Body:
Maybe a @Lob could suit you ? (despite what it imply)

@Lob
ArrayList<String> vals;

(note that your collection must be explicitly an ArrayList)


问:
Why does jQuery run this code three times?
I have this snippet:

jQuery(document).ready(function() {
  //First bracket detection
  var string = $.trim($('p').text());
  string = string.replace(/\(([^)]+)\)/, "$1");
  $('p').html(string);
});```
<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>
<p> width (10mm) </p>
<p> width (10mm) </p>
<p> width (10mm) </p></code>```

As you can see the items are duplicated. Each item appears 3 times, how can I do it only once?

答:
You need to use .each() to replace the content of paragraph in its context.

jQuery(document).ready(function() {
  $('p').each(function() {
    //First bracket detection
    var string = $.trim($(this).text());
    string = string.replace(/\(([^)]+)\)/, "$1");
    $(this).html(string);
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  font-size: 30px;
  color: green;
  background: yellow;
}</code>```

width (10mm)

width (10mm)

width (10mm)
```

Body:
I have this snippet:

jQuery(document).ready(function() {
  //First bracket detection
  var string = $.trim($('p').text());
  string = string.replace(/\(([^)]+)\)/, "$1");
  $('p').html(string);
});

 width (10mm)

 width (10mm)

 width (10mm)

As you can see the items are duplicated. Each item appears 3 times, how can I do it only once?

Body:
You need to use .each() to replace the content of paragraph in its context.

jQuery(document).ready(function() {
  $('p').each(function() {
    //First bracket detection
    var string = $.trim($(this).text());
    string = string.replace(/\(([^)]+)\)/, "<span>$1</span>");
    $(this).html(string);
  })
});

span {
  font-size: 30px;
  color: green;
  background: yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>width (10mm)</p>
<p>width (10mm)</p>
<p>width (10mm)</p>


问:
What is the maximum recommended number of rows that a SQL 2008 R2 standalone server should store in a single table?
I'm designing my DB for functionality and performance for realtime AJAX web applications, and I don't currently have the resources to add DB server redundancy or load-balancing.

Unfortunately, I have a table in my DB that could potentially end up storing hundreds of millions of rows, and will need to read and write quickly to prevent lagging the web-interface.

Most, if not all, of the columns in this table are individually indexed, and I'd love to know if there are other ways to ease the burden on the server when running querys on large tables. But is there eventually a cap for the size (in rows or GB) of a table before a single unclustered SQL server starts to choke?

My DB only has a dozen tables, with maybe a couple dozen foriegn key relationships. None of my tables have more than 8 or so columns, and only one or two of these tables will end up storing a large number of rows. Hopefully the simplicity of my DB will make up for the massive amounts of data in these couple tables ...

答:
The only limit is the size of your primary key. Is it an INT or a BIGINT?

SQL will happily store the data without a problem. However, with 100 millions of rows, your best off partitioning the data. There are many good articles on this such as this article.

With partitions, you can have 1 thread per partition working at the same time to parallelise the query even more than is possible without paritioning.