问:
display max and min number from user inputted numbers c++
```<code># include <iostream>
using std::endl;
using std::cout;
using std::cin;
int main()
{
    int numUserInt;         // Number of integers the user inputs
    int integers;
    int number;
    int maxNumber = 0;
    int minNumber = 0;

    // Get the number of integers
    cout << "How many integers would you like to enter?" << endl;
    cin  >> numUserInt;
    cout << "Please enter " << numUserInt << " integers." << endl;

    integers = 1;

    while (integers <= numUserInt)
    {
        cin >> number;

        if (numUserInt == 1)
            maxNumber = minNumber = number;

        if (number > maxNumber)
            maxNumber = number;

        if (number < minNumber)
            minNumber = number;

        integers++;
    }

    cout << "min: " << minNumber << endl;
    cout << "max: " << maxNumber << endl;
    return 0;
}
</code>```

For a homework assignment I am supposed to ask a user "How many integers they would like to enter" and then find the Max and min number from the amount without using arrays. For the most part my program works, however when the user let's say enters -6 -6 the output is min: -6 and max: 0. I want this to say the min and max is -6 but I have no idea how to do this with making the rest of the code work. Anybody out there know of a way to do this?

答: Set the value of both the min and max variable to the initial input then compare the min and max to what the user inputs each time to check if an update is neeeded.

Body:
# include <iostream>
using std::endl;
using std::cout;
using std::cin;
int main()
{
    int numUserInt;         // Number of integers the user inputs
    int integers;
    int number;
    int maxNumber = 0;
    int minNumber = 0;

    // Get the number of integers
    cout << "How many integers would you like to enter?" << endl;
    cin  >> numUserInt;
    cout << "Please enter " << numUserInt << " integers." << endl;

    integers = 1;

    while (integers <= numUserInt)
    {
        cin >> number;

        if (numUserInt == 1)
            maxNumber = minNumber = number;

        if (number > maxNumber)
            maxNumber = number;

        if (number < minNumber)
            minNumber = number;

        integers++;
    }

    cout << "min: " << minNumber << endl;
    cout << "max: " << maxNumber << endl;
    return 0;
}

For a homework assignment I am supposed to ask a user "How many integers they would like to enter" and then find the Max and min number from the amount without using arrays. For the most part my program works, however when the user let's say enters -6 -6 the output is min: -6 and max: 0. I want this to say the min and max is -6 but I have no idea how to do this with making the rest of the code work. Anybody out there know of a way to do this?


来源: stackexchange

问:
TensorFlow is not using GPU
I sat up an AWS Deep Learning machine using the AMI. Now I'm trying to run the simple starter example from the TensorFlow

```<code># Creates a graph.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(c))
</code>```

But it appears that my machine is not using my GPUs.

MatMul_2: (MatMul): /job:localhost/replica:0/task:0/cpu:0 2017-07-09
  00:51:03.830238: I
  tensorflow/core/common_runtime/simple_placer.cc:847] MatMul_2:
  (MatMul)/job:localhost/replica:0/task:0/cpu:0 MatMul_1: (MatMul):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830259: I
  tensorflow/core/common_runtime/simple_placer.cc:847] MatMul_1:
  (MatMul)/job:localhost/replica:0/task:0/cpu:0 MatMul: (MatMul):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830271: I
  tensorflow/core/common_runtime/simple_placer.cc:847] MatMul:
  (MatMul)/job:localhost/replica:0/task:0/cpu:0 b_2: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830283: I
  tensorflow/core/common_runtime/simple_placer.cc:847] b_2:
  (Const)/job:localhost/replica:0/task:0/cpu:0 a_2: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830312: I
  tensorflow/core/common_runtime/simple_placer.cc:847] a_2:
  (Const)/job:localhost/replica:0/task:0/cpu:0 b_1: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830324: I
  tensorflow/core/common_runtime/simple_placer.cc:847] b_1:
  (Const)/job:localhost/replica:0/task:0/cpu:0 a_1: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830337: I
  tensorflow/core/common_runtime/simple_placer.cc:847] a_1:
  (Const)/job:localhost/replica:0/task:0/cpu:0 b: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830348: I
  tensorflow/core/common_runtime/simple_placer.cc:847] b:
  (Const)/job:localhost/replica:0/task:0/cpu:0 a: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830358: I
  tensorflow/core/common_runtime/simple_placer.cc:847] a:
  (Const)/job:localhost/replica:0/task:0/cpu:0

If I try to manually specify GPU with with tf.device('/gpu:0'): I get the following error:

InvalidArgumentError: Cannot assign a device for operation 'MatMul_3':
  Operation was explicitly assigned to /device:GPU:0 but available
  devices are [ /job:localhost/replica:0/task:0/cpu:0 ]. Make sure the
  device specification refers to a valid device.     [[Node: MatMul_3 =
  MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false,
  _device="/device:GPU:0"](a_3, b_3)]]

The only change I made to the AMI was that I updated TensorFlow to the latest version

Here's what I see when I run watch nvidia-smi

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 367.57                 Driver Version: 367.57                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K80           On   | 0000:00:1E.0     Off |                    0 |
| N/A   44C    P8    27W / 149W |      0MiB / 11439MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+
</code>```

答:
1.check your instance,do you select GPU?

use "watch nvidia-smi" to see GPU info.

2.check your AMI,and tensorflow version, maybe it doesn't support GPU or have some wrong config.

I use this AMI: Deep Learning AMI Amazon Linux (ami-296e7850).

ContentLicense: CC BY-SA 3.0

Title: TensorFlow is not using GPU

Body:
I sat up an AWS Deep Learning machine using the AMI. Now I'm trying to run the simple starter example from the TensorFlow

# Creates a graph.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(c))

But it appears that my machine is not using my GPUs.

MatMul_2: (MatMul): /job:localhost/replica:0/task:0/cpu:0 2017-07-09
  00:51:03.830238: I
  tensorflow/core/common_runtime/simple_placer.cc:847] MatMul_2:
  (MatMul)/job:localhost/replica:0/task:0/cpu:0 MatMul_1: (MatMul):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830259: I
  tensorflow/core/common_runtime/simple_placer.cc:847] MatMul_1:
  (MatMul)/job:localhost/replica:0/task:0/cpu:0 MatMul: (MatMul):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830271: I
  tensorflow/core/common_runtime/simple_placer.cc:847] MatMul:
  (MatMul)/job:localhost/replica:0/task:0/cpu:0 b_2: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830283: I
  tensorflow/core/common_runtime/simple_placer.cc:847] b_2:
  (Const)/job:localhost/replica:0/task:0/cpu:0 a_2: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830312: I
  tensorflow/core/common_runtime/simple_placer.cc:847] a_2:
  (Const)/job:localhost/replica:0/task:0/cpu:0 b_1: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830324: I
  tensorflow/core/common_runtime/simple_placer.cc:847] b_1:
  (Const)/job:localhost/replica:0/task:0/cpu:0 a_1: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830337: I
  tensorflow/core/common_runtime/simple_placer.cc:847] a_1:
  (Const)/job:localhost/replica:0/task:0/cpu:0 b: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830348: I
  tensorflow/core/common_runtime/simple_placer.cc:847] b:
  (Const)/job:localhost/replica:0/task:0/cpu:0 a: (Const):
  /job:localhost/replica:0/task:0/cpu:0 2017-07-09 00:51:03.830358: I
  tensorflow/core/common_runtime/simple_placer.cc:847] a:
  (Const)/job:localhost/replica:0/task:0/cpu:0

If I try to manually specify GPU with with tf.device('/gpu:0'): I get the following error:

InvalidArgumentError: Cannot assign a device for operation 'MatMul_3':
  Operation was explicitly assigned to /device:GPU:0 but available
  devices are [ /job:localhost/replica:0/task:0/cpu:0 ]. Make sure the
  device specification refers to a valid device.     [[Node: MatMul_3 =
  MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false,
  _device="/device:GPU:0"](a_3, b_3)]]

The only change I made to the AMI was that I updated TensorFlow to the latest version

Here's what I see when I run watch nvidia-smi

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 367.57                 Driver Version: 367.57                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K80           On   | 0000:00:1E.0     Off |                    0 |
| N/A   44C    P8    27W / 149W |      0MiB / 11439MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+


问:
Sliding window time complexity
I have this sliding window algorithms for problem;Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
People said the running time of this algorithm is o(len(s)) and I'd like to make sure that if I understand it correctly.

So the outer while is o(len(s)) (assume map look up is o(1)) and the inner while loop also can run for o(len(s)) in worst case. For exmaple, if S is axyzzzzzzzbc and P is abc then the inner while loop moves the start pointer to the end so it will be o(len(s) + len(s)) so it's o(2len(s)) but we drop constant so the final run time is o(len(s)).

Please let me know if this is correct.

```<code>public List<Integer> findAnagrams(String s, String p) {
    List<Integer> ret = new ArrayList<>();
    Map<Character, Integer> map = new HashMap<>();
    for (Character c : p.toCharArray()) {
        map.put(c, map.get(c) == null ? 1 : map.get(c) + 1);
    }
    int b = 0, i = 0;
    int c = map.size();
    while (i < s.length()) {
        if (map.containsKey(s.charAt(i))) {
            int t = map.get(s.charAt(i)) - 1;
            map.put(s.charAt(i), t);
            if (t == 0) c--;
        }
        i++;
        while (c == 0) {
            if (map.containsKey(s.charAt(b))) {
                int t = map.get(s.charAt(b)) + 1;
                map.put(s.charAt(b), t);
                if (t > 0) c++;
                    c++;
            }
            if (i - b == p.length()) {
                ret.add(b);
            }
            b++;

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

答:
Yes, complexity is linear.
Most chars are treated twice - except for last M=p.length-1 ones.

So O(N + N - M) = O(N)

Title: Sliding window time complexity

Body:
I have this sliding window algorithms for problem;Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
People said the running time of this algorithm is o(len(s)) and I'd like to make sure that if I understand it correctly.

So the outer while is o(len(s)) (assume map look up is o(1)) and the inner while loop also can run for o(len(s)) in worst case. For exmaple, if S is axyzzzzzzzbc and P is abc then the inner while loop moves the start pointer to the end so it will be o(len(s) + len(s)) so it's o(2len(s)) but we drop constant so the final run time is o(len(s)).

Please let me know if this is correct.

public List<Integer> findAnagrams(String s, String p) {
    List<Integer> ret = new ArrayList<>();
    Map<Character, Integer> map = new HashMap<>();
    for (Character c : p.toCharArray()) {
        map.put(c, map.get(c) == null ? 1 : map.get(c) + 1);
    }
    int b = 0, i = 0;
    int c = map.size();
    while (i < s.length()) {
        if (map.containsKey(s.charAt(i))) {
            int t = map.get(s.charAt(i)) - 1;
            map.put(s.charAt(i), t);
            if (t == 0) c--;
        }
        i++;
        while (c == 0) {
            if (map.containsKey(s.charAt(b))) {
                int t = map.get(s.charAt(b)) + 1;
                map.put(s.charAt(b), t);
                if (t > 0) c++;
                    c++;
            }
            if (i - b == p.length()) {
                ret.add(b);
            }
            b++;

        }
    }
    return ret;


问:
Huge empty area at end of table view
There seems to be a huge empty, opaque area below my cells. As I scroll the table view up, I can see there's an opaque area that covers the bright orange background of the table view as shown in the right screen shot. Based on this question, I tried setting the footerHeight to 0 and footerView to an empty view, but it didn't work. Any solution?

Code

```<code>private func setupSongsTable() {
        let frame = CGRect(x: 0, y: 0, width: Screen.width, height: Screen.height)
        songsTable = UITableView(frame: frame, style: UITableViewStyle.plain)
        songsTable.sectionIndexBackgroundColor = UIColor.clear
        songsTable.backgroundColor = .orange
        songsTable.isOpaque = false
        songsTable.backgroundView = nil
        self.view.addSubview(songsTable!)
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        cell.backgroundColor = .blue
        return cell
}
</code>```

答: Try setting the tableView.backgroundColor to .clear. If that doesn't work, check to see what your cell's background colors are. cell.backgroundColor. Judging from your screenshots, it looks like your cells have a white background color while your table's are the default apple light grey color.

Title: Huge empty area at end of table view

Body:
There seems to be a huge empty, opaque area below my cells. As I scroll the table view up, I can see there's an opaque area that covers the bright orange background of the table view as shown in the right screen shot. Based on this question, I tried setting the footerHeight to 0 and footerView to an empty view, but it didn't work. Any solution?

Code

private func setupSongsTable() {
        let frame = CGRect(x: 0, y: 0, width: Screen.width, height: Screen.height)
        songsTable = UITableView(frame: frame, style: UITableViewStyle.plain)
        songsTable.sectionIndexBackgroundColor = UIColor.clear
        songsTable.backgroundColor = .orange
        songsTable.isOpaque = false
        songsTable.backgroundView = nil
        self.view.addSubview(songsTable!)
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        cell.backgroundColor = .blue
        return cell
}


问:
Where is the repository of material.angular.io (the website) located?
In the official website of Material, it says

material.angular.io - We build our own documentation with Angular Material!

But where is the repository located (I mean the source code of the website)? I guess it is on Github but couldn't find it.

答:
If you look at the website , it has a github repository link,

```<code>https://github.com/angular/material2
</code>```

Body:
If you look at the website , it has a github repository link,

https://github.com/angular/material2


问:
Where to find Paint.NET multithreading white paper?
Like I wrote elsewhere, I seem to be sure that a white paper by Rick Brewster about multithreading used in
Paint.NET once existed. I am not able to find any reference to this white paper again however. Does it (still) exist? And if so, where?

EDIT: Found out in comments to an unrelated question that Paint.NET is still free, but code is no longer available? Is this related to the fact that I can't seem to find that white paper any more?

EDIT2: Went straight to the horses mouth on this and will return any answer that I get here. In the meantime any answer you guys might have is more than welcome!

答:
Is it possible, that you found this whitepaper following a link on Coding Horror to Rick Brewster's Blog? Seems he has cleaned up his blog and there are no entries before 2006 anymore.

The only "very little" explanation about threading in Paint.Net i could find anymore was on CodeProject.

OwnerDisplayName: peSHIr

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: peSHIr

OwnerDisplayName: Peter


问:
Access containing function
So, I'm working on a library that generates functions using a function constructor.

Each generated function is to have a property attached to the function known as default for store default values for an options parameter.

like so:

```<code>var generated_function = function( arg1, arg2, options_arg ){ ... }
generated_function.default = {}
</code>```

The reason for attaching the default as a property of the function instead of storing it inside the function like this:

```<code>var generated_function = function( arg1, arg2, options_arg ){
  default = {}
}
</code>```

is that I want the option to change the default settings during runtime if needed.

An example use would be say your default options is a huge object consisting of 100s or evens 1000s of properties, and your argumentative options is on average only 25% of the size that the default is.

Let's also say you are calling this function 100s or 1000s of times, and you are changing the argumentative options every call, but only changing the default options say a maximum of only 2 times.

Now I could just pass the default options along with the argumentative options in that parameter, but that would require creating and passing a lot of objects that are very large in size to the generated function. This is a memory problem.

I cannot afford memory problems with this script. Remember that the function is generated, meaning I also face the problem of passing all of data at that size and frequency to not one, but multiple functions

What I need is to be able to access that attached property, but I cannot do it like this:

```<code>var generated_function = function( arg1, arg2, options_arg ){
  ...
  generated_function.default ... //do something with it
  ...
}
generated_function.default = {}
</code>```

because the name of the function is automatically generated meaning that it will be hard to access the function by name like I did, and the function can be generated inside another generated function meaning that I have to deal with scope problems.

So, basically what I am looking for is something along the lines of:

```<code>var generated_function = function( arg1, arg2, options_arg ){
  ...
  containing_function.default ... //do something with it
  ...
}
generated_function.default = {}
</code>```

So I can use it like this in this generated scenario:

```<code>( window[ somerandomlygeneratedstring ] = function( arg1, arg2, options_arg ){
  ...
  containing_function.default ... //do something with it
  ...
  ( someobjectthatcannotbetracked[ somerandomlygeneratedstring ] = function( arg1, arg2, options_arg ){
    ...
    containing_function.default ...
    ...
  } ).default = { ... }

} ).default = { ... }
</code>```

答:
Function expressions can have an optional name that is only available in the function, so:

```<code>var generated_function = function whatever( arg1, arg2, options_arg ){
  ...
  whatever.default ... //do something with it
  ...
}
</code>```

It doesn't matter that all the generated functions have the same name.

There were some issues with named function expressions in IE up and including version 8 but they aren't an issue in this case if the name is chosen appropriately.

E.g.

var fn0 = function foo(){
  console.log(foo.props.bar);
}
fn0.props = {bar:'f0 old bar'};

var fn1 = function foo(){
  console.log(foo.props.bar);
}
fn1.props = {bar:'f1 old bar'};

// Call fn0, change props, call again
fn0();
fn0.props.name = 'f0 new bar';
fn0();

// Call fn1, change props, call again
fn1();
fn1.props.name = 'f1 new bar';
fn1();```
</div>
</div>
</p>

<p>The above shows that using the same name for multiple function expressions is fine since the name is only available within the function. It's practically identical to:</p>

```var fn0 = function () {
  var foo = arguments.callee;
}
```

except that it's safe in strict mode.

Title: Access containing function

Body:
So, I'm working on a library that generates functions using a function constructor.

Each generated function is to have a property attached to the function known as default for store default values for an options parameter.

like so:

var generated_function = function( arg1, arg2, options_arg ){ ... }
generated_function.default = {}

The reason for attaching the default as a property of the function instead of storing it inside the function like this:

var generated_function = function( arg1, arg2, options_arg ){
  default = {}
}

is that I want the option to change the default settings during runtime if needed.

An example use would be say your default options is a huge object consisting of 100s or evens 1000s of properties, and your argumentative options is on average only 25% of the size that the default is.

Let's also say you are calling this function 100s or 1000s of times, and you are changing the argumentative options every call, but only changing the default options say a maximum of only 2 times.

Now I could just pass the default options along with the argumentative options in that parameter, but that would require creating and passing a lot of objects that are very large in size to the generated function. This is a memory problem.

I cannot afford memory problems with this script. Remember that the function is generated, meaning I also face the problem of passing all of data at that size and frequency to not one, but multiple functions

What I need is to be able to access that attached property, but I cannot do it like this:

var generated_function = function( arg1, arg2, options_arg ){
  ...
  generated_function.default ... //do something with it
  ...
}
generated_function.default = {}

because the name of the function is automatically generated meaning that it will be hard to access the function by name like I did, and the function can be generated inside another generated function meaning that I have to deal with scope problems.

So, basically what I am looking for is something along the lines of:

var generated_function = function( arg1, arg2, options_arg ){
  ...
  containing_function.default ... //do something with it
  ...
}
generated_function.default = {}

So I can use it like this in this generated scenario:

( window[ somerandomlygeneratedstring ] = function( arg1, arg2, options_arg ){
  ...
  containing_function.default ... //do something with it
  ...
  ( someobjectthatcannotbetracked[ somerandomlygeneratedstring ] = function( arg1, arg2, options_arg ){
    ...
    containing_function.default ...
    ...
  } ).default = { ... }

} ).default = { ... }

Body:
Function expressions can have an optional name that is only available in the function, so:

var generated_function = function whatever( arg1, arg2, options_arg ){
  ...
  whatever.default ... //do something with it
  ...
}

It doesn't matter that all the generated functions have the same name.

There were some issues with named function expressions in IE up and including version 8 but they aren't an issue in this case if the name is chosen appropriately.

E.g.

var fn0 = function foo(){
  console.log(foo.props.bar);
}
fn0.props = {bar:'f0 old bar'};

var fn1 = function foo(){
  console.log(foo.props.bar);
}
fn1.props = {bar:'f1 old bar'};

// Call fn0, change props, call again
fn0();
fn0.props.name = 'f0 new bar';
fn0();

// Call fn1, change props, call again
fn1();
fn1.props.name = 'f1 new bar';
fn1();

The above shows that using the same name for multiple function expressions is fine since the name is only available within the function. It's practically identical to:

var fn0 = function () {
  var foo = arguments.callee;
}

except that it's safe in strict mode.


问:
ng-table fixed header and scroll bar
I am using this NG-TABLE and having a hard time trying to modify CSS. I want fixed header and scroll bar for the data. I am using CSS in this link.

My html looks like this.

```<code><ng-table class="table-scroll" [config]="config"
          [rows]="rows" [columns]="columns">
</ng-table>
</code>```

I opened developer tools and observed that table scroll css is not working.

I found the issue. User agent css is overwriting my css. Inside ng-table, there is another table and clss. How can I override that ?

答:
When you use the standard class attribute its value can be ignored by the Angular element.

Much better to go with ngClass instead, as it will append its values to any classes added by the element:

```<code><ng-table [ngClass]="'table-scroll'" [config]="config" [rows]="rows" [columns]="columns">
</ng-table>
</code>```

Example plunker:  https://plnkr.co/edit/d4uFrAsnRJqYMqiyLuTG?p=preview

A second option would be to change the selector from .table-scroll thead ... to the generic table selector table thead ... etc, if you don't have other tables on the page that would be affected.

Title: ng-table fixed header and scroll bar

Body:
I am using this NG-TABLE and having a hard time trying to modify CSS. I want fixed header and scroll bar for the data. I am using CSS in this link.

My html looks like this.

<ng-table class="table-scroll" [config]="config"
          [rows]="rows" [columns]="columns">
</ng-table>

I opened developer tools and observed that table scroll css is not working.

I found the issue. User agent css is overwriting my css. Inside ng-table, there is another table and clss. How can I override that ?

Body:
When you use the standard class attribute its value can be ignored by the Angular element.

Much better to go with ngClass instead, as it will append its values to any classes added by the element:

<ng-table [ngClass]="'table-scroll'" [config]="config" [rows]="rows" [columns]="columns">
</ng-table>

Example plunker:  https://plnkr.co/edit/d4uFrAsnRJqYMqiyLuTG?p=preview

A second option would be to change the selector from .table-scroll thead ... to the generic table selector table thead ... etc, if you don't have other tables on the page that would be affected.


问:
ember.js scroll to bottom of chat box after route refresh
I'm building an ember app with email like messaging.

When a user is sending a message the container should scroll
to the bottom to show the new message. Here's the action that creates the new message

```<code>  createMessage(messageParams) {
    this.get('store').createRecord('message', messageParams).save()
    .then(() => {
      return this.refresh()
    })
    .then(() => {
        let objDiv = document.getElementById("message-container");
        objDiv.scrollTop = objDiv.scrollHeight;
    })
    .catch(() => {
      this.get('flashMessages')
        .danger('There was a problem. Please try again.');
    });
</code>```

As of now the chat box does not scroll to the bottom when the new message appears in the container. It works when I wrap the code in the second .then in a set timeout.

Should I put the code that scrolls the container to the bottom somewhere else in route file? I tried putting it in the afterModel hook. I also tried putting it in a .then after the model hook. When I did that, I got a blank white page when navigating to the route in the app.

```<code>model(params) {
    return Ember.RSVP.hash({
      messages: this.get('store').query('message', {
        id: params.conversation_id
      }),
      conversation: this.get('store').find('conversation', params.conversation_id)
    }).then(() => {
      let objDiv = document.getElementById("message-container");
      objDiv.scrollTop = objDiv.scrollHeight;
    });
  }
</code>```

答:
In didTransition hook, you can run DOM code in run loop afterRender queue.

```<code>didTransition() {
  Ember.run.later('afterRender', () => {
    let objDiv = document.getElementById("message-container");
    objDiv.scrollTop = objDiv.scrollHeight;
  }, 100);
  return true;
},
</code>```

DOM manipulation code should go in Component, I prefer you to write component for showing the message and make use of the component lifecycle hook methods(i.e, in your case didRender would be best fit)

Body:
I'm building an ember app with email like messaging.

When a user is sending a message the container should scroll
to the bottom to show the new message. Here's the action that creates the new message

  createMessage(messageParams) {
    this.get('store').createRecord('message', messageParams).save()
    .then(() => {
      return this.refresh()
    })
    .then(() => {
        let objDiv = document.getElementById("message-container");
        objDiv.scrollTop = objDiv.scrollHeight;
    })
    .catch(() => {
      this.get('flashMessages')
        .danger('There was a problem. Please try again.');
    });

As of now the chat box does not scroll to the bottom when the new message appears in the container. It works when I wrap the code in the second .then in a set timeout.

Should I put the code that scrolls the container to the bottom somewhere else in route file? I tried putting it in the afterModel hook. I also tried putting it in a .then after the model hook. When I did that, I got a blank white page when navigating to the route in the app.

model(params) {
    return Ember.RSVP.hash({
      messages: this.get('store').query('message', {
        id: params.conversation_id
      }),
      conversation: this.get('store').find('conversation', params.conversation_id)
    }).then(() => {
      let objDiv = document.getElementById("message-container");
      objDiv.scrollTop = objDiv.scrollHeight;
    });
  }

Body:
In didTransition hook, you can run DOM code in run loop afterRender queue.

didTransition() {
  Ember.run.later('afterRender', () => {
    let objDiv = document.getElementById("message-container");
    objDiv.scrollTop = objDiv.scrollHeight;
  }, 100);
  return true;
},

DOM manipulation code should go in Component, I prefer you to write component for showing the message and make use of the component lifecycle hook methods(i.e, in your case didRender would be best fit)


问:
Why this while loop does not work?
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

```<code>M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)
</code>```

`

答:
In your while loop, you are using the and operator on B and C. As per Reference 5.1 of Python 2.7, only empty arrays would yield False.

https://docs.python.org/release/2.7.13/library/stdtypes.html#truth-value-testing

As suggested by Mark, subsequent to your first pop, the condition B[0] <= C[0] is no longer true and therefore no more element is popped. This, in turn, means that neither B or C ever reaches a point where it is empty. Therefore, there is no possibility to exit this loop.

Title: Why this while loop does not work?

Body:
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)

`


问:
Want to make it so prices actually reflect the choices
Hope everyone is having a good weekend!

If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!

var pizzaPrice = 0;

function Pizza(size,toppings,pizzaPrice) {
  this.size = size;
  this.toppings = toppings;
  this.pizzaPrice = 0;
}

Pizza.prototype.price = function() {
  if (this.size === "Small") {
    this.pizzaPrice += 2;
  }
  else if (this.size === "Medium") {
    this.pizzaPrice += 3;
  }
  else if (this.size === "Large") {
    this.pizzaPrice += 4;
  }
  if (this.toppings === "Cheese") {
    this.pizzaPrice += 3;
  }

  else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
    this.pizzaPrice += 10;
    console.log("hey");

  }

  else if (this.toppings === "Vegetarian") {
    this.pizzaPrice += 2;
  }
  else if (this.toppings === "Supreme") {
    this.pizzaPrice += 4;
  }
  else if (this.toppings === "Pepperoni") {
    this.pizzaPrice += 3;
  }

return this.pizzaPrice;
}

$(document).ready(function(){
  $("form#pizza").submit(function(event){
    event.preventDefault();

    var size = $("input[type=radio][name=size]:checked").val();
    var toppings = $("input[type=checkbox][name=toppings]:checked").val();
    var newPizza = new Pizza(size,toppings,pizzaPrice);
    newPizza.price();

    $("#responses").append("
" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "
");

      });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <title>Pizza Pizza</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.2.0.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <h2>Pizza Toppings</h2>
      </div>
      <form id="pizza">
        <div class="form-group">
          <p>What size would you like your pizza:</p>
          <input type="radio" name="size" value="Small">Small.<br>
          <input type="radio" name="size" value="Medium">Medium.<br>
          <input type="radio" name="size" value="Large">Large.<br>
        </div>
        <div class="form-group">
          <p>Which toppings would you like</p>
          <input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
          <input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
          <input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
          <input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
          <input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
          <input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
          <input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
          <input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
        </div>
       <button type="submit">Let's get your order</button>
      </form>
      <ul id="responses">
      </ul>
    </div>
  </body>
</html></code>```

答:
The statement here

```<code>var toppings = $("input[type=checkbox][name=toppings]:checked").val();
</code>```

is incorrect. As it is returning you the value of first checked checkbox.
Instead use following statement to get an array of checked values.

```<code>var toppings = $("input[type=checkbox][name=toppings]:checked").get();
</code>```

Now while retrieving the values you can use the following:

```<code>(this.toppings.indexOf("Cheese") >= 0)
</code>```

The indexOf() returns -1 if no matching results is found.
Hope this solves your problem.

Body:
Hope everyone is having a good weekend!

If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!

var pizzaPrice = 0;

function Pizza(size,toppings,pizzaPrice) {
  this.size = size;
  this.toppings = toppings;
  this.pizzaPrice = 0;
}

Pizza.prototype.price = function() {
  if (this.size === "Small") {
    this.pizzaPrice += 2;
  }
  else if (this.size === "Medium") {
    this.pizzaPrice += 3;
  }
  else if (this.size === "Large") {
    this.pizzaPrice += 4;
  }
  if (this.toppings === "Cheese") {
    this.pizzaPrice += 3;
  }

  else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
    this.pizzaPrice += 10;
    console.log("hey");

  }

  else if (this.toppings === "Vegetarian") {
    this.pizzaPrice += 2;
  }
  else if (this.toppings === "Supreme") {
    this.pizzaPrice += 4;
  }
  else if (this.toppings === "Pepperoni") {
    this.pizzaPrice += 3;
  }

return this.pizzaPrice;
}

$(document).ready(function(){
  $("form#pizza").submit(function(event){
    event.preventDefault();

    var size = $("input[type=radio][name=size]:checked").val();
    var toppings = $("input[type=checkbox][name=toppings]:checked").val();
    var newPizza = new Pizza(size,toppings,pizzaPrice);
    newPizza.price();

    $("#responses").append("
" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "
");

      });
    });

<!DOCTYPE html>

    <title>Pizza Pizza</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">

Pizza Toppings

      <form id="pizza">

What size would you like your pizza:

          <input type="radio" name="size" value="Small">Small.

          <input type="radio" name="size" value="Medium">Medium.

          <input type="radio" name="size" value="Large">Large.

Which toppings would you like

          <input type="checkbox" name="toppings" value="Cheese">Cheese.

          <input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.

          <input type="checkbox" name="toppings" value="Supreme">Supreme.

          <input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.

          <input type="checkbox" name="toppings" value="Fruit">Fruit.

          <input type="checkbox" name="toppings" value="Bacon">Bacon.

          <input type="checkbox" name="toppings" value="Artichoke">Artichoke.

          <input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.

       <button type="submit">Let's get your order</button>
      </form>

Body:
The statement here

var toppings = $("input[type=checkbox][name=toppings]:checked").val();

is incorrect. As it is returning you the value of first checked checkbox.
Instead use following statement to get an array of checked values.

var toppings = $("input[type=checkbox][name=toppings]:checked").get();

Now while retrieving the values you can use the following:

(this.toppings.indexOf("Cheese") >= 0)

The indexOf() returns -1 if no matching results is found.
Hope this solves your problem.


问:
I want call php page by clicking on a button but I want to verify it first through javascript that entered value is correct or not
```<code><head>
function search() {
    var n = document.getElementById("search");
    if(n === A || n === B) {
        location.href = "search.php";
        return true;
    } else {
        alert "Enter Correct value ...";
        return false;
    }
}
</script>
</head>
</code>```

I'm using this code for verify entered value and after verification I want call php page to get the entered value for further task

```<code><body>
<form>
    <input type="text" id="search" onsubmit="search()" name="bg">
</form>
</body>
</code>```

答:
Try this code : why you are not using opening script tag

< script > tag after

```<code><head>
</script>
function search() {
    var n = document.getElementById("search");
    if(n === A || n === B) {
        location.href = "search.php";
        return true;
    } else {
        alert "Enter Correct value ...";
        return false;
    }
}
</script>
</head>
</code>```

Body:
function search() {
    var n = document.getElementById("search");
    if(n === A || n === B) {
        location.href = "search.php";
        return true;
    } else {
        alert "Enter Correct value ...";
        return false;
    }
}
</script>

I'm using this code for verify entered value and after verification I want call php page to get the entered value for further task

<form>
    <input type="text" id="search" onsubmit="search()" name="bg">
</form>

Body:
Try this code : why you are not using opening script tag

< script > tag after < head >

<head>
</script>
function search() {
    var n = document.getElementById("search");
    if(n === A || n === B) {
        location.href = "search.php";
        return true;
    } else {
        alert "Enter Correct value ...";
        return false;
    }
}
</script>
</head>


问:
How to solve Leaks?
So I have memory leaks in my game. I think its coming from Admob and game center integration. Any suggestion for tackling this problem? I tried locating the problem using leak instrument but I have no idea how to do that. Also is it worth solving the leaks? I have about 7 leaks every while.

```<code>//Ad banner

        self.banner = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
        self.banner.adUnitID = "ca-app-pub-3940256099942544/6300978111"
        self.banner.rootViewController = self
        let request: GADRequest = GADRequest()
        self.banner.load(request)
        self.banner.frame = CGRect(x: 0,y: view.bounds.height - self.banner.frame.size.height, width: self.banner.frame.size.width, height: self.banner.frame.size.height)

        self.view.addSubview(self.banner!)

//gamecenter authentication

    func authPlayer () {
            let player = GKLocalPlayer.localPlayer()
            player.authenticateHandler = {
                (view, error) in
                if view != nil {
                    self.present(view!, animated: true,completion: nil)

                }
            }
        }
</code>```

答:
Add deinit to your classes with a print message to determine which classes are not dying when they should. Then, you go to the places that these classes are instantiated and make them weak or unowned variables with an optional type.

If that doesn't fix it, then you may have issues with closures going on, but I would worry about learning closure capture leaks only AFTER you understand the basics of ARC.

Here is a great tutorial that shows how ARC works and how to track down leaks in more detail:

https://www.raywenderlich.com/134411/arc-memory-management-swift

To your second question, no, memory leaks may not be a huge concern for you. However, they may also be a huge concern. The way to find out is to leave your app on for the whole day, or spend half an hour going through the different levels and seeing if your memory usage keeps going up.

If your memory use keeps going up, then you have a problem that definitely needs fixing. Otherwise, your app is just using more resources than is needed, which isn't ideal, but not necessarily critical to fix either.

Title: How to solve Leaks?

Body:
So I have memory leaks in my game. I think its coming from Admob and game center integration. Any suggestion for tackling this problem? I tried locating the problem using leak instrument but I have no idea how to do that. Also is it worth solving the leaks? I have about 7 leaks every while.

//Ad banner

        self.banner = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
        self.banner.adUnitID = "ca-app-pub-3940256099942544/6300978111"
        self.banner.rootViewController = self
        let request: GADRequest = GADRequest()
        self.banner.load(request)
        self.banner.frame = CGRect(x: 0,y: view.bounds.height - self.banner.frame.size.height, width: self.banner.frame.size.width, height: self.banner.frame.size.height)

        self.view.addSubview(self.banner!)

//gamecenter authentication

    func authPlayer () {
            let player = GKLocalPlayer.localPlayer()
            player.authenticateHandler = {
                (view, error) in
                if view != nil {
                    self.present(view!, animated: true,completion: nil)

                }
            }
        }


问:
Wordpress - Menu links and dropdown does not work in frontpage home
When we load site www.cligest.com made with WordPress the menu links and the dropdown options on the web initial page, the frontpage ("home") don't work. They just work in all other pages except "home".

I've tried 15 different solutions, with no luck.

答:
Try adding the following css:</p>

```<code>nav ul.main-menu {

    z-index: 10;
}
</code>```

Body:
Try adding the following css:

nav ul.main-menu {

    z-index: 10;
}


答:
This occurs because you have a div on top of the menu. It only happens on the homepage because that div or .homepage-section only exists on the homepage.

Try adding this to your CSS sheet and see if it makes any difference. It should bring your menu on top.

```<code>.main-menu {z-index: 2}
</code>```

Title: Wordpress - Menu links and dropdown does not work in frontpage home

Body:
When we load site www.cligest.com made with WordPress the menu links and the dropdown options on the web initial page, the frontpage ("home") don't work. They just work in all other pages except "home".

I've tried 15 different solutions, with no luck.

Body:
This occurs because you have a div on top of the menu. It only happens on the homepage because that div or .homepage-section only exists on the homepage.

Try adding this to your CSS sheet and see if it makes any difference. It should bring your menu on top.

.main-menu {z-index: 2}


问:
Grails - how to call a controller method from a form
I'm completely new to grails, and I appreciate any help.
This code is in my gsp file:

```<code><g:form action="backfillMachineTags">
            <fieldset class="buttons">
                <g:submitButton name="create" class="save"
                                value="${message(code: 'default.button.create.label', default: 'Create')}"/>
            </fieldset>
        </g:form>
</code>```

And this code is in my RegressionPoolMachineController.groovy file:

```<code>def backfillMachineTags()
    {
        flash.message = "testing message"
        redirect(action: "list")
    }
</code>```

But when I click the submit button on the form, the method is never entered and I get a 404 not found.

message:/pool-manager/regressionPoolMachine/backfillMachineTags

status:  The requested resource is not available.

I also tried doing:

```<code><g:form url="[action:'backfillMachineTags',controller:'RegressionPoolMachineController']">
</code>```

but get a similar 404 not found.

Am I missing a step to connect my form and controller?

答:
Try to use the following:</p>

```<code><g:form controller = "controllerName" action ="actionName" >
    <fieldset class="buttons">
        <g:submitButton name="create" class="save" value ="${message(code: 'default.button.create.label', default: 'Create')}"/>
    </fieldset>
 </g:form>
</code>```

Body:
I'm completely new to grails, and I appreciate any help.
This code is in my gsp file:

<g:form action="backfillMachineTags">
            <fieldset class="buttons">
                <g:submitButton name="create" class="save"
                                value="${message(code: 'default.button.create.label', default: 'Create')}"/>
            </fieldset>
        </g:form>

And this code is in my RegressionPoolMachineController.groovy file:

def backfillMachineTags()
    {
        flash.message = "testing message"
        redirect(action: "list")
    }

But when I click the submit button on the form, the method is never entered and I get a 404 not found.

message:/pool-manager/regressionPoolMachine/backfillMachineTags

status:  The requested resource is not available.

I also tried doing:

<g:form url="[action:'backfillMachineTags',controller:'RegressionPoolMachineController']">

but get a similar 404 not found.

Am I missing a step to connect my form and controller?

Body:
Try to use the following:

<g:form controller = "controllerName" action ="actionName" >
    <fieldset class="buttons">
        <g:submitButton name="create" class="save" value ="${message(code: 'default.button.create.label', default: 'Create')}"/>
    </fieldset>
 </g:form>


问:
How to call reloaddata() from another class?
I have two classes NSViewController, which contains a NSTableView, and a NSPageController, which can be used to add data to the table view. How can I call reloadData() from NSPageController to update the table view of NSViewController?

Update:

I already tried to solve this with a delegate and I already have done this in Objective-C, but with swift I feel completely lost.

My PageController needs to notify the ViewController, that the tableView has to be updated. So I added this code to my PageController

```<code>protocol PageControllerDelegate {
    func updateTableView()
}
</code>```

and

```<code>weak var delegate: PageControllerDelegate?
</code>```

To my ViewController which hold the table view I added the following lines:

```<code>class ViewController: NSViewController, PageControllerDelegate {
...
</code>```

and

```<code>func updateTableView() {
        self.tableView.reloadData()
}
</code>```

Xcode gives me the following errors:

'weak' may only be applied to class and class-bound protocol types, not 'PageControllerDelegate'

Property 'delegate' with type 'PageControllerDelegate?' cannot override a property with type 'NSPageControllerDelegate?' (aka 'Optional')

答:
A simple way to do, depending on your control hierarchy - if your NSViewControllers hold your controller, then give our controller class a weak var delegate: NSViewControllerDelegate, and define a `protocol

```<code>NSViewControllerDelegate: AnyObject {
   func controllerShouldUpdateTableView(_ controller: NSController)
}
</code>```

have your NSViewController conform to this protocol, and then make sure set the delegate on the controller. Just call this function when needed to reload your table.

Body:
I have two classes NSViewController, which contains a NSTableView, and a NSPageController, which can be used to add data to the table view. How can I call reloadData() from NSPageController to update the table view of NSViewController?

Update:

I already tried to solve this with a delegate and I already have done this in Objective-C, but with swift I feel completely lost.

My PageController needs to notify the ViewController, that the tableView has to be updated. So I added this code to my PageController

protocol PageControllerDelegate {
    func updateTableView()
}

and

weak var delegate: PageControllerDelegate?

To my ViewController which hold the table view I added the following lines:

class ViewController: NSViewController, PageControllerDelegate {
...

and

func updateTableView() {
        self.tableView.reloadData()
}

Xcode gives me the following errors:

'weak' may only be applied to class and class-bound protocol types, not 'PageControllerDelegate'

Property 'delegate' with type 'PageControllerDelegate?' cannot override a property with type 'NSPageControllerDelegate?' (aka 'Optional')

Body:
A simple way to do, depending on your control hierarchy - if your NSViewControllers hold your controller, then give our controller class a weak var delegate: NSViewControllerDelegate, and define a `protocol

NSViewControllerDelegate: AnyObject {
   func controllerShouldUpdateTableView(_ controller: NSController)
}

have your NSViewController conform to this protocol, and then make sure set the delegate on the controller. Just call this function when needed to reload your table.


问:
Cannot resolve method putExtra
I am working through an app in Android Studio that passes data using intent for school. I have created my object to pass the data through and started the Intent but I keep getting a warning that my putExtra method cannot be resolved. Any ideas?
Thanks in advance.

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

private ContactInfo contactobject;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Bundle extra = getIntent().getExtras();
    contactobject = (ContactInfo)extra.get("contact");
    if (contactobject == null )
        contactobject = new ContactInfo();

    TextView name1 = (TextView) findViewById(R.id.Name1);
    name1.setText(contactobject.getOneName());

    TextView phone1 = (TextView) findViewById(R.id.Phone1);
    phone1.setText(contactobject.getOnePhone());

    TextView email1 = (TextView) findViewById(R.id.Email1);
    email1.setText(contactobject.getOneEmail());

    TextView kin1 = (TextView) findViewById(R.id.Kin1);
    kin1.setText(contactobject.getOneKin());

    TextView name2 = (TextView) findViewById(R.id.Name2);
    name2.setText(contactobject.getTwoName());

    TextView phone2 = (TextView) findViewById(R.id.Phone2);
    phone2.setText(contactobject.getTwoPhone());

    TextView email2 = (TextView) findViewById(R.id.Email2);
    email2.setText(contactobject.getTwoEmail());

    TextView kin2 = (TextView) findViewById(R.id.Kin2);
    kin2.setText(contactobject.getTwoEmail());

}

public void EditPrimary(View view)
{
    Intent intent1 = new Intent(getApplicationContext(), Edit1.class);
    Intent intent = intent1.putExtra("contact", contactobject);
    startActivity(intent1);
}

}
</code>```

答:
There are two points:

Point 1: don't need to assign intent1.putExtra("contact", contactobject); value to other variable

Point 2: Your ContactInfo Class must implements class Parcelable or Serializable while you are passing it through an Intent.

See this post to learn how to make a Class Parcelable.

I am sure you are missing second point.

Title: Cannot resolve method putExtra

Body:
I am working through an app in Android Studio that passes data using intent for school. I have created my object to pass the data through and started the Intent but I keep getting a warning that my putExtra method cannot be resolved. Any ideas?
Thanks in advance.

public class MainActivity extends AppCompatActivity {

private ContactInfo contactobject;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Bundle extra = getIntent().getExtras();
    contactobject = (ContactInfo)extra.get("contact");
    if (contactobject == null )
        contactobject = new ContactInfo();

    TextView name1 = (TextView) findViewById(R.id.Name1);
    name1.setText(contactobject.getOneName());

    TextView phone1 = (TextView) findViewById(R.id.Phone1);
    phone1.setText(contactobject.getOnePhone());

    TextView email1 = (TextView) findViewById(R.id.Email1);
    email1.setText(contactobject.getOneEmail());

    TextView kin1 = (TextView) findViewById(R.id.Kin1);
    kin1.setText(contactobject.getOneKin());

    TextView name2 = (TextView) findViewById(R.id.Name2);
    name2.setText(contactobject.getTwoName());

    TextView phone2 = (TextView) findViewById(R.id.Phone2);
    phone2.setText(contactobject.getTwoPhone());

    TextView email2 = (TextView) findViewById(R.id.Email2);
    email2.setText(contactobject.getTwoEmail());

    TextView kin2 = (TextView) findViewById(R.id.Kin2);
    kin2.setText(contactobject.getTwoEmail());

}

public void EditPrimary(View view)
{
    Intent intent1 = new Intent(getApplicationContext(), Edit1.class);
    Intent intent = intent1.putExtra("contact", contactobject);
    startActivity(intent1);
}

}


问:
String to Double in Java
I have in my Java app double numbers. I need to convert String to Double, but string representation of number is

, - separates decimal part of number (
  example    1,5  eq 6/4 )

. - separates groups of three digits (
  example  1.000.000  eq 1000000 )

.
How to achieve this conversion String to Double ?

答:
Looks like the German locale has that number format.</p>

```<code>Double d = (Double) NumberFormat.getInstance(Locale.GERMAN).parse(s);
</code>```

Title: String to Double in Java

Body:
Looks like the German locale has that number format.

Double d = (Double) NumberFormat.getInstance(Locale.GERMAN).parse(s);


问:
Uploaded files are neither moving into a new location , nor storing in database.
I have been tried many times to move the uploaded image or file in a location and also store the name in database.

All the functions work perfectly in LocalHost, but not on Server.
Neither I can see any thing in the directory of a server not any info of the uploaded file in a database.

I have googled and tried almost every trick to solve the issue. Common solution is to edit the permission of a folder. I did it too but all in vain.

What can be the solution ? What am I doing wrong ? The following code works perfectly if using Local host .

```<code>        $destination_path ="uploads/";
        $target = $destination_path.basename( $_FILES["Upload"]["name"]);
        $filename=$_FILES['Upload']['name'];
        $filetype=$_FILES['Upload']['type'];
        $filetmp=$_FILES['Upload']['tmp_name'];
        $images=move_uploaded_file($filetmp, $target);
        $attachment = file_get_contents($_FILES["Upload"]["tmp_name"]);

       $ins_sql="INSERT INTO wp_reklamation(Vorname,Nachname,Auftragsnummer,name,Upload,Grund,Wunsch,Telefonnummer,Email) VALUES('$vorname','$nachname','$auftrag','$filename','$images','$grund','$wunsch','$telefon','$email')";
</code>```

Moreover, to send the attachment is also an issue. But I believe if this problem first can get resolved, I can solve that mail problem by using the above parameters . But Ofcourse nothing is selected nor moved in the location and database, then how can mail send the item name or anything else related to it .

Thanks

答:
If the code works fine on localhost but not on your server, the most likely cause of the issue is that PHP file uploads are not enabled on your server.
To enable them, find the "file_uploads" directive in your 'php.ini' file and set it to on:

file_uploads = On

Also make sure that the user running your PHP server has permission to write to the target directory.

This question suggests creating a new group with permissions to read and write to the directory and adding the users for the PHP server and FTP as members, so the directory is still accessible through FTP and the server can write uploaded files to it.

Body:
I have been tried many times to move the uploaded image or file in a location and also store the name in database.

All the functions work perfectly in LocalHost, but not on Server.
Neither I can see any thing in the directory of a server not any info of the uploaded file in a database.

I have googled and tried almost every trick to solve the issue. Common solution is to edit the permission of a folder. I did it too but all in vain.

What can be the solution ? What am I doing wrong ? The following code works perfectly if using Local host .

        $destination_path ="uploads/";
        $target = $destination_path.basename( $_FILES["Upload"]["name"]);
        $filename=$_FILES['Upload']['name'];
        $filetype=$_FILES['Upload']['type'];
        $filetmp=$_FILES['Upload']['tmp_name'];
        $images=move_uploaded_file($filetmp, $target);
        $attachment = file_get_contents($_FILES["Upload"]["tmp_name"]);

       $ins_sql="INSERT INTO wp_reklamation(Vorname,Nachname,Auftragsnummer,name,Upload,Grund,Wunsch,Telefonnummer,Email) VALUES('$vorname','$nachname','$auftrag','$filename','$images','$grund','$wunsch','$telefon','$email')";

Moreover, to send the attachment is also an issue. But I believe if this problem first can get resolved, I can solve that mail problem by using the above parameters . But Ofcourse nothing is selected nor moved in the location and database, then how can mail send the item name or anything else related to it .

Thanks


问:
In tensorflow, how to separate by sentences when running word2vec model?
In gensim word2vec, the input can be a list of sentences. However, in tensorflow word2vec, the input is a list of words (concatenate sentences together). Is there a way to separate the sentences when constructing {target word, context word} pairs?
I am using the following code:
https://github.com/tensorflow/tensorflow/blob/r0.8/tensorflow/models/embedding/word2vec.py</p>

答:
Here is a Skip-gram pair generator from Tensorflow example: https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/examples/tutorials/word2vec/word2vec_basic.py

```<code># Step 3: Function to generate a training batch for the skip-gram model.
def generate_batch(batch_size, num_skips, skip_window):
  global data_index
  assert batch_size % num_skips == 0
  assert num_skips <= 2 * skip_window
  batch = np.ndarray(shape=(batch_size), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
  span = 2 * skip_window + 1 # [ skip_window target skip_window ]
  buffer = collections.deque(maxlen=span)
  for _ in range(span):
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  for i in range(batch_size // num_skips):
    target = skip_window  # target label at the center of the buffer
    targets_to_avoid = [ skip_window ]
    for j in range(num_skips):
      while target in targets_to_avoid:
        target = random.randint(0, span - 1)
      targets_to_avoid.append(target)
      batch[i * num_skips + j] = buffer[skip_window]
      labels[i * num_skips + j, 0] = buffer[target]
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  return batch, labels
</code>```

If you run above module, you will get {target word, context word} pairs within each mini-batch.

For example, if your data looks like

```<code>data: ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse']
</code>```

Then you will get input and output pair below:

```<code>with num_skips = 2 and skip_window = 1:
    batch: ['originated', 'originated', 'as', 'as', 'a', 'a', 'term', 'term', 'of', 'of', 'abuse', 'abuse', 'first', 'first', 'used', 'used']
    labels: ['as', 'anarchism', 'originated', 'a', 'term', 'as', 'a', 'of', 'term', 'abuse', 'of', 'first', 'used', 'abuse', 'against', 'first']
</code>```

Because the skip gram predicts context words: originated -> as, originated -> anarchism.

I have CBOW batch generator implementation as well. Comment it if you want me to post that here as well.

Body:
Here is a Skip-gram pair generator from Tensorflow example: https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/examples/tutorials/word2vec/word2vec_basic.py

# Step 3: Function to generate a training batch for the skip-gram model.
def generate_batch(batch_size, num_skips, skip_window):
  global data_index
  assert batch_size % num_skips == 0
  assert num_skips <= 2 * skip_window
  batch = np.ndarray(shape=(batch_size), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
  span = 2 * skip_window + 1 # [ skip_window target skip_window ]
  buffer = collections.deque(maxlen=span)
  for _ in range(span):
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  for i in range(batch_size // num_skips):
    target = skip_window  # target label at the center of the buffer
    targets_to_avoid = [ skip_window ]
    for j in range(num_skips):
      while target in targets_to_avoid:
        target = random.randint(0, span - 1)
      targets_to_avoid.append(target)
      batch[i * num_skips + j] = buffer[skip_window]
      labels[i * num_skips + j, 0] = buffer[target]
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  return batch, labels

If you run above module, you will get {target word, context word} pairs within each mini-batch.

For example, if your data looks like

data: ['anarchism', 'originated', 'as', 'a', 'term', 'of', 'abuse']

Then you will get input and output pair below:

with num_skips = 2 and skip_window = 1:
    batch: ['originated', 'originated', 'as', 'as', 'a', 'a', 'term', 'term', 'of', 'of', 'abuse', 'abuse', 'first', 'first', 'used', 'used']
    labels: ['as', 'anarchism', 'originated', 'a', 'term', 'as', 'a', 'of', 'term', 'abuse', 'of', 'first', 'used', 'abuse', 'against', 'first']

Because the skip gram predicts context words: originated -> as, originated -> anarchism.

I have CBOW batch generator implementation as well. Comment it if you want me to post that here as well.


问:
How to center a list item inside a horizontal unordered list?
html/css newbie here.

I have done some courses on html/css and now I'm testing my knowledge by attempting to copy some websites I like. Right now I'm trying my best to make Khan Academy's front page (https://www.khanacademy.org), but I've been struggling with something.

I have an
 that represents the top navigation bar of the page, and now I'm trying to center their logo (
 that is inside the navbar as a list item) to the page but using text-align: center and margin-left: auto; & margin-right: auto doesn't seem to do anything.

Here's my code:

body {
  margin: 0;
  padding: 0;
  background-image: url("https://cdn.kastatic.org/images/homepage/mountains-simple.svg");
  background-repeat: no-repeat;
  background-size: 157.75%;
  background-position-x: 50.825%;
}

li {
  display: inline-block;
}

.navbar {
  overflow: hidden;
  width: 100%;
  height: 60px;
  border-bottom-color: #68e2de;
  border-bottom-width: 1px;
  border-bottom-style: solid;
}

.navbar {
  list-style: none;
}

.navbar-text {
  color: white;
  float: left;
  font-weight: 400;
  font-family: 'Montserrat', sans-serif;
  font-weight: 500;
  font-size: 17px;
  padding: 13px 38px 0px 4px;
  margin-left: -8px;
}

#ka {
  display: inline-block;
}

#ka-logo {
  float: left;
  width: 24px;
  margin-left: auto;
  margin-right: auto;
}

#search-icon {
  width: 32px;
  margin-left: -44px;
  margin-top: 8px;
}

#search-bar {
  background-color: #47dcd6;
  border-radius: 4px;
  margin-left: 8px;
  border: 1px solid #47dcd6;
  padding: 12px 175px 14px 12px;
}

#expand-triangle {
  font-size: 13px;
  margin-left: 7px;
  color: #85e8e3;
}

.bold-signika {
  display: inline;
  font-family: 'Signika', sans-serif;
  font-size: 23px;
  color: white;
  font-weight: 600;
}

.signika {
  display: inline;
  font-family: 'Signika', sans-serif;
  color: white;
  font-size: 23px;
}

#sign {
  float: right;
  margin-right: 44px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Signika:400,600" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="main.css">
</head>

<body>
  <ul class="navbar">
    <li class="navbar-text">Subjects<span id="expand-triangle">▼</span></li>
    <li id="search-bar" class="navbar-text">Search</li>
    <li><img id="search-icon" src="search.png"></li>
    <li>
      <div id="ka">
        <img id="ka-logo" src="leaf-green.svg">
        <div class="bold-signika">KHAN</div>
        <div class="signika">ACADEMY</div>
      </div>
    </li>
    <li id="sign" class="navbar-text">New user / Sign up</li>
  </ul>
</body>

</html></code>```

I have seem this question but what was suggested didn't work for me.

My question is: how do I center the logo div?

A side note: since I'm fairly new to html there could be a lot of bad practices in the code above. Tips on how to do the things I did more efficiently would be highly appreciated.

答:
here a solution for your problem.

In CSS, flex is very usefull, take a look at:

Flex guide https://css-tricks.com/snippets/css/a-guide-to-flexbox/

My CSS

I have used flexbox for centered verically divs and set the right div.

For the logo, I used a first div with the height and width of the taskbar (non-clickable) and a second with the logo centered (clickable) with position absolute.

Enjoy

body {
  margin: 0;
  padding: 0;
  background-image: url("https://cdn.kastatic.org/images/homepage/mountains-simple.svg");
  background-repeat: no-repeat;
  background-size: 157.75%;
  background-position-x: 50.825%;
}

li {
  display: inline-block;
}

.navbar {
  overflow: hidden;
  width: 100%;
  height: 60px;
  border-bottom-color: #68e2de;
  border-bottom-width: 1px;
  border-bottom-style: solid;

  display: flex;
  align-items:center;
  position:absolute;
}

.navbar {
  list-style: none;
}

.navbar-text {
  color: white;
  float: left;
  font-family: 'Montserrat', sans-serif;
  font-weight: 500;
  font-size: 17px;
  /**padding: 0 38px 0px 4px;**/
}

.logo {
  position:absolute;
  height:100%;
  top:0;
  left:0;
  width:100%;
  display:flex;
  justify-content:center;
  align-items:center;
  pointer-events:none;
}

.logo-container {
  display:flex;
  align-items:center;
  pointer-events:all;
}

.logo-container .ka-logo {
  width: 24px;
}

.left, .right {
  display:flex;
  align-items:center;
}

.left {
  margin:0 10px;
}

.right {
  justify-content:right;
  margin:0 10px 0 auto;
}

#search-icon {
  width: 32px;
  margin-left: -44px;
  margin-top: 8px;
}

#search-bar {
  background-color: #47dcd6;
  border-radius: 4px;
  margin-left: 8px;
  border: 1px solid #47dcd6;
  padding: 12px 175px 14px 12px;
}

#expand-triangle {
  font-size: 13px;
  margin-left: 7px;
  color: #85e8e3;
}

.bold-signika {
  display: inline;
  font-family: 'Signika', sans-serif;
  font-size: 23px;
  color: white;
  font-weight: 600;
}

.signika {
  display: inline;
  font-family: 'Signika', sans-serif;
  color: white;
  font-size: 23px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Signika:400,600" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="main.css">
</head>

<body>
  <div class="navbar">
    <div class="left">
      <li class="navbar-text">Subjects<span id="expand-triangle">▼</span></li>
      <li id="search-bar" class="navbar-text">Search</li>
      <li><img id="search-icon" src="search.png"></li>
    </div>
    <div class="logo">
      <div class="logo-container">
          <img class="ka-logo" src="leaf-green.svg">
          <div class="bold-signika">KHAN</div>
          <div class="signika">ACADEMY</div>
        </div>
    </div>
    <div class="right">
      <li class="navbar-text">New user / Sign up</li>
    </div>
  </div>

  <!--<ul class="navbar">
    <div class="left">
      <li class="navbar-text">Subjects<span id="expand-triangle">▼</span></li>
      <li id="search-bar" class="navbar-text">Search</li>
      <li><img id="search-icon" src="search.png"></li>
    </div>
    <div class="center">
      <li>
        <div id="ka">
          <img id="ka-logo" src="leaf-green.svg">
          <div class="bold-signika">KHAN</div>
          <div class="signika">ACADEMY</div>
        </div>
      </li>
    </div>
    <div class="right">
      <li id="sign" class="navbar-text">New user / Sign up</li>
    </div>
  </ul>-->
</body>

</html></code>```

Body:
html/css newbie here.

I have done some courses on html/css and now I'm testing my knowledge by attempting to copy some websites I like. Right now I'm trying my best to make Khan Academy's front page (https://www.khanacademy.org), but I've been struggling with something.

I have an
 that represents the top navigation bar of the page, and now I'm trying to center their logo (
 that is inside the navbar as a list item) to the page but using text-align: center and margin-left: auto; & margin-right: auto doesn't seem to do anything.

Here's my code:

body {
  margin: 0;
  padding: 0;
  background-image: url("https://cdn.kastatic.org/images/homepage/mountains-simple.svg");
  background-repeat: no-repeat;
  background-size: 157.75%;
  background-position-x: 50.825%;
}

li {
  display: inline-block;
}

.navbar {
  overflow: hidden;
  width: 100%;
  height: 60px;
  border-bottom-color: #68e2de;
  border-bottom-width: 1px;
  border-bottom-style: solid;
}

.navbar {
  list-style: none;
}

.navbar-text {
  color: white;
  float: left;
  font-weight: 400;
  font-family: 'Montserrat', sans-serif;
  font-weight: 500;
  font-size: 17px;
  padding: 13px 38px 0px 4px;
  margin-left: -8px;
}

#ka {
  display: inline-block;
}

#ka-logo {
  float: left;
  width: 24px;
  margin-left: auto;
  margin-right: auto;
}

#search-icon {
  width: 32px;
  margin-left: -44px;
  margin-top: 8px;
}

#search-bar {
  background-color: #47dcd6;
  border-radius: 4px;
  margin-left: 8px;
  border: 1px solid #47dcd6;
  padding: 12px 175px 14px 12px;
}

#expand-triangle {
  font-size: 13px;
  margin-left: 7px;
  color: #85e8e3;
}

.bold-signika {
  display: inline;
  font-family: 'Signika', sans-serif;
  font-size: 23px;
  color: white;
  font-weight: 600;
}

.signika {
  display: inline;
  font-family: 'Signika', sans-serif;
  color: white;
  font-size: 23px;
}

#sign {
  float: right;
  margin-right: 44px;
}

<!DOCTYPE html>

  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Signika:400,600" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="main.css">

Subjects▼

Search

KHAN

ACADEMY

New user / Sign up

I have seem this question but what was suggested didn't work for me.

My question is: how do I center the logo div?

A side note: since I'm fairly new to html there could be a lot of bad practices in the code above. Tips on how to do the things I did more efficiently would be highly appreciated.

Body:
here a solution for your problem.

In CSS, flex is very usefull, take a look at:

Flex guide https://css-tricks.com/snippets/css/a-guide-to-flexbox/

My CSS

I have used flexbox for centered verically divs and set the right div.

For the logo, I used a first div with the height and width of the taskbar (non-clickable) and a second with the logo centered (clickable) with position absolute.

Enjoy

body {
  margin: 0;
  padding: 0;
  background-image: url("https://cdn.kastatic.org/images/homepage/mountains-simple.svg");
  background-repeat: no-repeat;
  background-size: 157.75%;
  background-position-x: 50.825%;
}

li {
  display: inline-block;
}

.navbar {
  overflow: hidden;
  width: 100%;
  height: 60px;
  border-bottom-color: #68e2de;
  border-bottom-width: 1px;
  border-bottom-style: solid;

  display: flex;
  align-items:center;
  position:absolute;
}

.navbar {
  list-style: none;
}

.navbar-text {
  color: white;
  float: left;
  font-family: 'Montserrat', sans-serif;
  font-weight: 500;
  font-size: 17px;
  /**padding: 0 38px 0px 4px;**/
}

.logo {
  position:absolute;
  height:100%;
  top:0;
  left:0;
  width:100%;
  display:flex;
  justify-content:center;
  align-items:center;
  pointer-events:none;
}

.logo-container {
  display:flex;
  align-items:center;
  pointer-events:all;
}

.logo-container .ka-logo {
  width: 24px;
}

.left, .right {
  display:flex;
  align-items:center;
}

.left {
  margin:0 10px;
}

.right {
  justify-content:right;
  margin:0 10px 0 auto;
}

#search-icon {
  width: 32px;
  margin-left: -44px;
  margin-top: 8px;
}

#search-bar {
  background-color: #47dcd6;
  border-radius: 4px;
  margin-left: 8px;
  border: 1px solid #47dcd6;
  padding: 12px 175px 14px 12px;
}

#expand-triangle {
  font-size: 13px;
  margin-left: 7px;
  color: #85e8e3;
}

.bold-signika {
  display: inline;
  font-family: 'Signika', sans-serif;
  font-size: 23px;
  color: white;
  font-weight: 600;
}

.signika {
  display: inline;
  font-family: 'Signika', sans-serif;
  color: white;
  font-size: 23px;
}

<!DOCTYPE html>
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Signika:400,600" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="main.css">
</head>

<body>
  <div class="navbar">
    <div class="left">
      <li class="navbar-text">Subjects<span id="expand-triangle">▼</span></li>
      <li id="search-bar" class="navbar-text">Search</li>
      <li><img id="search-icon" src="search.png"></li>
    </div>
    <div class="logo">
      <div class="logo-container">
          <img class="ka-logo" src="leaf-green.svg">
          <div class="bold-signika">KHAN</div>
          <div class="signika">ACADEMY</div>
        </div>
    </div>
    <div class="right">
      <li class="navbar-text">New user / Sign up</li>
    </div>
  </div>

  <!--<ul class="navbar">
    <div class="left">
      <li class="navbar-text">Subjects<span id="expand-triangle">▼</span></li>
      <li id="search-bar" class="navbar-text">Search</li>
      <li><img id="search-icon" src="search.png"></li>
    </div>
    <div class="center">
      <li>
        <div id="ka">
          <img id="ka-logo" src="leaf-green.svg">
          <div class="bold-signika">KHAN</div>
          <div class="signika">ACADEMY</div>
        </div>
      </li>
    </div>
    <div class="right">
      <li id="sign" class="navbar-text">New user / Sign up</li>
    </div>
  </ul>-->
</body>

</html>


问:
how can print data from database in javascript
i want to print date column from database in javascript code

this is the original javascript code i want to change date countdown

```<code><script type="text/javascript">
 $(document).ready(function() {
 $('#countdown').countdown('2017/07/10 06:32:11', function(event) {
 $(this).html(event.strftime('%H:%M:%S'));
 });

});
</script>
</code>```

and this code after edit :

```<code><?php
$count = $DB_con->prepare("SELECT * FROM `auction` WHER ORDER BY id DESC");
$count->execute();
foreach ($count->fetchAll() as $rowL)
{
?>
 <script type="text/javascript">
 $(document).ready(function() {
  var countdw;
  countdw = = <?php echo $rowL['dateauction']; ?>
 $('#countdown').countdown(document.write(countdw), function(event) {
$(this).html(event.strftime('%H:%M:%S'));
});

});
</script>
<?php
}
?>
</code>```

答:
If you only have one value from the database, you don't need to loop anything, although I can't imagine you have one whole table dedicated to one row unless you have a bunch of rows chronicled, in which case you probably should limit to one row to return. At any rate, it's likely it should look something more like this:</p>

```<code><?php
# You probably just need to limit 1 and only select the column you need
$query = $DB_con->prepare("SELECT `dateauction` FROM `auction` ORDER BY id DESC LIMIT 1");
$query->execute();
# Just fetch without a loop
$row = $query->fetch(PDO::FETCH_ASSOC);
?>
<script type="text/javascript">
$(document).ready(function() {
    // You should probably have quotes and a semicolon, also only one equal sign
    var countdw = '<?php echo $row['dateauction'] ?>';
    $('#countdown').countdown(document.write(countdw), function(event) {
        $(this).html(event.strftime('%H:%M:%S'));
    });
});
</script>
</code>```

Body:
i want to print date column from database in javascript code

this is the original javascript code i want to change date countdown

and this code after edit :

<?php
$count = $DB_con->prepare("SELECT * FROM `auction` WHER ORDER BY id DESC");
$count->execute();
foreach ($count->fetchAll() as $rowL)
{
?>

<?php
}
?>

Body:
If you only have one value from the database, you don't need to loop anything, although I can't imagine you have one whole table dedicated to one row unless you have a bunch of rows chronicled, in which case you probably should limit to one row to return. At any rate, it's likely it should look something more like this:

<?php
# You probably just need to limit 1 and only select the column you need
$query = $DB_con->prepare("SELECT `dateauction` FROM `auction` ORDER BY id DESC LIMIT 1");
$query->execute();
# Just fetch without a loop
$row = $query->fetch(PDO::FETCH_ASSOC);
?>
<script type="text/javascript">
$(document).ready(function() {
    // You should probably have quotes and a semicolon, also only one equal sign
    var countdw = '<?php echo $row['dateauction'] ?>';
    $('#countdown').countdown(document.write(countdw), function(event) {
        $(this).html(event.strftime('%H:%M:%S'));
    });
});
</script>


问:
How to wait for my remote script complete , which is triggered by paramiko module
I was trying to execute a python script in my remote machine
The remote command will take 1 minute to complete [ it is a python script, just print something in a loop]

I am seeing my thread throws the command and come out immediately.
I want my thread to wait till it  the remote script completes.

is there a way for this?

```<code>class Thread_cls(threading.Thread):
def __init__(self,tid,tname,ip,script):
    threading.Thread.__init__(self)
    print 'kkk'
    self.thread_id=tid
    self.thread_name=tname
    self.ip=ip
    self.script=script
def run(self):

    print "ENTERED HERE"
    stdin,stdout,stderr=self.connect_to_linux_vm(self.ip).exec_command(self.script)
    exit_status = stdout.channel.recv_exit_status()
    print "out of ssh command"
    #pass
def connect_to_linux_vm(self,ip,uname=None,password=None):
    ssh_linux = paramiko.SSHClient()
    ssh_linux.set_missing_host_key_policy(
    paramiko.AutoAddPolicy())

    ssh_linux.connect(ip, username=uname,
            password=pwd)

    return ssh_linux

obj1=Thread_cls(1,'T1','x.x.x.x',"python TEST.py")
obj1.start()
obj1.join()
</code>```

答:
Change the line

```<code>stdin, stdout, stderr = self.connect_to_linux_vm(self.ip).exec_command(self.script)
</code>```

to two lines:

```<code>ssh = self.connect_to_linux_vm(self.ip)
stdin, stdout, stderr = ssh.exec_command(self.script)
</code>```

otherwise the SSHClient object returned from connect_to_linux_vm() would be immediately destroyed after it invokes exec_command() since there's no other vars still referenceing to it.

Body:
I was trying to execute a python script in my remote machine
The remote command will take 1 minute to complete [ it is a python script, just print something in a loop]

I am seeing my thread throws the command and come out immediately.
I want my thread to wait till it  the remote script completes.

is there a way for this?

class Thread_cls(threading.Thread):
def __init__(self,tid,tname,ip,script):
    threading.Thread.__init__(self)
    print 'kkk'
    self.thread_id=tid
    self.thread_name=tname
    self.ip=ip
    self.script=script
def run(self):

    print "ENTERED HERE"
    stdin,stdout,stderr=self.connect_to_linux_vm(self.ip).exec_command(self.script)
    exit_status = stdout.channel.recv_exit_status()
    print "out of ssh command"
    #pass
def connect_to_linux_vm(self,ip,uname=None,password=None):
    ssh_linux = paramiko.SSHClient()
    ssh_linux.set_missing_host_key_policy(
    paramiko.AutoAddPolicy())

    ssh_linux.connect(ip, username=uname,
            password=pwd)

    return ssh_linux

obj1=Thread_cls(1,'T1','x.x.x.x',"python TEST.py")
obj1.start()
obj1.join()

Body:
Change the line

stdin, stdout, stderr = self.connect_to_linux_vm(self.ip).exec_command(self.script)

to two lines:

ssh = self.connect_to_linux_vm(self.ip)
stdin, stdout, stderr = ssh.exec_command(self.script)

otherwise the SSHClient object returned from connect_to_linux_vm() would be immediately destroyed after it invokes exec_command() since there's no other vars still referenceing to it.


问:
PHP prepare statement for COUNT() with condition for one result
Counting number of failed login attempt for last 2 hours with IP addresses.
But following bind_param code section showing error.

Call to a member function bind_param() on boolean

Here is the code:

```<code> $ipp = $_SERVER['REMOTE_ADDR'];
 $flood_count = $mysqli->query("SELECT COUNT(f_ip) FROM flood WHERE f_ip = ?
   AND f_time > NOW()-INTERVAL 2 HOUR ");
                 $flood_count->bind_param('s',$ipp);
                 $flood_count->execute();
                   $flood_count->store_result();
                  $flood_count->bind_result($count_data);
                  $flood_count->fetch();
                  echo $count_data;
</code>```

Testing it on local host where ip address is '::1'

答:
on line 2:  $mysqli->prepare( ..... )

query tries to execute directly. prepare is what you need to bind the parameters

Body:
Counting number of failed login attempt for last 2 hours with IP addresses.
But following bind_param code section showing error.

Call to a member function bind_param() on boolean

Here is the code:

 $ipp = $_SERVER['REMOTE_ADDR'];
 $flood_count = $mysqli->query("SELECT COUNT(f_ip) FROM flood WHERE f_ip = ?
   AND f_time > NOW()-INTERVAL 2 HOUR ");
                 $flood_count->bind_param('s',$ipp);
                 $flood_count->execute();
                   $flood_count->store_result();
                  $flood_count->bind_result($count_data);
                  $flood_count->fetch();
                  echo $count_data;

Testing it on local host where ip address is '::1'


问:
How to hide Windows Desktop and change desktop background color in c#?
I need to know how to hide Windows Desktop and change desktop background color in c# and restore the previous configuration.

Any idea?

BR

答:
Enumerate all desktop window with EnumWindows. Collect every visible window handle.

Call ShowWindow with appropriate arguments to make the collected windows to be visible/invisible.

Take note that all created windows after this operation will be visible. To hide desktop icons you shall spy the window structure (with a tool like Spy++), get specific window handle by its class name and then call ShowWindow on the obtained widnow handle.

Of course, EnumWindows and ShowWindow must be P/Invoked. See www.pinvoke.net for getting the correct declaration.


问:
Execute a block only when a code has not been executed in 3 seconds
I want to implement a promise in my code to run  angular.bootstrap() in block 2 if 3 seconds has passed and angular.bootstrap() in block 1 has not been done, but only if.

I have two blocks of code:

```<code>// block 1:
Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    })
}

// block 2:
$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
})
</code>```

Does anyone know how to do this?

Edit 1: Just to clarify that it is possible that Office.initialize is never executed (ie, when the app is loaded in Office as an add-in). In this case, I still want to execute angular.bootstrap of block 2 in 3 seconds.

答:
This solution uses underscorejs once function. Write a function like,

```<code>var bootstrapInit = _.once(function(){
angular.bootstrap(document, ['myApp']);
});
</code>```

Now, you can call this function in block 1, block 2 and setTimeout with 3 sec. Whichever invokes this first will execute the function and the remaining call will be dummy one.

Body:
I want to implement a promise in my code to run  angular.bootstrap() in block 2 if 3 seconds has passed and angular.bootstrap() in block 1 has not been done, but only if.

I have two blocks of code:

// block 1:
Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    })
}

// block 2:
$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
})

Does anyone know how to do this?

Edit 1: Just to clarify that it is possible that Office.initialize is never executed (ie, when the app is loaded in Office as an add-in). In this case, I still want to execute angular.bootstrap of block 2 in 3 seconds.

Body:
This solution uses underscorejs once function. Write a function like,

var bootstrapInit = _.once(function(){
angular.bootstrap(document, ['myApp']);
});

Now, you can call this function in block 1, block 2 and setTimeout with 3 sec. Whichever invokes this first will execute the function and the remaining call will be dummy one.


问:
Create Resource in .java file
Can I create and modify Resource like layout or TextView in activity (.java file) but not in Res folder ? In normal, I have to create it in Res and link to activity by their id. </p>

答:
Yes, you can dynamically create your views and inflate them using LayoutInflater in your java code.
If you already have xml file with you, you can use this http://37.46.125.53/xmltojava/ to convert it to java code.

For example:

XML layout:

```<code><TextView
    android:layout_width="20dp">
</TextView>
</code>```

Java code:

```<code>TextView textview = new TextView();
textview.setWidth(30); // needs to be calculated based on certain conditions
</code>```

Title: Create Resource in .java file

Body:
Yes, you can dynamically create your views and inflate them using LayoutInflater in your java code.
If you already have xml file with you, you can use this http://37.46.125.53/xmltojava/ to convert it to java code.

For example:

XML layout:

<TextView
    android:layout_width="20dp">
</TextView>

Java code:

TextView textview = new TextView();
textview.setWidth(30); // needs to be calculated based on certain conditions


问:
Can not account for an extra line in output
There is something wrong with I/O of the following code.Just after I enter the t, i get an output line, which I can not account for, I am a beginner, and this is so frustrating. Please have a look.</p>

```<code>#include<bits/stdc++.h>

using namespace std;

int main()
{
    string name;
    string sname;
    int t;
    cin>>t;
while(t--)
{

    getline(cin,name);
    *(name.begin())-=32;
    if(name.find(" ")==-1)
    {
        cout<<name;
    }

    *(name.begin()+name.find(" "))=49;
    if(name.find(" ")==-1)
    {
            *(name.begin()+name.find("1")+1)-=32;
            sname=name.substr(name.find("1")+1);
            cout<<*(name.begin())<<"."<<" "<<sname;
    }
    else
    {
        *(name.begin()+name.find("1")+1)-=32;
        *(name.begin()+name.find(" ")+1)-=32;
        sname=name.substr(name.find(" ")+1);
        cout<<*(name.begin())<<"."<<" "<<*(name.begin()+name.find("1")+1)<<"."<<" "<<sname;
    }
    printf("\n");
}
return 0;
}
</code>```

答:
Okay so, I don't really think there is any error, but I will propose you a modified version of your code, which will be more readable, more efficient, and less error prone:

```<code>// #include<bits/stdc++.h> I don't know what that include is, use more specific header based on your needs like
#include <string> // for std::string
#include <iostream> // for std::cout

// using namespace std;
// Avoid using "using namespace", it's a really bad practice in C++

int main()
{
  std::string name;
  std::string sname;
  int t;

  std::cin >> t;

  while(t--)
    {
      std::getline(std::cin, name);

      // *(name.begin()) -= 32;
      // Use operator[], it was made for that purpose
      name[0] -= 32;

      size_t pos = name.find(" ");

      if(pos == std::string::npos)
        {
          std::cout << name;
        }

      name[pos] = 49; // pretty dangerous since pos could be std::string::npos, which is the max value for a size_t

      pos = name.find(" ");

      size_t first_one = name.find("1");

      // here you should check if first_one != std::string::npos

      if(pos == std::string::npos)
        {
          name[first_one + 1] -= 32;
          sname = name.substr(name.find("1") + 1); // dangerous
          std::cout << name[0] << ". " << sname;
        }
        else
        {
          name[first_one + 1] -= 32;
          name[pos + 1] -= 32;
          sname = name.substr(name.find(" ")+1); // dangerous too
          std::cout << name[0] << ". " << name[name.find("1")+1] << ". " << sname;
        }
      // printf("\n"); Avoid using printf, std::cout is here for c++ (printf comes from C)
      std::cout << '\n';
    }
  return 0;
}
</code>```

So to conclude, avoid "using namespace", that's bad, for explanation, google, first link, etc..
Use websites like cppreference.com or cplusplus.com to see methods and usages of objects like std::string or std::cout.
Avoid doing std::cout << "a" << "b";, instead do std::cout << "ab";, or if you need to output single chars, std::cout << 'a';.

Verify everything, a big and very important rule for devs is "Never trust the user", always imagine they are gonna try to break your program, you might think "yeah but i will be the only user", that's a bad reason, take good habits early. So always check, here if t is negative, your program will be almost infinite, if there is no space or '1', it will explode, etc.. All of these small mistakes might be security flaws in bigger software.

Good luck :)

Body:
There is something wrong with I/O of the following code.Just after I enter the t, i get an output line, which I can not account for, I am a beginner, and this is so frustrating. Please have a look.

#include<bits/stdc++.h>

using namespace std;

int main()
{
    string name;
    string sname;
    int t;
    cin>>t;
while(t--)
{

    getline(cin,name);
    *(name.begin())-=32;
    if(name.find(" ")==-1)
    {
        cout<<name;
    }

    *(name.begin()+name.find(" "))=49;
    if(name.find(" ")==-1)
    {
            *(name.begin()+name.find("1")+1)-=32;
            sname=name.substr(name.find("1")+1);
            cout<<*(name.begin())<<"."<<" "<<sname;
    }
    else
    {
        *(name.begin()+name.find("1")+1)-=32;
        *(name.begin()+name.find(" ")+1)-=32;
        sname=name.substr(name.find(" ")+1);
        cout<<*(name.begin())<<"."<<" "<<*(name.begin()+name.find("1")+1)<<"."<<" "<<sname;
    }
    printf("\n");
}
return 0;
}

Body:
Okay so, I don't really think there is any error, but I will propose you a modified version of your code, which will be more readable, more efficient, and less error prone:

// #include<bits/stdc++.h> I don't know what that include is, use more specific header based on your needs like
#include <string> // for std::string
#include <iostream> // for std::cout

// using namespace std;
// Avoid using "using namespace", it's a really bad practice in C++

int main()
{
  std::string name;
  std::string sname;
  int t;

  std::cin >> t;

  while(t--)
    {
      std::getline(std::cin, name);

      // *(name.begin()) -= 32;
      // Use operator[], it was made for that purpose
      name[0] -= 32;

      size_t pos = name.find(" ");

      if(pos == std::string::npos)
        {
          std::cout << name;
        }

      name[pos] = 49; // pretty dangerous since pos could be std::string::npos, which is the max value for a size_t

      pos = name.find(" ");

      size_t first_one = name.find("1");

      // here you should check if first_one != std::string::npos

      if(pos == std::string::npos)
        {
          name[first_one + 1] -= 32;
          sname = name.substr(name.find("1") + 1); // dangerous
          std::cout << name[0] << ". " << sname;
        }
        else
        {
          name[first_one + 1] -= 32;
          name[pos + 1] -= 32;
          sname = name.substr(name.find(" ")+1); // dangerous too
          std::cout << name[0] << ". " << name[name.find("1")+1] << ". " << sname;
        }
      // printf("\n"); Avoid using printf, std::cout is here for c++ (printf comes from C)
      std::cout << '\n';
    }
  return 0;
}

So to conclude, avoid "using namespace", that's bad, for explanation, google, first link, etc..
Use websites like cppreference.com or cplusplus.com to see methods and usages of objects like std::string or std::cout.
Avoid doing std::cout << "a" << "b";, instead do std::cout << "ab";, or if you need to output single chars, std::cout << 'a';.

Verify everything, a big and very important rule for devs is "Never trust the user", always imagine they are gonna try to break your program, you might think "yeah but i will be the only user", that's a bad reason, take good habits early. So always check, here if t is negative, your program will be almost infinite, if there is no space or '1', it will explode, etc.. All of these small mistakes might be security flaws in bigger software.

Good luck :)


问:
How to enable mobile Data?
I am making an android app that provide a location for user for emergency situations . Now I want the app to enable the mobile data when the user open the app .. thanks in advance </p>

答:
Unless you have a rooted phone I don't think you can enable and disable data programmatically because in order to do so we have to include MODIFY_PHONE_STATE permission which is only given to system or signature apps.

setMobileDataEnabled() method is no longer callable via reflection. It was callable since Android 2.1 (API 7) to Android 4.4 (API 19) via reflection, but as of Android 5.0 and later, even with the rooted phones, the setMobileDataEnabled() method is not callable.

Title: How to enable mobile Data?


问:
Using a string argument to represent an object
If I have the following code:

```<code>TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}
</code>```

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.

答: You will have to pass the page into the function, otherwise in what context is the function going to search for the control? The you can use Page,FindControl() method to find the control.</p>

Body:
If I have the following code:

TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.