问:
list.append in python 3: nonetype is not iterable?
I am trying to add every word in romeo.txt to an empty list.

I thought this code was okay but python3 returns a traceback saying

File "test.py", line 13, in <module>
      if i in lst:
  TypeError: argument of type 'NoneType' is not iterable

here's my code:

```<code>fh = open("romeo.txt")
lst = list()
words = fh.read()
list1 = words.split()
for i in list1:
    if i in lst:
        continue
    else:
        lst = lst.append(i)
lst = lst.sort()
print(lst)
</code>```

答:
Hello Maxine Mou,

Python 3 learning for best website,

1. https://www.tutorialspoint.com/python3/

2. https://docs.python.org/3/tutorial/

3. https://learnpythonthehardway.org/python3/

Difference between python 2 and python 3,

1. http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html

2. https://www.quora.com/What-are-the-major-differences-between-Python-2-and-Python-3

The close() Method

The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.

Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

Syntax

```<code>fileObject.close();
</code>```

Your Mistake

  When you write below function so it is not proper way because python is understood like as iterable object so you get error so only write lst.append(i).

lst = lst.append(i)

Second mistake same as first. If you are sorting the list using sort() function so don't need to store in any variable because Python is sorting in existing list. So only write lst.sort().

lst = lst.sort()

Try this below code,

```<code>    #Open File using open() file function
    fh = open("test.txt")
    lst = list()
    words = fh.read()
    list1 = words.split()

    for item in list1:
        if item in lst:
            continue
        else:
            lst.append(item)

    #List sorting using sort() function
    lst.sort()

    #Display the sorting list
    print(lst)

    # Close the file using close() method
    fh.close()
</code>```

I hope my answer is helpful. If any query so please comment.

Body:
I am trying to add every word in romeo.txt to an empty list.

I thought this code was okay but python3 returns a traceback saying

File "test.py", line 13, in <module>
      if i in lst:
  TypeError: argument of type 'NoneType' is not iterable

here's my code:

fh = open("romeo.txt")
lst = list()
words = fh.read()
list1 = words.split()
for i in list1:
    if i in lst:
        continue
    else:
        lst = lst.append(i)
lst = lst.sort()
print(lst)

Body:
Hello Maxine Mou,

Python 3 learning for best website,

1. https://www.tutorialspoint.com/python3/

2. https://docs.python.org/3/tutorial/

3. https://learnpythonthehardway.org/python3/

Difference between python 2 and python 3,

1. http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html

2. https://www.quora.com/What-are-the-major-differences-between-Python-2-and-Python-3

The close() Method

The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.

Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

Syntax

fileObject.close();

Your Mistake

  When you write below function so it is not proper way because python is understood like as iterable object so you get error so only write lst.append(i).

lst = lst.append(i)

Second mistake same as first. If you are sorting the list using sort() function so don't need to store in any variable because Python is sorting in existing list. So only write lst.sort().

lst = lst.sort()

Try this below code,

    #Open File using open() file function
    fh = open("test.txt")
    lst = list()
    words = fh.read()
    list1 = words.split()

    for item in list1:
        if item in lst:
            continue
        else:
            lst.append(item)

    #List sorting using sort() function
    lst.sort()

    #Display the sorting list
    print(lst)

    # Close the file using close() method
    fh.close()

I hope my answer is helpful. If any query so please comment.


来源: stackexchange

问:
Simple “Hello World” in ReactJS not working
I am not getting hello world as an output. Can anyone tell me what i am missing  , its a basic code , got an output in a different way using createElement function. I am new to react.

Code:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>My First App</title>
    </head>
    <body>
        <div id="react-app"></div>
        <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
        <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>

        <script type="text/jsx">

            class StoryBox extends React.Component{
                render(){
                    return(<div> Hello World </div> );
                }
            }

            var target= document.getElementById('react-app')
            ReactDOM.render(<StoryBox>,target);
        </script>
    </body>
</html>
</code>```

答:
You need to include a JSXTransformer in order to be able to execute raw JSX. Try running the code below:

```<code><div id="react-app">
</div>

<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>

<script type="text/jsx">
  class StoryBox extends React.Component{
    render(){
      return(<div> Hello World </div> );
    }
  }
  ReactDOM.render(<StoryBox />, document.getElementById('react-app'))
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am not getting hello world as an output. Can anyone tell me what i am missing  , its a basic code , got an output in a different way using createElement function. I am new to react.

Code:

<!DOCTYPE html>

        <title>My First App</title>

Body:
You need to include a JSXTransformer in order to be able to execute raw JSX. Try running the code below:

<div id="react-app">
</div>

<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>

<script type="text/jsx">
  class StoryBox extends React.Component{
    render(){
      return(<div> Hello World </div> );
    }
  }
  ReactDOM.render(<StoryBox />, document.getElementById('react-app'))
</script>


问:
Creating a test project to test classes in another project in Android
I have a project with many classes and activities. I would like to test some of those classes by creating another project and using them. Is this possible? I tried creating an Android test project in Eclipse, linking to the project I want to test, creating an activity and there using some of those classes. Unfortunately, I get NoClassDefFoundError. Could you please address me to the right direction on how to create this kind of test?
Thanks!</p>

答:
What you are looking for is JUnit testing. There  is plenty  out there  to get  you started.

To test activities you can fire intents using ActivityInstrumentationTestCase2

ContentLicense: CC BY-SA 2.5


问:
What is difference between instantiating variable inside constructor and directly in class + Typescript / Angular
```<code>export class ReactiveFormOne {
  studentA: Student = new Student();

  studentB: Student;

  constructor (){
    this.studentB = new Student();
  }
}
</code>```

What is the fundamental difference between studentA and studentB?

答:
These are effectively identical. A class property initializer is transpiled into an equivalent assignment following the first super call, or the first statement(s) of the constructor if there is no super call.

I would recommend putting order-dependent initializations in the constructor body since future maintainers will generally be less eager to re-order statements in blocks, but may e.g. re-order initialized properties declared in the class body to conform to style guides.

Body:
export class ReactiveFormOne {
  studentA: Student = new Student();

  studentB: Student;

  constructor (){
    this.studentB = new Student();
  }
}

What is the fundamental difference between studentA and studentB?


问:
Producing a batch message
Let's say there is a batch API for performing tasks List[T]. In order to do the job all the tasks needs to be pushed to kafka. There are 2 ways to do that :

1) Pushing List as a message in kafka
2) Pushing individual task T in kafka

I believe approach 1 would be better since i don't have to push the messages to kafka mutiple times for a single batch call. Can some one please tell me if there is any harm in such approach ?

答:
A Kafka producer can batch together individual messages sent within a short time window (the particular config is linger.ms), so the cost of sending individual messages is probably a lot lower than you think.

Probably a more important factor to consider is how the consumer is going to consume messages. What should happen if the consumer cannot process one of the tasks, for example? If the consumer is just just going to call some other batch-based API which succeeds or fails as a batch, the a single message containing a list of tasks would be a perfectly good fit. On the other hand if the consumer ultimately has to process tasks individually then sending individual messages is probably a better fit, and will probably save you from having to implement some sort of retry logic in your consumer, because you can probably configure Kafka to behave with the semantics you need.

Title: Producing a batch message


问:
How can I clear all the AngularJS $scope and $rootScope values within a single function?
I need to clear all the $scope values while performing some operations.

For eg: If I Click a "Signout" button to redirect to "signin" page, then all the $scope or $rootScope values in the session should be cleared.

How can I achieve this?

答:
```<code>               You not want delete scope
               var authScope =['authLogo','currentPath','pageTitle','app'];
                for (var prop in $rootScope) {
                    if (prop.substring(0,1) !== '$') {
                        if(authScope.indexOf(prop) ==-1)
                            delete $rootScope[prop];
                    }
                }
</code>```


问:
PHP script not working as expected
My php script is woking outside function but not inside function.

```<code>$uid = $_SESSION['user_id'];
function getUserName($conn) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}
</code>```

Unable to get it where I am wrong.

答:
DO NOT use global variable. It's evil.

Pass the user ID as parameter to the function:

```<code>function getUserName($conn, $uid) {
    $sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
    $row = $conn->query($sql)->fetch_array();
    return $row["user_name"];
}

echo getUserName($conn, $_SESSION['user_id']);
</code>```

Title: PHP script not working as expected

Body:
My php script is woking outside function but not inside function.

$uid = $_SESSION['user_id'];
function getUserName($conn) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}

Unable to get it where I am wrong.

Body:
DO NOT use global variable. It's evil.

Pass the user ID as parameter to the function:

function getUserName($conn, $uid) {
    $sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
    $row = $conn->query($sql)->fetch_array();
    return $row["user_name"];
}

echo getUserName($conn, $_SESSION['user_id']);


问:
Format issue at run time in OBIEE11G
I want my cell size to be static at runtime regardless of default images, which I kept in each cell of the analysis. The problem is, I have kept an default image in each cell ,when it runs the cell's width gets enlarged automatically. Please suggest me what can be done, to keep the cell size static at run time,Cell size should not get enlarged at runtime.</p>

答:
a) It's an "analysis" and not a "report". A "report" is a completely different object type: a BI Publisher report.
b) Therein already lies your answer: Oracle provides the two distinct tools of Answers and BI Publisher because the first is used for analytical, dynamic rendering and the second for pixel-perfect, more static reporting.
c) To sum up: OBI Answers = dynamic. BIP = pixel perfect.</p>

Title: Format issue at run time in OBIEE11G


问:
'Date.parse("05/11/19")' parses in YY/MM/DD?
I have a date in string format "05/11/19" I used Date.parse, but when I use strftime("%d %b %Y"), it parsed the date as 19 Nov 2005. Is there another way to parse my string to date without messing up the day and year fields?

答:
You can pass a format String when parsing:</p>

```<code>require 'date'

datestring = '05/11/19' # 05 Nov 2019
date = Date.strptime(datestring, '%d/%m/%y')
puts date.strftime('%d %b %Y') # => 05 Nov 2019
</code>```

Body:
You can pass a format String when parsing:

require 'date'

datestring = '05/11/19' # 05 Nov 2019
date = Date.strptime(datestring, '%d/%m/%y')
puts date.strftime('%d %b %Y') # => 05 Nov 2019


问:
How to write Assertion to validate test output in Cucumber step definitions?
I am using selenium/Cucumber and junit runner class to execute my scripts.
I want to use assertion in cucumber to verify my test output, can some please write me an example how to do the same in cucumber.

As I googled, I found that people use junit/TestNG assertions like below: assertTrue(selenium.isTextPresent("Name of the Customer"));

Can I use the same assertions in cucumber test and how? Thanks!!

答:
Cucumber as such does not contain any assertion framework.

An assertion is a comparison of values. If the comparison fails, an exception is thrown. This means that you can build you own comparison or use a library such as JUnit or AssertJ. The signaling is the same, an exception is thrown and the execution of a scenario is halted.

You may be interested in a detailed example on how to use this. One that I have written and presented at Java Developer Day is available on my blog.


问:
Empty reduce output while using Custom Partitioner in MapReduce
Problem Statement:

Input

Monami 45000 A

      Tarun 34000 B

      Riju 25000 C

      Rita 42000 A

      Mithun 40000 A

      Archana 21000 C

      Shovik 32000 B

I want to use Custom Partitioner in Mapreduce to separate employee records with grade A, B and C in three different output files.

Output 1

Monami 45000 A

      Rita 42000 A

      Mithun 40000 A

Output 2

Tarun 34000 B

      Shovik 32000 B

Output 3

Riju 25000 C

      Archana 21000 C

Map Code:

```<code>import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
//import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Mapper;

public class Map
            extends Mapper<LongWritable,Text,Text,Text>
{

//private Text key1 = new Text();
//private Text value1 = new Text();

@Override
protected void map(LongWritable key,Text value,Context context)
                        throws IOException,InterruptedException
{
    String line = value.toString();
    String[] part = line.split("\t");
    int len = part.length;

    //System.out.println(len);
    if (len == 3)
    {
        context.write(new Text(part[2]), new Text(part[0]+"\t"+part[1]));
        //System.out.println(part[0]+part[1]+part[2]);
    }

}
</code>```

Partitioner Code

```<code> import org.apache.hadoop.io.Text;
 import org.apache.hadoop.mapreduce.Partitioner;

 public class CustomPartitioner
            extends Partitioner<Text,Text>
{
@Override
public int getPartition(Text key, Text value, int numReduceTasks)
    {
    if(numReduceTasks==0)
        return 0;
    if(key.equals(new Text("A")))
        return 0;
    if(key.equals(new Text("B")))
        return 1;
    else
        return 2;
    }
    }
</code>```

Reduce Code

```<code> import java.io.IOException;
 import java.util.Iterator;

 import org.apache.hadoop.io.Text;
 //import org.apache.hadoop.io.IntWritable;
 import org.apache.hadoop.mapreduce.Reducer;

 public class Reduce
                extends Reducer<Text,Text,Text,Text>
 {

@Override
protected void reduce(Text key,Iterable<Text> values,Context context)
                                        throws IOException,InterruptedException
    {
        Iterator<Text> itr = values.iterator();

        while(itr.hasNext())
        {
            context.write(new Text(itr.next().getBytes()),new Text(key));
        }

    }
   }
</code>```

Driver Class

```<code> import org.apache.hadoop.fs.Path;
//import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MapReduceDriver
{
public static void main(String[] args) throws Exception
{
    Job job = new Job();

    job.setJarByClass(MapReduceDriver.class);
    job.setJobName("Custom Partitioner");

    FileInputFormat.addInputPath(job,new Path(args[0]));
    FileOutputFormat.setOutputPath(job,new Path(args[1]));

    job.setMapperClass(Map.class);
    job.setPartitionerClass(CustomPartitioner.class);
    job.setReducerClass(Reduce.class);
    job.setNumReduceTasks(3);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);

    System.exit(job.waitForCompletion(true)?0:1);

}

}
</code>```

The code runs without any errors but three reduce output files are empty. Also when the job runs, it shows map output bytes as zero. Hence I believe the map is not generating any key-value pairs. But I cannot find out the reason. Can you help me find the mistake?

Also I have one more confusion: In Map class, when variable len is checked for > 0, then I am getting ArrayIndexOutOfBoundsException but it runs fine without any exception if checked with == 3. Why does it throw an exception with > 0 ?

答:
The problem is that your input data (as pasted here) is not tab-separated, but comma-separated. It should work fine, if you replace this line:

```<code> String[] part = line.split("\t");
</code>```

with this line:

```<code>String[] part = line.split(" ");
</code>```

The reason you are getting an exception when you check for len > 0 is that your string is not split into any sub-parts so len is 1. Then it satisfies the if condition and tries to execute something for the position 2 of parts, which does not exist.

In the existing code, len is not 3, so the code never enters the if block, hence, no exception thrown.

Body:
Problem Statement:

Input

Monami 45000 A

      Tarun 34000 B

      Riju 25000 C

      Rita 42000 A

      Mithun 40000 A

      Archana 21000 C

      Shovik 32000 B

I want to use Custom Partitioner in Mapreduce to separate employee records with grade A, B and C in three different output files.

Output 1

Monami 45000 A

      Rita 42000 A

      Mithun 40000 A

Output 2

Tarun 34000 B

      Shovik 32000 B

Output 3

Riju 25000 C

      Archana 21000 C

Map Code:

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
//import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Mapper;

public class Map
            extends Mapper<LongWritable,Text,Text,Text>
{

//private Text key1 = new Text();
//private Text value1 = new Text();

@Override
protected void map(LongWritable key,Text value,Context context)
                        throws IOException,InterruptedException
{
    String line = value.toString();
    String[] part = line.split("\t");
    int len = part.length;

    //System.out.println(len);
    if (len == 3)
    {
        context.write(new Text(part[2]), new Text(part[0]+"\t"+part[1]));
        //System.out.println(part[0]+part[1]+part[2]);
    }

}

Partitioner Code

 import org.apache.hadoop.io.Text;
 import org.apache.hadoop.mapreduce.Partitioner;

 public class CustomPartitioner
            extends Partitioner<Text,Text>
{
@Override
public int getPartition(Text key, Text value, int numReduceTasks)
    {
    if(numReduceTasks==0)
        return 0;
    if(key.equals(new Text("A")))
        return 0;
    if(key.equals(new Text("B")))
        return 1;
    else
        return 2;
    }
    }

Reduce Code

 import java.io.IOException;
 import java.util.Iterator;

 import org.apache.hadoop.io.Text;
 //import org.apache.hadoop.io.IntWritable;
 import org.apache.hadoop.mapreduce.Reducer;

 public class Reduce
                extends Reducer<Text,Text,Text,Text>
 {

@Override
protected void reduce(Text key,Iterable<Text> values,Context context)
                                        throws IOException,InterruptedException
    {
        Iterator<Text> itr = values.iterator();

        while(itr.hasNext())
        {
            context.write(new Text(itr.next().getBytes()),new Text(key));
        }

    }
   }

Driver Class

 import org.apache.hadoop.fs.Path;
//import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MapReduceDriver
{
public static void main(String[] args) throws Exception
{
    Job job = new Job();

    job.setJarByClass(MapReduceDriver.class);
    job.setJobName("Custom Partitioner");

    FileInputFormat.addInputPath(job,new Path(args[0]));
    FileOutputFormat.setOutputPath(job,new Path(args[1]));

    job.setMapperClass(Map.class);
    job.setPartitionerClass(CustomPartitioner.class);
    job.setReducerClass(Reduce.class);
    job.setNumReduceTasks(3);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);

    System.exit(job.waitForCompletion(true)?0:1);

}

}

The code runs without any errors but three reduce output files are empty. Also when the job runs, it shows map output bytes as zero. Hence I believe the map is not generating any key-value pairs. But I cannot find out the reason. Can you help me find the mistake?

Also I have one more confusion: In Map class, when variable len is checked for > 0, then I am getting ArrayIndexOutOfBoundsException but it runs fine without any exception if checked with == 3. Why does it throw an exception with > 0 ?

Body:
The problem is that your input data (as pasted here) is not tab-separated, but comma-separated. It should work fine, if you replace this line:

 String[] part = line.split("\t");

with this line:

String[] part = line.split(" ");

The reason you are getting an exception when you check for len > 0 is that your string is not split into any sub-parts so len is 1. Then it satisfies the if condition and tries to execute something for the position 2 of parts, which does not exist.

In the existing code, len is not 3, so the code never enters the if block, hence, no exception thrown.


问:
Knockout Performance - removeAll Observable Array
In my html view I bind a html table with knockout viewmodel, that contains 3 observableArrays, as following:

```<code>function myViewModel() {
    var self = this;
    self.RowIds = ko.observableArray();
    self.ColIds = ko.observableArray();

    self.allCellsList = ko.observableArray();

    self.calculateText = function (r_id, c_id) {
        console.log('calculateText');
        var item = ko.utils.arrayFirst(self.allCellsList(), function (i) {
            return i.rowId() == r_id && i.colId() == c_id;
        });
        return item.text();
    }

    self.loadData = function (rowIds, colIds, allCellsList) {

        //remove old data (not necessary, only for testing , to see how long it takes)
        self.allCellsList.removeAll();

        //populate new data:
        self.RowIds(ko.mapping.fromJS(rowIds));
        self.ColIds(ko.mapping.fromJS(colIds));
        self.allCellsList(ko.mapping.fromJS(allCellsList));
    }

}
</code>```

RowIds contains list of ids for each row in the table, CoIds  contains list of ids for each column in table.
allCellsList is the main table that holds list of objects, where each of them contain two identifiers: rowId and colId.
The function calculateText  is called in each cell in table , and calculates the matching data in allCellsList by these 2 fields.
As following:

```<code><table>
    <tbody data-bind="foreach:RowIds">
        <tr data-bind="foreach:$root.ColIds()">
            <td>
                <div data-bind="text:$root.calculateText($data , $parent)">
                </div>
            </td>
        </tr>
    </tbody>
</table>
</code>```

When I initialize the allCellsList with new data in loadData function, by removing the old data and fetching the new data (or by directly fetching the new data, without using the removeAll function) – the calculateText  function is called, For each item in the old list , and for each item in the new list.
If the old list contains a huge amount of records – the clear array operation takes too long. (sometimes 3-4 seconds)

My question is how can I populate the allCellsList in that case or in other , so that the reloading operation will be faster?
Is there a way to avoid calling the function calculateText , when allCellsList is being cleared?

Thank you.

答:
The calculateText function shouldn't be running when calling RowIds.removeAll and ColIds.removeAll. However, it will run when calling self.allCellsList.removeAll, since there's a dependency to this array.

To get only one calculation, do things in this order:

```<code>self.loadData = function (rowIds, colIds, allCellsList) {
    self.RowIds.removeAll();
    self.ColIds.removeAll();

    // You don't need this and I'd suggest you removing it
    // self.allCellsList.removeAll();

    // First load the data that `calculateText` depends on
    self.allCellsList(ko.mapping.fromJS(allCellsList));

    // Calculate for these only when added to DOM
    self.ColIds(ko.mapping.fromJS(colIds));
    self.RowIds(ko.mapping.fromJS(rowIds));

}
</code>```

Edit, to further make my point: Every time you clear vals when there is data in the DOM, you get a recalc for each cell... If you make sure there's no data in the DOM when you set vals, you only get one per cell.

var valSource = {
  a: { "1": "A1", "2": "A2", "3": "A3" },
  b: { "1": "B1", "2": "B2", "3": "B3" },
  c: { "1": "C1", "2": "C2", "3": "C3" }
};
var colSource = [{ id: "a" }, { id: "b" }, { id: "c" }];
var rowSource = [{ id: "1"   }, { id: "2" }];

var cols = ko.observableArray([]);
var rows = ko.observableArray([]);
var vals = ko.observable({});
var i = 0;

var getCellValue = function(col, row) {
  i = i + 1;
  var col = vals()[col.id] || {};
  return col[row.id];
};

var updateSlow = function() {
  // Clear
  vals({}); // Triggers a recalc for every cell
  rows([]); // Remove these freshly recalced cells...
  cols([]); // Does nothing

  // Set
  rows(rowSource.slice(0)); // Adds rows
  cols(colSource.slice(0)); // Adds cells and recalcs
  vals(Object.assign({}, valSource)); // Recalcs again

  console.log("Updates slow:", i);
  i = 0;
};

var updateFast = function() {
  // Clear
  rows([]);
  cols([]);

  // Set
  vals(Object.assign({}, valSource)); // No DOM, so no recalc
  rows(rowSource.slice(0)); // Add rows
  cols(colSource.slice(0)); // Add cells and calculate once

  console.log("Updates fast:", i);
  i = 0;
}

ko.applyBindings({ cols: cols, rows: rows, getCellValue: getCellValue, updateSlow: updateSlow});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<button data-bind="click: updateSlow">update slow</button>
<button data-bind="click: updateFast">update fast</button>

<table data-bind="foreach: rows">
  <tr data-bind="foreach: cols">
    <td data-bind="text: getCellValue($data, $parent)"></td>
  </tr>
</table></code>```

Body:
In my html view I bind a html table with knockout viewmodel, that contains 3 observableArrays, as following:

function myViewModel() {
    var self = this;
    self.RowIds = ko.observableArray();
    self.ColIds = ko.observableArray();

    self.allCellsList = ko.observableArray();

    self.calculateText = function (r_id, c_id) {
        console.log('calculateText');
        var item = ko.utils.arrayFirst(self.allCellsList(), function (i) {
            return i.rowId() == r_id && i.colId() == c_id;
        });
        return item.text();
    }

    self.loadData = function (rowIds, colIds, allCellsList) {

        //remove old data (not necessary, only for testing , to see how long it takes)
        self.allCellsList.removeAll();

        //populate new data:
        self.RowIds(ko.mapping.fromJS(rowIds));
        self.ColIds(ko.mapping.fromJS(colIds));
        self.allCellsList(ko.mapping.fromJS(allCellsList));
    }

}

RowIds contains list of ids for each row in the table, CoIds  contains list of ids for each column in table.
allCellsList is the main table that holds list of objects, where each of them contain two identifiers: rowId and colId.
The function calculateText  is called in each cell in table , and calculates the matching data in allCellsList by these 2 fields.
As following:

When I initialize the allCellsList with new data in loadData function, by removing the old data and fetching the new data (or by directly fetching the new data, without using the removeAll function) – the calculateText  function is called, For each item in the old list , and for each item in the new list.
If the old list contains a huge amount of records – the clear array operation takes too long. (sometimes 3-4 seconds)

My question is how can I populate the allCellsList in that case or in other , so that the reloading operation will be faster?
Is there a way to avoid calling the function calculateText , when allCellsList is being cleared?

Thank you.

Body:
The calculateText function shouldn't be running when calling RowIds.removeAll and ColIds.removeAll. However, it will run when calling self.allCellsList.removeAll, since there's a dependency to this array.

To get only one calculation, do things in this order:

self.loadData = function (rowIds, colIds, allCellsList) {
    self.RowIds.removeAll();
    self.ColIds.removeAll();

    // You don't need this and I'd suggest you removing it
    // self.allCellsList.removeAll();

    // First load the data that `calculateText` depends on
    self.allCellsList(ko.mapping.fromJS(allCellsList));

    // Calculate for these only when added to DOM
    self.ColIds(ko.mapping.fromJS(colIds));
    self.RowIds(ko.mapping.fromJS(rowIds));

}

Edit, to further make my point: Every time you clear vals when there is data in the DOM, you get a recalc for each cell... If you make sure there's no data in the DOM when you set vals, you only get one per cell.

var valSource = {
  a: { "1": "A1", "2": "A2", "3": "A3" },
  b: { "1": "B1", "2": "B2", "3": "B3" },
  c: { "1": "C1", "2": "C2", "3": "C3" }
};
var colSource = [{ id: "a" }, { id: "b" }, { id: "c" }];
var rowSource = [{ id: "1"   }, { id: "2" }];

var cols = ko.observableArray([]);
var rows = ko.observableArray([]);
var vals = ko.observable({});
var i = 0;

var getCellValue = function(col, row) {
  i = i + 1;
  var col = vals()[col.id] || {};
  return col[row.id];
};

var updateSlow = function() {
  // Clear
  vals({}); // Triggers a recalc for every cell
  rows([]); // Remove these freshly recalced cells...
  cols([]); // Does nothing

  // Set
  rows(rowSource.slice(0)); // Adds rows
  cols(colSource.slice(0)); // Adds cells and recalcs
  vals(Object.assign({}, valSource)); // Recalcs again

  console.log("Updates slow:", i);
  i = 0;
};

var updateFast = function() {
  // Clear
  rows([]);
  cols([]);

  // Set
  vals(Object.assign({}, valSource)); // No DOM, so no recalc
  rows(rowSource.slice(0)); // Add rows
  cols(colSource.slice(0)); // Add cells and calculate once

  console.log("Updates fast:", i);
  i = 0;
}

ko.applyBindings({ cols: cols, rows: rows, getCellValue: getCellValue, updateSlow: updateSlow});

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<button data-bind="click: updateSlow">update slow</button>
<button data-bind="click: updateFast">update fast</button>

<table data-bind="foreach: rows">
  <tr data-bind="foreach: cols">
    <td data-bind="text: getCellValue($data, $parent)"></td>
  </tr>
</table>


答:
Do these changes:

1. Include babel standalone script to transform your jsx, put the cdn links in the head part, script:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
</code>```

2. Instead of storyBox use StoryBox (capital S), check this answer for reason.

3. You forgot to close, here: <storyBox>, use this: <StoryBox />.

4. Instead of Div use div.

Check the working snippet:

<!DOCTYPE html>

      <title>My First App</title>

```

Title: Simple “Hello World” in ReactJS not working

Body:
Do these changes:

1. Include babel standalone script to transform your jsx, put the cdn links in the head part, script:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>

2. Instead of storyBox use StoryBox (capital S), check this answer for reason.

3. You forgot to close, here: <storyBox>, use this: <StoryBox />.

4. Instead of Div use div.

Check the working snippet:

<!DOCTYPE html>
<html>
   <head>
      <title>My First App</title>
      <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
      <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
   </head>

   <body>

      <div id="react-app"></div>
      <script type="text/jsx">

         class StoryBox extends React.Component{
            render(){
               return(<div> Hello World </div> );
            }
         }

        var target= document.getElementById('react-app')
        ReactDOM.render(<StoryBox/>,target)

      </script>

  </body>
</html>


问:
Angular2 for mobile development
If I use Angular2 for mobile development, could I still get access to device features like camera, GPS(location) and local device storage? For which functionalities, I'll need to know native ios/android programming?</p>

答:
You have to combine Angular with Ionic or Angular with Nativescript.
After deciding which combination you prefer check their documentation. </p>

Title: Angular2 for mobile development


问:
why android is built on a VM (Dalvik)
I am curious to know what made google choose to develop android's framework on java VM.

In the process of writing code for android for nearly 6 months now, I observed that running code on a VM in a resource limited platform is really slow. There is a lot of overhead involved. I know that java is portable etc etc, is it not possible at all to use native languages and get both performance and features offered by a VM ? For performance oriented applications one still ends up writing native code and wrap it with JNI,

So why did google choose this particular stack :

Arm based core (understandable, ARM is the best for mobile devices)

Linux (Open source)

Java VM (My question)

EDIT : I know java - JVM runs on par with C++ applications on my server, but not on android.
With respect to android its not the case - As a matter of my experience, a C++ code wrapped with JNI runs far faster than java code (note I have even checked with exact same code from a static block in java) I will agree with your answer on any other platform.

答:
Java applications have been proven(not always) to run just as quickly and smoothly as applications written in languages like c, c++, etc.  See this reference, check out the PDFs.  Many people say that java and the vm is slow without actually much proof or details - and this reference goes into some detail

Java is a widely known language and it's easy to pick up.  putting the android sdk and tools in the hands of all these people who know Java already allows the android market to have a great potential of supplying its users with a large quantity of applications.

disclaimer: i'm no expert on this matter, just my 2 cents

ContentLicense: CC BY-SA 4.0

Title: why android is built on a VM (Dalvik)


问:
arrange one below the other every 2 columns from data frame in R
Hi I have a df as below which show date and their respected

```<code>date   1_val   date  2_val  . . . .  date  n_val
  2014   23      2014  33    . . . .  2014   34
  2015   22      2016  12    . . . .  2016   99
</code>```

i have tried with hard coding to arrange the columns one below the other

```<code>for 1&2 columns
a=1
b=2
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out<-names_2

for 3&4 columns
a=3
b=4
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out1<-names_2

till n-numbers
df1= rbind(samp_out,samp_out1,......samp_out_n)
</code>```

output

```<code> date   variable   value
2014     1_val       23
2015     1_val       22
2014     2_val       33
2016     2_val       12
.
.
2014     n_val      34
2016     n_val      99
</code>```

Thanks in advance

答:
You can use stack from base R,

```<code>setNames(data.frame(stack(df[c(TRUE, FALSE)])[1],
                    stack(df[c(FALSE, TRUE)])),
       c('date', 'value', 'variable'))

#  date value variable
#1 2014    33    1_val
#2 2013    32    1_val
#3 2014    65    2_val
#4 2013    34    2_val
</code>```

Body:
Hi I have a df as below which show date and their respected

date   1_val   date  2_val  . . . .  date  n_val
  2014   23      2014  33    . . . .  2014   34
  2015   22      2016  12    . . . .  2016   99

i have tried with hard coding to arrange the columns one below the other

for 1&2 columns
a=1
b=2
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out<-names_2

for 3&4 columns
a=3
b=4
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out1<-names_2

till n-numbers
df1= rbind(samp_out,samp_out1,......samp_out_n)

output

 date   variable   value
2014     1_val       23
2015     1_val       22
2014     2_val       33
2016     2_val       12
.
.
2014     n_val      34
2016     n_val      99

Thanks in advance

Body:
You can use stack from base R,

setNames(data.frame(stack(df[c(TRUE, FALSE)])[1],
                    stack(df[c(FALSE, TRUE)])),
       c('date', 'value', 'variable'))

#  date value variable
#1 2014    33    1_val
#2 2013    32    1_val
#3 2014    65    2_val
#4 2013    34    2_val


问:
How does a compiler identify its host machine's hardware? Which component?
My teacher told me that the intermediate code is generic for all systems but a component of the compiler then make it different according the system/environment the code is run on. Can someone please explain it.</p>

答:
Normally a compiler is divided into two parts: A frontend that does the parsing, and which generates intermediate code. Then a backend which takes the intermediate code and generate the assembly or machine code.

The frontend can be generic, but the backend is built for a specific target. So the compiler doesn't have to "identify" the host, only know the target.

Note that host and target may be different systems, which is used for cross compilation.


问:
How do you add Background Image in JPanel (NetBeans GUI Builder)
I have JTabbedPane with five tabs and each have Jpanel i want add different images for each panel in NetBeans IDE</p>

答:
Change the layout of your Jframe to null.

Create a jlabel and cover whole jframe with it.

Add your image to the icon property of the inserted jlabel.

Change the layout of jframe back to free layout.
You are done
It worked for me


问:
How to add a synonym in solr which the word having comma?
Generally we map synonyms in synonyms.txt like below
           -->the,teh,eh  and so on.

But i have a synonym like below
         -->10,000, ten thousand

since the 10,000 number has comma, it is unable to map.

can anyone let me know how to add this synonym

Thanks,

Subbarao.

答: Use \ before your comma, like: 10\,000.

Body: Use \ before your comma, like: 10\,000.


问:
How to find the source of $PATH?
I'm using a Centos 7 server. I'm entering the command echo $PATH and trying to figure out where it's getting the path that it's putting out. The path doesn't match what's in my .bash_profile, and there is no .bashrc file. How do I find out where my current $PATH is being sourced from?

答:
The Default values for .bashrc and $PATH are stored in files /etc/bashrc and /etc/profile. These files are used by shell and kernel for setting default values for proper functioning of the server.

I would advise not to change any values here, as it might cause abnormal behavior in the server.

Title: How to find the source of $PATH?


问:
Open PDF blob from Angular Component
In my Angular application, I need to open a PDF when a button is clicked.

I followed the directions given by this post in the first place, so I have these two methods right now:

In the calling component

```<code>public PrepareDownload(){
   this._certificateService
            .GetPdf(args)
            .subscribe(
            result => {
                this.BlobUri = URL.createObjectURL(result);
            }
}

public Download() {
    window.open(this.BlobUri);
}
</code>```

In the service

```<code>public GetPdf() : any  {
  var headers = new Headers();
  headers.append("Content-Type", "application/json");
  var payload = {id:215};
  return this._http.post(this.requestUri,
                         JSON.stringify(payload),
                         { headers: headers,
                           responseType: ResponseContentType.Blob })
                   .map((response: Response) =>
                   {
                      return new Blob([response.blob()], { type: 'application/pdf' });
                   });
}
</code>```

GetPdf's response contains an array like the following [ 37,80,68,70,45,49,46,...]. Unfortunately, when the download method is called, the result seems to be an invalid pdf. When downloading the file via firefox and renaming it to a txt-file, I can see that the content is not binary but the complete byte array as a string.

答:
As indicated in the comments by @David Siro, The Service had to be modified.
The request now returns a stream rather than a byte array, which can be handled as described in the question.</p>

Title: Open PDF blob from Angular Component

Body:
In my Angular application, I need to open a PDF when a button is clicked.

I followed the directions given by this post in the first place, so I have these two methods right now:

In the calling component

public PrepareDownload(){
   this._certificateService
            .GetPdf(args)
            .subscribe(
            result => {
                this.BlobUri = URL.createObjectURL(result);
            }
}

public Download() {
    window.open(this.BlobUri);
}

In the service

public GetPdf() : any  {
  var headers = new Headers();
  headers.append("Content-Type", "application/json");
  var payload = {id:215};
  return this._http.post(this.requestUri,
                         JSON.stringify(payload),
                         { headers: headers,
                           responseType: ResponseContentType.Blob })
                   .map((response: Response) =>
                   {
                      return new Blob([response.blob()], { type: 'application/pdf' });
                   });
}

GetPdf's response contains an array like the following [ 37,80,68,70,45,49,46,...]. Unfortunately, when the download method is called, the result seems to be an invalid pdf. When downloading the file via firefox and renaming it to a txt-file, I can see that the content is not binary but the complete byte array as a string.


答:
Best thing you can do is avoid globals and just pass the uid as a parameter:

```<code>$uid = $_SESSION['user_id'];

$username = getUserName($conn, $uid);

function getUserName($uid, $conn) {
    $sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
    $row = $conn->query($sql)->fetch_array();
    return $row["user_name"];
}
</code>```

Read http://php.net/manual/en/language.variables.scope.php to learn about variable scope in PHP

Also read this post about SQL injection

Title: PHP script not working as expected

Body:
Best thing you can do is avoid globals and just pass the uid as a parameter:

$uid = $_SESSION['user_id'];

$username = getUserName($conn, $uid);

function getUserName($uid, $conn) {
    $sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
    $row = $conn->query($sql)->fetch_array();
    return $row["user_name"];
}

Read http://php.net/manual/en/language.variables.scope.php to learn about variable scope in PHP

Also read this post about SQL injection


问:
How to disable ActiveRecord callbacks in Rails 3?
I would like to skip/disable ActiveRecord callbacks in, specifically, Rails 3. The following is an example solution I thought of -- creating an attribute that is defined to create the object without callbacks.

```<code>product = Product.new(title: 'Smth')
product.send(:create_without_callbacks)
</code>```

The above example is similar to that in this answer, but the author said it is for specifically Rails 2. Is there a similar, or even better, way to do this for Rails 3?

答:
See the question: How can I avoid running ActiveRecord callbacks?

This blog post has another explanation with example.

Body:
I would like to skip/disable ActiveRecord callbacks in, specifically, Rails 3. The following is an example solution I thought of -- creating an attribute that is defined to create the object without callbacks.

product = Product.new(title: 'Smth')
product.send(:create_without_callbacks)

The above example is similar to that in this answer, but the author said it is for specifically Rails 2. Is there a similar, or even better, way to do this for Rails 3?


问:
How can I print a list of characters in a string using a for loop?
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

```<code>string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}
</code>```

I know this code is not correct. Can anyone help me out?

答:
If you want to write each character between A and Z, I would use this:

```<code>for (char c = 'A'; c <= 'Z'; c++)
{
    Console.WriteLine(c);
}
</code>```

That code works because char is convertible to int.

If you want to iterate over the string and write each character on its own line, I would use the string length, and then iterate over the string to get the character. There is no need to use Convert.ToChar since the indexer already returns a char.

```<code>string alpha = "A";

for(int i = 0; i < alpha.Length; i++)
{
    Console.WriteLine(alpha[i]);
}
</code>```

Body:
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}

I know this code is not correct. Can anyone help me out?

Body:
If you want to write each character between A and Z, I would use this:

for (char c = 'A'; c <= 'Z'; c++)
{
    Console.WriteLine(c);
}

That code works because char is convertible to int.

If you want to iterate over the string and write each character on its own line, I would use the string length, and then iterate over the string to get the character. There is no need to use Convert.ToChar since the indexer already returns a char.

string alpha = "A";

for(int i = 0; i < alpha.Length; i++)
{
    Console.WriteLine(alpha[i]);
}


问:
Is it possible to use ijson to create and load JSON objects in memory (not from/to a file)?
I'm trying to use ijson instead of json to be able to efficiently dump/load dictionaries to/from strings (in-memory, not from a file) [1].

Are there any examples for ijson analogous to standard dumping/loading with json? All sources I've seen that use ijson have examples with files only.

[1] -- Dictionaries are being converted to strings in order to store them in a set

答:
You can reach both goals (dict to string and string to dict without using the json lib).

Let's look at the above example:

```<code>import ast
di = {"a":2, "b": 3}

print (str(di))
>>> "{'a': 2, 'b': 3}"

print (type(str(di)))
>>> <class 'str'>

print (ast.literal_eval(str(di)))
>>> {'a': 2, 'b': 3}

print (type(ast.literal_eval(str(di))))
>>> <class 'dict'>
</code>```

You have a dictionary, In order to turn it into string, you just need to cast it into str.

If you want to return the str to dict you can use the ast lib.

You can read more about ast.literal_eval

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display.

EDIT:

After further investigation and following this SO question It seems that using json would get you to a faster results (performance).

Look at abarnert answer at the attached link, specifacally on:

Why is json.loads so much faster ?

Because Python literal syntax is a
  more complex and powerful language than JSON, it's likely to be slower
  to parse. And, probably more importantly, because Python literal
  syntax is not intended to be used as a data interchange format (in
  fact, it's specifically not supposed to be used for that), nobody is
  likely to put much effort into making it fast for data interchange.

```<code>import json
di = {"a":2, "b": 3}

print (json.dumps(di))
>>> '{"a": 2, "b": 3}'

print (type(json.dumps(di)))
>>> <class 'str'>

print (json.loads(json.dumps(di)))
>>> {'a': 2, 'b': 3}

print (type(json.loads(json.dumps(di))))
>>> <class 'dict'>
</code>```

Body:
You can reach both goals (dict to string and string to dict without using the json lib).

Let's look at the above example:

import ast
di = {"a":2, "b": 3}

print (str(di))
>>> "{'a': 2, 'b': 3}"

print (type(str(di)))
>>> <class 'str'>

print (ast.literal_eval(str(di)))
>>> {'a': 2, 'b': 3}

print (type(ast.literal_eval(str(di))))
>>> <class 'dict'>

You have a dictionary, In order to turn it into string, you just need to cast it into str.

If you want to return the str to dict you can use the ast lib.

You can read more about ast.literal_eval

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display.

EDIT:

After further investigation and following this SO question It seems that using json would get you to a faster results (performance).

Look at abarnert answer at the attached link, specifacally on:

Why is json.loads so much faster ?

Because Python literal syntax is a
  more complex and powerful language than JSON, it's likely to be slower
  to parse. And, probably more importantly, because Python literal
  syntax is not intended to be used as a data interchange format (in
  fact, it's specifically not supposed to be used for that), nobody is
  likely to put much effort into making it fast for data interchange.

import json
di = {"a":2, "b": 3}

print (json.dumps(di))
>>> '{"a": 2, "b": 3}'

print (type(json.dumps(di)))
>>> <class 'str'>

print (json.loads(json.dumps(di)))
>>> {'a': 2, 'b': 3}

print (type(json.loads(json.dumps(di))))
>>> <class 'dict'>


问:
AngularJS ng-selected
I am using the following code in my website. Everything is working fine but whenever I select a value in the first select, the second select always returns selected value as A, even if I select B in the second select. Could anyone tell me what the problem is. </p>

```<code>     <span ng-show="a.Action">Called</span><select name="First" form="{{a.ID}}" ng-model="Calling" ng-show="!a.Action">
                            <option value="">Not Called</option><option value="C">Called</option>
                    </select>
                        </td>
                        <td colspan="1">
                         <select name="Second"  form="{{a.ID}}" ng-disabled="Calling==C" ng-show="!a.Action">
                            <option value="A" ng-selected="a.Disposition == 'A'">A</option>
                            <option value="B" ng-selected="a.Disposition == 'B'">B</option>
                         </select>
                          <select name="Second"  form="{{a.ID}}"  ng-show="a.Action">
                            <option value="A" ng-selected="a.Disposition == 'A'">A</option>
                            <option value="B" selected="selected" ng-selected="a.Disposition == 'B'">B</option>
                          </select>
</code>```

<p>That is my angular code in the html file. The form is submitted to a php file, where the value of $_POST[Second] is always A whenever value in  a.Disposition is A/blank and always B if value in a.Disposition is B when the page loads. I change the default selected value in the Second select box. Yet that value does not get passed.
However, after the First select statement is removed, i.e, when a value exists in a.Action then the Second select statement works fine. Could anyone tell me why that is happening and how do I circumvent this problem? </p>

答:
In both your "select" statements you have a "ng-selected" which is responsible for the selected default value, but since you did not declare a "ng-value" the chosen value is not considered in the controller model. You should bind the select with a model using

```<code><select name="Second" ng-value="yourModel" form="{{a.ID}}" ng-disabled="Calling==C" ng-show="!a.Action">
    <option value="A" ng-selected="a.Disposition == 'A'">A</option>
    <option value="B" ng-selected="a.Disposition == 'B'">B</option>
</select>
</code>```

then the chosen value will be stored in the controller side as

```<code>$scope.yourModel
</code>```

Title: AngularJS ng-selected

Body:
I am using the following code in my website. Everything is working fine but whenever I select a value in the first select, the second select always returns selected value as A, even if I select B in the second select. Could anyone tell me what the problem is.

     Called<select name="First" form="{{a.ID}}" ng-model="Calling" ng-show="!a.Action">
                            <option value="">Not Called</option><option value="C">Called</option>
                    </select>

                         <select name="Second"  form="{{a.ID}}" ng-disabled="Calling==C" ng-show="!a.Action">
                            <option value="A" ng-selected="a.Disposition == 'A'">A</option>
                            <option value="B" ng-selected="a.Disposition == 'B'">B</option>
                         </select>
                          <select name="Second"  form="{{a.ID}}"  ng-show="a.Action">
                            <option value="A" ng-selected="a.Disposition == 'A'">A</option>
                            <option value="B" selected="selected" ng-selected="a.Disposition == 'B'">B</option>
                          </select>

That is my angular code in the html file. The form is submitted to a php file, where the value of $_POST[Second] is always A whenever value in  a.Disposition is A/blank and always B if value in a.Disposition is B when the page loads. I change the default selected value in the Second select box. Yet that value does not get passed.
However, after the First select statement is removed, i.e, when a value exists in a.Action then the Second select statement works fine. Could anyone tell me why that is happening and how do I circumvent this problem?

Body:
In both your "select" statements you have a "ng-selected" which is responsible for the selected default value, but since you did not declare a "ng-value" the chosen value is not considered in the controller model. You should bind the select with a model using

<select name="Second" ng-value="yourModel" form="{{a.ID}}" ng-disabled="Calling==C" ng-show="!a.Action">
    <option value="A" ng-selected="a.Disposition == 'A'">A</option>
    <option value="B" ng-selected="a.Disposition == 'B'">B</option>
</select>

then the chosen value will be stored in the controller side as

$scope.yourModel


问:
Is it possible to Increment/Decrement in php without using a variable?
For example: I have this code:

```<code>echo substr("1234567", -2, 1);
</code>```

This will echo: 6

I want it to echo 7 (in that case), so i can do this:

```<code>$newvar = substr("1234567", -2, 1);
echo ++$newvar;
</code>```

This will echo: 7

My problem is i have a lot of numbers to Increment, so i tried, for example:

echo ++substr("1234567", -2, 1); or echo ++(substr("1234567", -2, 1));

but that doesn't work. is it possible to some how increment the number without using a variable?

答:
What do you want to increment?

Try just adding 1, like echo substr("1234567", -2, 1)+1;

Body:
For example: I have this code:

echo substr("1234567", -2, 1);

This will echo: 6

I want it to echo 7 (in that case), so i can do this:

$newvar = substr("1234567", -2, 1);
echo ++$newvar;

This will echo: 7

My problem is i have a lot of numbers to Increment, so i tried, for example:

echo ++substr("1234567", -2, 1); or echo ++(substr("1234567", -2, 1));

but that doesn't work. is it possible to some how increment the number without using a variable?


问:
Pandas: How to properly set value defined by boolean index with value from another cell defined by boolean index?
I want to choose a value in my dataframe using boolean indexing and fill it with another value from the same dataqframe also choosen with boolean indexing.

Now the problem is of course, that I can't expect any of them to return exactly one value, and even if I can the syntax can't.

So right now I have to do something like this:

```<code>import pandas as pd
import numpy as np
L1 = ['A','A','A','A','B','B','B','B']
L2 = ['a','b','c','d','a','b','c','d']
L3 = [1,2,3,4,5,6,7,8]
df = pd.DataFrame({"L1":L1,"L2":L2,"L3":L3})

filtered = df.loc[(df.L1 == 'B')&(df.L2 == 'c'),"L3"]
if not filtered.empty:
    value = filtered.values[0]
else:
    value = np.nan
df.loc[(df.L1 == 'A')&(df.L2 == 'c'),"L3"] = value
</code>```

First I have to choose the target value which returns a series, then have to make sure that at least one value is in there and only then I can set it.

If I weren't sure that there was only one value I'd have to do consider the case of several value being returned as well and how to deal with that case.

Is there a shorter more elegant way to do this, basically a function that says "fill value where conditions XYZ are met with value where conditions ABC are met" that can be provided with a function to handle multiple values, e.g. mean or first?

答:
I think you can use Series.item if need filter only one value but unfortuntely with if else:

```<code>value = np.nan if filtered.empty else filtered.item()
</code>```

Body:
I want to choose a value in my dataframe using boolean indexing and fill it with another value from the same dataqframe also choosen with boolean indexing.

Now the problem is of course, that I can't expect any of them to return exactly one value, and even if I can the syntax can't.

So right now I have to do something like this:

import pandas as pd
import numpy as np
L1 = ['A','A','A','A','B','B','B','B']
L2 = ['a','b','c','d','a','b','c','d']
L3 = [1,2,3,4,5,6,7,8]
df = pd.DataFrame({"L1":L1,"L2":L2,"L3":L3})

filtered = df.loc[(df.L1 == 'B')&(df.L2 == 'c'),"L3"]
if not filtered.empty:
    value = filtered.values[0]
else:
    value = np.nan
df.loc[(df.L1 == 'A')&(df.L2 == 'c'),"L3"] = value

First I have to choose the target value which returns a series, then have to make sure that at least one value is in there and only then I can set it.

If I weren't sure that there was only one value I'd have to do consider the case of several value being returned as well and how to deal with that case.

Is there a shorter more elegant way to do this, basically a function that says "fill value where conditions XYZ are met with value where conditions ABC are met" that can be provided with a function to handle multiple values, e.g. mean or first?

Body:
I think you can use Series.item if need filter only one value but unfortuntely with if else:

value = np.nan if filtered.empty else filtered.item()


问:
setuptools: force version of another package (if present) while not forcing installation of this package (when not present)
During development of Pylint, we encountered interesting problem related to non-dependency that may break pylint package.

Case is following:

python-future had a conflicting alias to configparser package. Quoting official docs:

This release removes the configparser package as an alias for ConfigParser on Py2 to improve compatibility with Lukasz Langa’s backported configparser package. Previously python-future and the configparser backport clashed, causing various compatibility issues. (Issues #118, #181)

python-future itself is not a dependency of Pylint

What would be a standard way to enforce if python-future is present, force it to 0.16 or later limitation? I want to avoid defining dependency as future>=0.16 - by doing this I'd force users to install package that they don't need and won't use in a general case.

答:
There is no supported way to tell pip or setuptools that a package needs to satisfy a constraint only if installed. There might be some hacks but I imagine they'll all be fragile and likely breaking in the future versions of pip/setuptools.

Honestly, the only good way is to document it for users that future < 16.0 would break pylint, in the appropriate location in the documentation.

Making your setup.py script contain conditional dependencies is something that has been strongly discouraged for some time now. Once a wheel is built, the package is installed with the same dependency information as the wheel holds - setup.py is not run on the end-user's system, only on the packager's system, which means any setup.py hack (like @phd's) would not be useful (since pylint distributes wheels).


问:
Scaling in MathJax with respect to text direction
I'm working on a site which is in Arabic (default text direction is "right to left") and I'm using "Noto Naskh Arabic" font for arabic text and Latin-Modern for latin text which I'm definig by the following css code:

```<code>*[dir="ltr"] {
        font-size: 20px !important;
        font-family:"Latin-Modern";
}
</code>```

Users may need to enter mathematical equations and I'm using 'Mathjax' for this purpose, the problem is that:

Fractions are displayed without the horizontal line

Equations are displayed with different sizes between arabic and latin paragraph as when I write

 some text in english here $\int f(x)dx $

I have come to a slution to the first problem using css

```<code>span:lang(ar).MathJax {
    direction: ltr !important;
    font-family:"Latin-Modern";
    }
</code>```

For the second problem, I need to know if there is a way to automatically specify scale separately for equation which are embedded in Arabic paragraph end those embedded in English paragraph.

答:
It seems like the main issue is that you have to scale in the first place. I'm guessing you did that because MathJax is rendering too large in RTL contexts.

It looks like MathJax is having issues detecting the correct ex-height of the surrounding font. That can be caused by various problems, from fonts not having a correct ex-height to bad CSS interactions; from a quick test it's not the fonts.

As a workaround you can disable font matching in the MathJax configuration

```<code>MathJax.Hub.Config({
     "HTML-CSS": {matchFontHeight: false},
     SVG: {matchFontHeight: false},
     CommonHTML: {matchFontHeight: false}
});
</code>```

You should then also disable the scaling you applied.

Body:
I'm working on a site which is in Arabic (default text direction is "right to left") and I'm using "Noto Naskh Arabic" font for arabic text and Latin-Modern for latin text which I'm definig by the following css code:

*[dir="ltr"] {
        font-size: 20px !important;
        font-family:"Latin-Modern";
}

Users may need to enter mathematical equations and I'm using 'Mathjax' for this purpose, the problem is that:

Fractions are displayed without the horizontal line

Equations are displayed with different sizes between arabic and latin paragraph as when I write

 some text in english here $\int f(x)dx $

I have come to a slution to the first problem using css

span:lang(ar).MathJax {
    direction: ltr !important;
    font-family:"Latin-Modern";
    }

For the second problem, I need to know if there is a way to automatically specify scale separately for equation which are embedded in Arabic paragraph end those embedded in English paragraph.

Body:
It seems like the main issue is that you have to scale in the first place. I'm guessing you did that because MathJax is rendering too large in RTL contexts.

It looks like MathJax is having issues detecting the correct ex-height of the surrounding font. That can be caused by various problems, from fonts not having a correct ex-height to bad CSS interactions; from a quick test it's not the fonts.

As a workaround you can disable font matching in the MathJax configuration

MathJax.Hub.Config({
     "HTML-CSS": {matchFontHeight: false},
     SVG: {matchFontHeight: false},
     CommonHTML: {matchFontHeight: false}
});

You should then also disable the scaling you applied.


问:
Rails3.0.0Beta4 setting session store to database
I am porting a Rails 2.3.8 app to Rails 3.0.0Beta4.  I can't get the session to be written to the database instead of cookies.

I do the following in config/environments/development.rb:

```<code>config.session_store(:active_record_store)
</code>```

The session store is set correctly - I verify that by dumping config after the set.

What am I missing?

答:
Once you have raked, put this into your environment.rb not development.rb

config.action_controller.session_store = :active_record_store

Slotishtype

Body:
I am porting a Rails 2.3.8 app to Rails 3.0.0Beta4.  I can't get the session to be written to the database instead of cookies.

I do the following in config/environments/development.rb:

config.session_store(:active_record_store)

The session store is set correctly - I verify that by dumping config after the set.

What am I missing?


问:
Is it possible for XAML Pages (WPF App) be included in a dll?
I want to compile a series of pages (Xaml as in WPF app) in a dynamic link library but it seems that there is some limitation to include them as content and their class as something that should be compiled.
I want them(pages) to read Resources directly from DLL and I use the pages in my application.

1.Is there a way to include them in DLL's?

For more info: I should point to the main problem here. I'm writing an app that use to be a plug-able one. the question about the app is:

2. how do I add these pages to extend my app?

答:
The problem was that I was using Class libraries instead of Custom Control library or user control library.

How to build library with WPF forms


问:
How to set different background color of every three html table rows in alternate
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table></code>```

Any help is appreciated]1

答:
You can use javascript for set the background-color

```<code> $('document').ready(function(){
     $('#table1 tr').each((index, value) => {
         if(index % 3 != 0){
             value.css({'background-color': '#0000FF'});
         }else{
             value.css({'background-color': '#00FF00'});
         }
     });
});
</code>```

or define two css class

```<code>.blue {background-color: #0000FF;}
.green {background-color: #00FF00;}
</code>```

and assign this class in all tr of table you want

Body:
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    a
    b
    c

    a
    b
    c

    a
    b
    c

Any help is appreciated]1

Body:
You can use javascript for set the background-color

 $('document').ready(function(){
     $('#table1 tr').each((index, value) => {
         if(index % 3 != 0){
             value.css({'background-color': '#0000FF'});
         }else{
             value.css({'background-color': '#00FF00'});
         }
     });
});

or define two css class

.blue {background-color: #0000FF;}
.green {background-color: #00FF00;}

and assign this class in all tr of table you want


问:
Truncate table in Oracle getting errors
I got the problem is when I run following command in Oracle, I encounter the error.

```<code>Truncate table mytable;
</code>```

Errors:

```<code>ORA-02266: unique/primary keys in table referenced by enabled foreign keys
</code>```

I found that, this mytable has relationship with other tables. That's why Truncate command cannot proceed anymore. How to delete data from myTable with the SQL scripts using Truncate command?

答:
I had the similar issue and I sorted it out by the following scripts.

```<code>begin
for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
(select b.table_name from user_constraints b where b.table_name like '%BIN%')
  and  a.constraint_type not in 'P')
LOOP
  execute immediate 'alter table '||i.table_name||' disable constraint '||i.constraint_name||'';
end loop;
end;
/

truncate table TABLE_1;
truncate table TABLE_2;

begin
for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
(select b.table_name from user_constraints b where b.table_name like '%BIN%')
  and  a.constraint_type not in 'P')
LOOP
  execute immediate 'alter table '||i.table_name||' enable constraint '||i.constraint_name||'';
end loop;
end;
/
</code>```

This script will first disable all the Constraints. Truncates the data in the tables and then enable the contraints.

Hope it helps.

cheers..

Title: Truncate table in Oracle getting errors

Body:
I got the problem is when I run following command in Oracle, I encounter the error.

Truncate table mytable;

Errors:

ORA-02266: unique/primary keys in table referenced by enabled foreign keys

I found that, this mytable has relationship with other tables. That's why Truncate command cannot proceed anymore. How to delete data from myTable with the SQL scripts using Truncate command?

Body:
I had the similar issue and I sorted it out by the following scripts.

begin
for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
(select b.table_name from user_constraints b where b.table_name like '%BIN%')
  and  a.constraint_type not in 'P')
LOOP
  execute immediate 'alter table '||i.table_name||' disable constraint '||i.constraint_name||'';
end loop;
end;
/

truncate table TABLE_1;
truncate table TABLE_2;

begin
for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
(select b.table_name from user_constraints b where b.table_name like '%BIN%')
  and  a.constraint_type not in 'P')
LOOP
  execute immediate 'alter table '||i.table_name||' enable constraint '||i.constraint_name||'';
end loop;
end;
/

This script will first disable all the Constraints. Truncates the data in the tables and then enable the contraints.

Hope it helps.

cheers..


问:
C# WPF Webbrowser msHTML - Explore DOM - Find Elements
I'm actually working on a personal project in C# using WPF and WPF WebBrowser. I really need to explore html DOM Elements as we used to do in javascript or php..etc

In my MainWindow I have this variable :

```<code>private mshtml.HTMLDocument mainDocument = new mshtml.HTMLDocument();
</code>```

In my webBrowser LoadComplete callback I have this :

```<code>mainDocument = (mshtml.HTMLDocument) mainBrowser.Document;
</code>```

Ok, so this is nice, it's working.

Now if I do this :

```<code>mshtml.IHTMLElement elem = mainDocument.getElementById("MY_ID");
</code>```

it's also very nice, can do elem.innerHTML or somes stuff like that.

BUT my problem is only HTMLDocument have methodes to find elements by ID, by tagnames..etc

I don't know how to find elements in IHTMLElement. I tried some stuff like casting IHTMLElement to IHTMLElement2..etc but nothing have worked.

Please if you have any ideas. A lot of people talks about hosting winforms webbrowser but I think it must have a way to do that only with mshtml.

Thanks a lot,
If you need more information, please feel free to ask me

ps : I'm french so I'm sorry about my Engish skills

答:
If you want to parse HTML document in Winforms or wpf, you can use an excellent parser htmlagility pack. Refer to below link
http://html-agility-pack.net

```<code>  var url = "http://html-agility-pack.net/";
 var web = new HtmlWeb();
 var doc = web.Load(url);
</code>```

After loading it in doc, you can get any attribute, tag, etc.

```<code> var value = doc.DocumentNode
.SelectNodes("//td/input")
.First()
.Attributes["value"].Value;
</code>```

It's super easy, just explore the doc a bit and you can make full use of it.

You can load html agility pack even from webbrowser, like below

```<code>HtmlAgilityPack.HtmlDocument doc = new
HtmlAgilityPack.HtmlDocument();
            doc.Load(webBrowser1.DocumentStream);
</code>```

Or you can do like this

```<code>HtmlAgilityPack.HtmlDocument doc = new
HtmlAgilityPack.HtmlDocument();
            doc.Load(webBrowser1.Document);
</code>```

Thanks

Body:
I'm actually working on a personal project in C# using WPF and WPF WebBrowser. I really need to explore html DOM Elements as we used to do in javascript or php..etc

In my MainWindow I have this variable :

private mshtml.HTMLDocument mainDocument = new mshtml.HTMLDocument();

In my webBrowser LoadComplete callback I have this :

mainDocument = (mshtml.HTMLDocument) mainBrowser.Document;

Ok, so this is nice, it's working.

Now if I do this :

mshtml.IHTMLElement elem = mainDocument.getElementById("MY_ID");

it's also very nice, can do elem.innerHTML or somes stuff like that.

BUT my problem is only HTMLDocument have methodes to find elements by ID, by tagnames..etc

I don't know how to find elements in IHTMLElement. I tried some stuff like casting IHTMLElement to IHTMLElement2..etc but nothing have worked.

Please if you have any ideas. A lot of people talks about hosting winforms webbrowser but I think it must have a way to do that only with mshtml.

Thanks a lot,
If you need more information, please feel free to ask me

ps : I'm french so I'm sorry about my Engish skills

Body:
If you want to parse HTML document in Winforms or wpf, you can use an excellent parser htmlagility pack. Refer to below link
http://html-agility-pack.net

  var url = "http://html-agility-pack.net/";
 var web = new HtmlWeb();
 var doc = web.Load(url);

After loading it in doc, you can get any attribute, tag, etc.

 var value = doc.DocumentNode
.SelectNodes("//td/input")
.First()
.Attributes["value"].Value;

It's super easy, just explore the doc a bit and you can make full use of it.

You can load html agility pack even from webbrowser, like below

HtmlAgilityPack.HtmlDocument doc = new
HtmlAgilityPack.HtmlDocument();
            doc.Load(webBrowser1.DocumentStream);

Or you can do like this

HtmlAgilityPack.HtmlDocument doc = new
HtmlAgilityPack.HtmlDocument();
            doc.Load(webBrowser1.Document);

Thanks


问:
PHP script not working as expected
My php script is woking outside function but not inside function.

```<code>$uid = $_SESSION['user_id'];
function getUserName($conn) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}
</code>```

Unable to get it where I am wrong.

答: you need to call the function to work code inside funtion</p>

Title: PHP script not working as expected

Body:
My php script is woking outside function but not inside function.

$uid = $_SESSION['user_id'];
function getUserName($conn) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}

Unable to get it where I am wrong.


问:
CSS positioning of div elements
I have a form control that I'm trying to position on a page. I've used absolute positioning which works perfectly in IE. However the position is very off in Firefox. Any idea on what I may be doing wrong?</p>

```<code>#Control-wrapper {
    position:relative;
}

#Control  {
    position:absolute;
    text-align:left;
    left:100px;
    top:790px;
}

<div id="Control-wrapper">
     <div id="Control" class="HideDiv">
        <%Html.RenderPartial("MyControl")%>
      </div>
 </div>
</code>```

答:
You're nesting forms. That's forbidden.

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->

— http://www.w3.org/TR/html4/interact/forms.html#h-17.3

Title: CSS positioning of div elements

Body:
I have a form control that I'm trying to position on a page. I've used absolute positioning which works perfectly in IE. However the position is very off in Firefox. Any idea on what I may be doing wrong?

#Control-wrapper {
    position:relative;
}

#Control  {
    position:absolute;
    text-align:left;
    left:100px;
    top:790px;
}

        <%Html.RenderPartial("MyControl")%>


问:
Simple “Hello World” in ReactJS not working
I am not getting hello world as an output. Can anyone tell me what i am missing  , its a basic code , got an output in a different way using createElement function. I am new to react.

Code:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>My First App</title>
    </head>
    <body>
        <div id="react-app"></div>
        <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
        <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>

        <script type="text/jsx">

            class StoryBox extends React.Component{
                render(){
                    return(<div> Hello World </div> );
                }
            }

            var target= document.getElementById('react-app')
            ReactDOM.render(<StoryBox>,target);
        </script>
    </body>
</html>
</code>```

答:
You need to add babel as well, to transform your jsx into es5. Here is the sample code. NOTE: your cdn for react was throwing error so I have used other cdn.

```<code><html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@latest/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">

      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('root')
      );

    </script>
  </body>
</html>
</code>```

P.S. If you want to try react using npm packages here is a simple github repository to start with.

Body:
I am not getting hello world as an output. Can anyone tell me what i am missing  , its a basic code , got an output in a different way using createElement function. I am new to react.

Code:

<!DOCTYPE html>

        <title>My First App</title>

Body:
You need to add babel as well, to transform your jsx into es5. Here is the sample code. NOTE: your cdn for react was throwing error so I have used other cdn.

<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@latest/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">

      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('root')
      );

    </script>
  </body>
</html>

P.S. If you want to try react using npm packages here is a simple github repository to start with.


答:
I guess you want the output to be a list from A to Z. This code does that for you:</p>

```<code>char alpha = 'A';
for(int i=0; i <= 25 ; i++)
{
    Console.WriteLine(Convert.ToChar(alpha + i));
}
</code>```

Title: How can I print a list of characters in a string using a for loop?

Body:
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}

I know this code is not correct. Can anyone help me out?

Body:
I guess you want the output to be a list from A to Z. This code does that for you:

char alpha = 'A';
for(int i=0; i <= 25 ; i++)
{
    Console.WriteLine(Convert.ToChar(alpha + i));
}


问:
want to build web site by django for take a value by Temperature sensor on particle-Photon
i want to build an web site by djnago. this site could be able to take values from Temperature sensor which is connection with my particle-Photon. i checked the net but i do not found an compatible libary Which could be connect my Photon and django framwork. is there any helpful libary to do this .
my "Temperature.ino" code:</p>

```<code>#include <OneWire.h>
OneWire ds = OneWire(D4);  // 1-wire signal on pin D4

unsigned long lastUpdate = 0;

float lastTemp;

void setup() {
  Serial.begin(9600);
  // Set up 'power' pins, comment out if not used!
  pinMode(D3, OUTPUT);
  pinMode(D5, OUTPUT);
  digitalWrite(D3, LOW);
  digitalWrite(D5, HIGH);
}

// up to here, it is the same as the address acanner
// we need a few more variables for this example

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  // The order is changed a bit in this example
  // first the returned address is printed

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  // second the CRC is checked, on fail,
  // print error and just return to try again

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();

  // we have a good address at this point
  // what kind of chip do we have?
  // we will set a type_s value for known types or just return

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS1820/DS18S20");
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    case 0x26:
      Serial.println("  Chip = DS2438");
      type_s = 2;
      break;
    default:
      Serial.println("Unknown device type.");
      return;
  }

  // this device has temp so let's read it

  ds.reset();               // first clear the 1-wire bus
  ds.select(addr);          // now select the device we just found
  // ds.write(0x44, 1);     // tell it to start a conversion, with parasite power on at the end
  ds.write(0x44, 0);        // or start conversion in powered mode (bus finishes low)

  // just wait a second while the conversion takes place
  // different chips have different conversion times, check the specs, 1 sec is worse case + 250ms
  // you could also communicate with other devices if you like but you would need
  // to already know their address to select them.

  delay(1000);     // maybe 750ms is enough, maybe not, wait 1 sec for conversion

  // we might do a ds.depower() (parasite) here, but the reset will take care of it.

  // first make sure current values are in the scratch pad

  present = ds.reset();
  ds.select(addr);
  ds.write(0xB8,0);         // Recall Memory 0
  ds.write(0x00,0);         // Recall Memory 0

  // now read the scratch pad

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE,0);         // Read Scratchpad
  if (type_s == 2) {
    ds.write(0x00,0);       // The DS2438 needs a page# to read
  }

  // transfer and print the values

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s == 2) raw = (data[2] << 8) | data[1];
  byte cfg = (data[4] & 0x60);

  switch (type_s) {
    case 1:
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10) {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
      celsius = (float)raw * 0.0625;
      break;
    case 0:
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      // default is 12 bit resolution, 750 ms conversion time
      celsius = (float)raw * 0.0625;
      break;

    case 2:
      data[1] = (data[1] >> 3) & 0x1f;
      if (data[2] > 127) {
        celsius = (float)data[2] - ((float)data[1] * .03125);
      }else{
        celsius = (float)data[2] + ((float)data[1] * .03125);
      }
  }

  // remove random errors
  if((((celsius <= 0 && celsius > -1) && lastTemp > 5)) || celsius > 125) {
      celsius = lastTemp;
  }

  fahrenheit = celsius * 1.8 + 32.0;
  lastTemp = celsius;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

  // now that we have the readings, we can publish them to the cloud
  String temperature = String(fahrenheit); // store temp in "temperature" string
  Particle.publish("temperature", temperature, PRIVATE); // publish to cloud
  delay(5000); // 5 second delay
}
</code>```

答:
I do not have any idea about Particle-Photon but basically your .ino extension shows that your file is Arduino file.

Arduino can be connected to python via serial communication.  In Django framework you can use that serial communication to get the temperature sensor data and return your logic applied data in JSON format ( by using django rest framework ) to get back data in arduino ( in your case particle photon ).

Body:
i want to build an web site by djnago. this site could be able to take values from Temperature sensor which is connection with my particle-Photon. i checked the net but i do not found an compatible libary Which could be connect my Photon and django framwork. is there any helpful libary to do this .
my "Temperature.ino" code:

#include <OneWire.h>
OneWire ds = OneWire(D4);  // 1-wire signal on pin D4

unsigned long lastUpdate = 0;

float lastTemp;

void setup() {
  Serial.begin(9600);
  // Set up 'power' pins, comment out if not used!
  pinMode(D3, OUTPUT);
  pinMode(D5, OUTPUT);
  digitalWrite(D3, LOW);
  digitalWrite(D5, HIGH);
}

// up to here, it is the same as the address acanner
// we need a few more variables for this example

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  // The order is changed a bit in this example
  // first the returned address is printed

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  // second the CRC is checked, on fail,
  // print error and just return to try again

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();

  // we have a good address at this point
  // what kind of chip do we have?
  // we will set a type_s value for known types or just return

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS1820/DS18S20");
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    case 0x26:
      Serial.println("  Chip = DS2438");
      type_s = 2;
      break;
    default:
      Serial.println("Unknown device type.");
      return;
  }

  // this device has temp so let's read it

  ds.reset();               // first clear the 1-wire bus
  ds.select(addr);          // now select the device we just found
  // ds.write(0x44, 1);     // tell it to start a conversion, with parasite power on at the end
  ds.write(0x44, 0);        // or start conversion in powered mode (bus finishes low)

  // just wait a second while the conversion takes place
  // different chips have different conversion times, check the specs, 1 sec is worse case + 250ms
  // you could also communicate with other devices if you like but you would need
  // to already know their address to select them.

  delay(1000);     // maybe 750ms is enough, maybe not, wait 1 sec for conversion

  // we might do a ds.depower() (parasite) here, but the reset will take care of it.

  // first make sure current values are in the scratch pad

  present = ds.reset();
  ds.select(addr);
  ds.write(0xB8,0);         // Recall Memory 0
  ds.write(0x00,0);         // Recall Memory 0

  // now read the scratch pad

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE,0);         // Read Scratchpad
  if (type_s == 2) {
    ds.write(0x00,0);       // The DS2438 needs a page# to read
  }

  // transfer and print the values

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s == 2) raw = (data[2] << 8) | data[1];
  byte cfg = (data[4] & 0x60);

  switch (type_s) {
    case 1:
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10) {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
      celsius = (float)raw * 0.0625;
      break;
    case 0:
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      // default is 12 bit resolution, 750 ms conversion time
      celsius = (float)raw * 0.0625;
      break;

    case 2:
      data[1] = (data[1] >> 3) & 0x1f;
      if (data[2] > 127) {
        celsius = (float)data[2] - ((float)data[1] * .03125);
      }else{
        celsius = (float)data[2] + ((float)data[1] * .03125);
      }
  }

  // remove random errors
  if((((celsius <= 0 && celsius > -1) && lastTemp > 5)) || celsius > 125) {
      celsius = lastTemp;
  }

  fahrenheit = celsius * 1.8 + 32.0;
  lastTemp = celsius;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

  // now that we have the readings, we can publish them to the cloud
  String temperature = String(fahrenheit); // store temp in "temperature" string
  Particle.publish("temperature", temperature, PRIVATE); // publish to cloud
  delay(5000); // 5 second delay
}


答:
If you don't restricted to a for loop you could do this with a foreach as well.</p>

```<code>string alpha = "A";

foreach (var element in alpha)
{
    Console.WriteLine(element);
}
</code>```

Body:
If you don't restricted to a for loop you could do this with a foreach as well.

string alpha = "A";

foreach (var element in alpha)
{
    Console.WriteLine(element);
}


问:
Custom Transaction Column Field in Netsuite
We have created a custom field on ITEM RECORDS (for Inventory AND Non-Inventory Parts) lets call this [FIELD A]

We now want to include this field on Transactions (Sales Orders/Invoices/Purchase Orders/etc.) lets call this [FIELD B]

I know we will need a Custom Transaction Column Field, however what is the best way to format/setup that column, so that [FIELD B] = [FIELD A] by default?

Side note; we want [FIELD B] to be editable, but the changes made are not saved to [FIELD A]

答:
In your Custom Transaction Column Field [FIELD B], under the Sourcing & Filtering Tab, set the Source List dropdown value to Item, and Source From dropdown to [FIELD A].

To set it as a default value but still be editable, make sure that the Store Value checkbox is ticked on [FIELD B]. Changing [FIELD B] will not affect the value of [FIELD A].