问:
Why this give me a segfault?
Here is my code, I'm getting a segmentation fault and I don't know why... I'm creating a grid which 'n' is its size, 'tab' is an array which his type is cellule : a cell has 2 values. So I'm creating in the function 'creer_grille' an array I malloc it (size can be 4 6 or 8) and I initialize the cells values with -1 and 0. Then in the following function I'm testing the 'creer_grille' function.</p>

```<code>typedef struct
{
    int val;
    int initial;
} cellule;

typedef struct
{
    cellule  *tab;
    int      n;
} grille;

grille  *creer_grille(int n)
{
    grille *g;
  int    i;

  assert(n == 4 || n == 6 || n == 8 && "Taille de la grille différent de 4,6 ou 8");
    g->n = n;
    g = malloc(sizeof(int) * (n*n));
        if (g->tab == NULL)
                exit(-1);
    for (i = 0; i < n*n; i++)
      {
        g->tab[i].val = -1;
        g->tab[i].initial = 0;
      }
      return g;
}

void detruire_grille(grille * g)
{
  free(g);
}

void test_creer_grille(){
    int i,k;
    for(k = 4; k <= 8 ; k+=2){
        grille * g = creer_grille(k);
        assert(g->n == k && "Problème dans le champ n de la grille");

        //Vérification que les cellules sont vides
        for(i = 0 ; i < k * k ; i++){
            assert(g->tab[i].val == -1 && "Problème : cellule non vide !");
            assert(g->tab[i].initial == 0 && "Problème : cellule initiale !");
        }
        detruire_grille(g);
    }
    printf("Test de la fonction creer_grille OK !\n");
}

int    main()
{
   test_creer_grille();
}
</code>```

答:
In your creer_grille function, you declare the g pointer. As it is not initialized, it will contain garbage.

Few lines later, you try to access the n member of g (g->n). Even at this time, your g pointer is not initialized. Therefore, you try to access a garbage location which for obvious reasons will lead to a segmentation fault.

A possible fix is to allocate memory for your g pointer before using it.

g = malloc(sizeof(grille));

I suspect that your compiler might have warned you about using an uninitialized variable.

Title: Why this give me a segfault?

Body:
Here is my code, I'm getting a segmentation fault and I don't know why... I'm creating a grid which 'n' is its size, 'tab' is an array which his type is cellule : a cell has 2 values. So I'm creating in the function 'creer_grille' an array I malloc it (size can be 4 6 or 8) and I initialize the cells values with -1 and 0. Then in the following function I'm testing the 'creer_grille' function.

typedef struct
{
    int val;
    int initial;
} cellule;

typedef struct
{
    cellule  *tab;
    int      n;
} grille;

grille  *creer_grille(int n)
{
    grille *g;
  int    i;

  assert(n == 4 || n == 6 || n == 8 && "Taille de la grille différent de 4,6 ou 8");
    g->n = n;
    g = malloc(sizeof(int) * (n*n));
        if (g->tab == NULL)
                exit(-1);
    for (i = 0; i < n*n; i++)
      {
        g->tab[i].val = -1;
        g->tab[i].initial = 0;
      }
      return g;
}

void detruire_grille(grille * g)
{
  free(g);
}

void test_creer_grille(){
    int i,k;
    for(k = 4; k <= 8 ; k+=2){
        grille * g = creer_grille(k);
        assert(g->n == k && "Problème dans le champ n de la grille");

        //Vérification que les cellules sont vides
        for(i = 0 ; i < k * k ; i++){
            assert(g->tab[i].val == -1 && "Problème : cellule non vide !");
            assert(g->tab[i].initial == 0 && "Problème : cellule initiale !");
        }
        detruire_grille(g);
    }
    printf("Test de la fonction creer_grille OK !\n");
}

int    main()
{
   test_creer_grille();
}


来源: stackexchange

问:
How to add up the same 'items' in a dictionary of multiple dictionaries in Python?
How could I add up the speed of these characters even if they don't all have the attribute speed? This is an example, there are many other attributes. The characters are picked randomly and grouped together:

```<code>character_1 = {'Money': .3, 'Strength': .25, 'Speed': .05}
character_2 = {'Money': .3, 'Age': 25, 'Speed': .7}
character_3 = {'Money': .3, 'Strength': .25, 'Power': 5}
</code>```

How could I find out the combined speed, money, age etc of all these characters? (if age is not defined for others the right answer should be 25 years in total)
thank you!!

答:
Have a look at defaultdict . You could implement your characters as float defaultdicts, which gives them a 0.0 for any item that hasn't been set yet:

```<code>from collections import defaultdict

character = defaultdict(float)
</code>```

So now any first item retrieval will initialize the value with zero if it hasn't been written before:

```<code>In [7]: character["Money"]
Out[7]: 0.0

In [8]: character["Speed"]
Out[8]: 0.0
</code>```

This approach has its drawbacks for certain applications, though. Like when not all values in the dict are of numeric type, or have a different initial value. In this case, a class might be the only choice you've got, as @Anton vBR pointed out.

ContentLicense: CC BY-SA 3.0

Body:
How could I add up the speed of these characters even if they don't all have the attribute speed? This is an example, there are many other attributes. The characters are picked randomly and grouped together:

character_1 = {'Money': .3, 'Strength': .25, 'Speed': .05}
character_2 = {'Money': .3, 'Age': 25, 'Speed': .7}
character_3 = {'Money': .3, 'Strength': .25, 'Power': 5}

How could I find out the combined speed, money, age etc of all these characters? (if age is not defined for others the right answer should be 25 years in total)
thank you!!

Body:
Have a look at defaultdict . You could implement your characters as float defaultdicts, which gives them a 0.0 for any item that hasn't been set yet:

from collections import defaultdict

character = defaultdict(float)

So now any first item retrieval will initialize the value with zero if it hasn't been written before:

In [7]: character["Money"]
Out[7]: 0.0

In [8]: character["Speed"]
Out[8]: 0.0

This approach has its drawbacks for certain applications, though. Like when not all values in the dict are of numeric type, or have a different initial value. In this case, a class might be the only choice you've got, as @Anton vBR pointed out.


问:
MatLab Quadratic Equation With ln
How to solve the function f(x)=ln(x^2)-0.7=0 with a known Matlab command?

```<code>clc;clear all;close all;

f(x)=ln(x^2)-0.7=0
B=sqrt f(x)
</code>```

答:
You can use symbolic variables together with the solve function:

```<code>syms x;
eqn = log(x^2) - 0.7 == 0;
solve(eqn,x)
</code>```

The above code will output:

```<code>ans =

  exp(7/20)
 -exp(7/20)
</code>```

Since the equation is quadratic, the solver returns two distinct solutions (often people forget that quadratic equations may have two specular solutions, one positive and one negative).

If you want to retrieve the numerical values (for example, in order to calculate their sqrt value):

```<code>sol = solve(eqn,x);
num = double(sol)

num =

 1.4191
-1.4191
</code>```

Title: MatLab Quadratic Equation With ln

Body:
How to solve the function f(x)=ln(x^2)-0.7=0 with a known Matlab command?

clc;clear all;close all;

f(x)=ln(x^2)-0.7=0
B=sqrt f(x)

Body:
You can use symbolic variables together with the solve function:

syms x;
eqn = log(x^2) - 0.7 == 0;
solve(eqn,x)

The above code will output:

ans =

  exp(7/20)
 -exp(7/20)

Since the equation is quadratic, the solver returns two distinct solutions (often people forget that quadratic equations may have two specular solutions, one positive and one negative).

If you want to retrieve the numerical values (for example, in order to calculate their sqrt value):

sol = solve(eqn,x);
num = double(sol)

num =

 1.4191
-1.4191


问:
Cannot find Method inside Stream.generate().forEach()

System.out.println(GraphController.GRAPHPOOL.peek().getEdge());
    Stream.generate(() -> {
     try {
       return GraphController.GRAPHPOOL.take();
     } catch (InterruptedException ie) {
       return "Interrupted!";
     }
    })
    .forEach(g   -> {System.out.println(g.getEdge());}
    });
```

I am able to print the object Edge returned by getEdge out of Stream.generate().forEach(), however, within forEach I can access only object g.

When trying to access g.getEdge() I get an error as follows:

error: cannot find symbol

System.out.println(g.getEdge());

symbol:   method getEdge()

location: variable g of type Object

How can I access g.getEdge()?

答: You have to cast your g to the wished datatype. As you can read, the variable g is currently an Object. Simply cast it with (neededObjectforGetEdge(g)).getEdge()

Body:
System.out.println(GraphController.GRAPHPOOL.peek().getEdge());
    Stream.generate(() -> {
     try {
       return GraphController.GRAPHPOOL.take();
     } catch (InterruptedException ie) {
       return "Interrupted!";
     }
    })
    .forEach(g   -> {System.out.println(g.getEdge());}
    });

I am able to print the object Edge returned by getEdge out of Stream.generate().forEach(), however, within forEach I can access only object g.

When trying to access g.getEdge() I get an error as follows:

error: cannot find symbol

System.out.println(g.getEdge());

symbol:   method getEdge()

location: variable g of type Object

How can I access g.getEdge()?


问:
What does "asp.net" mean?
I know asp stands for Active Server Pages but wondering if "Active Server" means anything actually? </p>

答:
Microsoft have used "Active" in the past for a few products, eg; Active Directory.
Many other technologies that mix presentation and logic have also used X S)erver P)ages - eg: J)ava S)erver P)ages.</p>

OwnerDisplayName: Sesh

ContentLicense: CC BY-SA 2.5

Title: What does "asp.net" mean?

OwnerDisplayName: mP


问:
iPhone UIButton to title text?
I have a UIButton created in UIBuilder. It is set to "Custom"

In code I add the title and images. The button works, images change on the click of the button. But no text appears?

```<code>btnAddRecord.SetTitle("Add Record",UIControlState.Normal);
btnAddRecord.SetTitleColor(UIColor.White,UIControlState.Normal);
btnAddRecord.SetBackgroundImage (UIImage.FromBundle ("Images/lowerBarButton.png"), UIControlState.Normal);
btnAddRecord.SetImage (UIImage.FromBundle ("Images/lowerBarButton.png"), UIControlState.Normal);
btnAddRecord.SetImage (UIImage.FromBundle ("Images/lowerBarButtonEnabled.png"), UIControlState.Highlighted);
</code>```

答:
Your syntax seems really weird.

Try [button setTitle:@"Title" forState:UIControlStateNormal]

Title: iPhone UIButton to title text?

Body:
I have a UIButton created in UIBuilder. It is set to "Custom"

In code I add the title and images. The button works, images change on the click of the button. But no text appears?

btnAddRecord.SetTitle("Add Record",UIControlState.Normal);
btnAddRecord.SetTitleColor(UIColor.White,UIControlState.Normal);
btnAddRecord.SetBackgroundImage (UIImage.FromBundle ("Images/lowerBarButton.png"), UIControlState.Normal);
btnAddRecord.SetImage (UIImage.FromBundle ("Images/lowerBarButton.png"), UIControlState.Normal);
btnAddRecord.SetImage (UIImage.FromBundle ("Images/lowerBarButtonEnabled.png"), UIControlState.Highlighted);


问:
How do I use functions like this? ( C++, operator overloading)
```<code>#include <iostream>
using namespace std;

class VectorND
{
public:
    int N;
    VectorND(int n)
        :N(n) {}

    float *vec_value = new float[N];

    void assignValue(int i, float v)
        {
            vec_value[i] = v;
        }

};
</code>```

This is my code and I'm trying to solve this problem,
 but I do not know what to do.

Problem 4. Implement operator overloading of VectorND class for the
  following operations.

```<code>my_vec.assignValue(3) = 10;

std::cout << my_vec(3);
</code>```

Example

```<code>int main(void)
{
  VectorND my_vec(10);
    my_vec.assignValue(3) = 10;
    std::cout << my_vec(3);

    return 0;
}

Output : 10
</code>```

答:
For the first operator overload you have to do something like this:

```<code>float& operator () (int i)
{
    return vec_value[i];
}
</code>```

When you do myVec(3) = 4;, the myVec(3) returns a reference to the float at the index 3 which you then assign to 4.

For myVec.assign(3) = 10 you should overload the assign method to take an index and return a reference to a float for that index.

For the second one it is more complicated you have to do a declaration in your class friend ostream& operator << (ostream& n, VectorND& myVec);

Then outside the class:

```<code>ostream& operator<<(ostream& n, const VectorND& myVec)
{
   // This just pushes all the values to the stream
   for(int i = 0; i< N; i++) cout<<vec_value[i]<<endl;
}
</code>```

Body:
#include <iostream>
using namespace std;

class VectorND
{
public:
    int N;
    VectorND(int n)
        :N(n) {}

    float *vec_value = new float[N];

    void assignValue(int i, float v)
        {
            vec_value[i] = v;
        }

};

This is my code and I'm trying to solve this problem,
 but I do not know what to do.

Problem 4. Implement operator overloading of VectorND class for the
  following operations.

my_vec.assignValue(3) = 10;

std::cout << my_vec(3);

Example

int main(void)
{
  VectorND my_vec(10);
    my_vec.assignValue(3) = 10;
    std::cout << my_vec(3);

    return 0;
}

Output : 10

Body:
For the first operator overload you have to do something like this:

float& operator () (int i)
{
    return vec_value[i];
}

When you do myVec(3) = 4;, the myVec(3) returns a reference to the float at the index 3 which you then assign to 4.

For myVec.assign(3) = 10 you should overload the assign method to take an index and return a reference to a float for that index.

For the second one it is more complicated you have to do a declaration in your class friend ostream& operator << (ostream& n, VectorND& myVec);

Then outside the class:

ostream& operator<<(ostream& n, const VectorND& myVec)
{
   // This just pushes all the values to the stream
   for(int i = 0; i< N; i++) cout<<vec_value[i]<<endl;
}


问:
Custom error handler prints console log two/three times
I am making my own exception handler wrapper and i only used a console.log inside just to test that it works. However calling a function that doesn't exist so that i can trigger the error, prints the console.log three times.

However moving the error trigger to ngOnInit console.log two times. Which i find weird?

Note: throw Error('hello') does the same

exception.handler.ts

```<code>import { ErrorHandler, Injectable, Injector } from '@angular/core'
import { ExceptionLoggingService } from './exception-logging.service'

@Injectable()
export class ExceptionHandler implements ErrorHandler {
  constructor (private injector: Injector) { }

  handleError (error) {
    // const loggingService = this.injector.get(ExceptionLoggingService)
    // const message = error.message ? error.message : error.toString()

    console.log('hello')

    throw error
  }
}
</code>```

Using Angular v5.0.3

答:
Here is what the Angular documentation says about ErrorHandler:

The default implementation of ErrorHandler prints error messages to
  the console.

So I think if you remove throw error and simply log your message, it should be print only once in the console:

```<code>handleError (error) {
  console.log('hello');
  //throw error;
}
</code>```

Body:
I am making my own exception handler wrapper and i only used a console.log inside just to test that it works. However calling a function that doesn't exist so that i can trigger the error, prints the console.log three times.

However moving the error trigger to ngOnInit console.log two times. Which i find weird?

Note: throw Error('hello') does the same

exception.handler.ts

import { ErrorHandler, Injectable, Injector } from '@angular/core'
import { ExceptionLoggingService } from './exception-logging.service'

@Injectable()
export class ExceptionHandler implements ErrorHandler {
  constructor (private injector: Injector) { }

  handleError (error) {
    // const loggingService = this.injector.get(ExceptionLoggingService)
    // const message = error.message ? error.message : error.toString()

    console.log('hello')

    throw error
  }
}

Using Angular v5.0.3

Body:
Here is what the Angular documentation says about ErrorHandler:

The default implementation of ErrorHandler prints error messages to
  the console.

So I think if you remove throw error and simply log your message, it should be print only once in the console:

handleError (error) {
  console.log('hello');
  //throw error;
}


问:
Output of mysqli_fetch_array($data) with loop and without loop
When I used while loop to print the values of a particular column using mysqli_fetch_array(), I got the correct output from the database.

```<code>while($row=mysqli_fetch_array($data))
{
  echo $row['name'];
}
</code>```

But when I used the below mentioned code without the loop, the output was different.

```<code>   $row=mysqli_fetch_array($data);
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
</code>```

When I used the below mentioned code, I could see that I get all the rows in the form of an associative array using mysqli_fetch_array().

```<code>$con=mysqli_connect("localhost", "root", "", "student_details");
$data=mysqli_query($con,"select * from `registration`");
while ($row = mysqli_fetch_array($data))
 {
    $rec[]=$row;
 }
echo "```";
print_r($rec);
echo "```";
?>
</code>```

My question is how to get all the values of a particular column (using a while loop), without usage of any loop.

答:
You can use mysqli_fetch_all to get all data in array but you might need to use foreach for further action.

```<code>$con=mysqli_connect("localhost", "root", "", "student_details");
$data=mysqli_query($con,"select * from `registration`");
$row = mysqli_fetch_all($data, MYSQLI_ASSOC);

echo "```"; print_r($row); die;
// Will show all data coming in $row as Array
```

<p>For further processing, you might need to use foreach like below:</p>

```foreach ($row as $item) {
    print_r($item);  // see what your item contains
}
```

Body:
When I used while loop to print the values of a particular column using mysqli_fetch_array(), I got the correct output from the database.

while($row=mysqli_fetch_array($data))
{
  echo $row['name'];
}

But when I used the below mentioned code without the loop, the output was different.

   $row=mysqli_fetch_array($data);
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];
    echo $row['name'];

When I used the below mentioned code, I could see that I get all the rows in the form of an associative array using mysqli_fetch_array().

$con=mysqli_connect("localhost", "root", "", "student_details");
$data=mysqli_query($con,"select * from `registration`");
while ($row = mysqli_fetch_array($data))
 {
    $rec[]=$row;
 }
echo "
";
print_r($rec);
echo "
";
?>

My question is how to get all the values of a particular column (using a while loop), without usage of any loop.

Body:
You can use mysqli_fetch_all to get all data in array but you might need to use foreach for further action.

$con=mysqli_connect("localhost", "root", "", "student_details");
$data=mysqli_query($con,"select * from `registration`");
$row = mysqli_fetch_all($data, MYSQLI_ASSOC);

echo "<pre>"; print_r($row); die;
// Will show all data coming in $row as Array

For further processing, you might need to use foreach like below:

foreach ($row as $item) {
    print_r($item);  // see what your item contains
}


问:
Why both subclass and superclass are true while using instanceof?
Sorry that I had a mistake while posting. The class that implements I should be B rather than A in this case. And here it is where I find confusing.
Also, if it is class C that implements I rather than A or B, the results are still the same.

```<code>interface I{}

public class A{
    A() {
        System.out.print("A: " + (this instanceof I) + " ");
    }
    public static void main(String[] args) {
        new C();
    }
}

class B extends A implements I {
    B() {
        System.out.print("B: " + (this instanceof I) + " ");
    }
}

class C extends B {
    C() {
        System.out.print("C: " + (this instanceof I) + " ");
    }
}
</code>```

Why both subclass and superclass are true while using instanceof?

The result of this code is:

```<code>A: true
B: true
C: true
</code>```

答:
The instanceof operator checks whether the given object is a sublcass (not necessarily a true subclass) of the given class. This does in general mean that you can cast the object to that class (reduce the view to it).

So for example if we have an ArrayList we could cast it to List, also instanceof would return true if we check that ArrayList against List. So in your example of course you could do

```<code>new C() instanceof B // true
new B() instanceof A // true
</code>```

However the classes also inherit such properties from their parents. Thus the class C is of course also subclass of A, since it is subclass of B and B is subclass of A, so we get

```<code>new C() instanceof A // true
</code>```

And the same holds for interfaces too, we get

```<code>new A() instanceof I // true
</code>```

and by inheritance

```<code>new B() instanceof I // true
new C() instanceof I // true
</code>```

Practical example

Take a look at the following example

```<code>public interface CanBark { }

public class Dog implements CanBark { }

public class Pug extends Dog { }
</code>```

of course the Pug is a Dog and since Dog is a CanBark the Pug is also a CanBark, we get

```<code>new Pug() instanceof Dog     // true
new Dog() instanceof CanBark // true
new Pug() instanceof CanBark // true
</code>```

Details of instanceof

The Java Language Specification (§15.20.2) defines the behavior of the instanceof operator as

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

Whereas the cast (§15.16) behaves like

[...] or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.

Therefore the casting refers to the casting rules specified in (§5.5). Your specific case is defined in (§5.5.1) as

If T (target) is an interface type:

  If S (source) is not a final class (§8.1.1), then, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs.

  Otherwise, the cast is always legal at compile time (because even if S does not implement T, a subclass of S might).

Body:
Sorry that I had a mistake while posting. The class that implements I should be B rather than A in this case. And here it is where I find confusing.
Also, if it is class C that implements I rather than A or B, the results are still the same.

interface I{}

public class A{
    A() {
        System.out.print("A: " + (this instanceof I) + " ");
    }
    public static void main(String[] args) {
        new C();
    }
}

class B extends A implements I {
    B() {
        System.out.print("B: " + (this instanceof I) + " ");
    }
}

class C extends B {
    C() {
        System.out.print("C: " + (this instanceof I) + " ");
    }
}

Why both subclass and superclass are true while using instanceof?

The result of this code is:

A: true
B: true
C: true

Body:
The instanceof operator checks whether the given object is a sublcass (not necessarily a true subclass) of the given class. This does in general mean that you can cast the object to that class (reduce the view to it).

So for example if we have an ArrayList we could cast it to List, also instanceof would return true if we check that ArrayList against List. So in your example of course you could do

new C() instanceof B // true
new B() instanceof A // true

However the classes also inherit such properties from their parents. Thus the class C is of course also subclass of A, since it is subclass of B and B is subclass of A, so we get

new C() instanceof A // true

And the same holds for interfaces too, we get

new A() instanceof I // true

and by inheritance

new B() instanceof I // true
new C() instanceof I // true

Practical example

Take a look at the following example

public interface CanBark { }

public class Dog implements CanBark { }

public class Pug extends Dog { }

of course the Pug is a Dog and since Dog is a CanBark the Pug is also a CanBark, we get

new Pug() instanceof Dog     // true
new Dog() instanceof CanBark // true
new Pug() instanceof CanBark // true

Details of instanceof

The Java Language Specification (§15.20.2) defines the behavior of the instanceof operator as

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

Whereas the cast (§15.16) behaves like

[...] or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.

Therefore the casting refers to the casting rules specified in (§5.5). Your specific case is defined in (§5.5.1) as

If T (target) is an interface type:

  If S (source) is not a final class (§8.1.1), then, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs.

  Otherwise, the cast is always legal at compile time (because even if S does not implement T, a subclass of S might).


问:
choosing camera for robot vision system
I am making a robot that navigates based on vision system . vision system use the colour of the object to navigate so how I choose my camera?

答:
If you want something simple that locates objects out of the box with little customization, you might try the pixy. It's self contained microprocessor and camera that can be trained to track 7 types of color signatures and 7 color codes. It can track multiple objects at one time returning coordinates for each.

Kickstart Video,  Kickstarter,  CMUcam5 Pixy,  Adafruit

Title: choosing camera for robot vision system


问:
Problem in using STIntersects in SQL Server 2008
Using this Spatial Query I am trying to get all the country information which intersects the point 78,22. Expected result is information of "India", but this query is returning no rows.

```<code>select * from countryspatial
where
geom.STIntersects((geometry::STGeomFromText('POINT (78 22)', 4326)))>0;
</code>```

This is the table definition:

```<code>CREATE TABLE [dbo].[CountrySpatial](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [ObjectID] [bigint] NULL,
 [FIPS_CNTRY] [nvarchar](255) NULL,
 [GMI_CNTRY] [nvarchar](255) NULL,
 [ISO_2DIGIT] [nvarchar](255) NULL,
 [ISO_3DIGIT] [nvarchar](255) NULL,
 [ISO_NUM] [int] NULL,
 [CNTRY_NAME] [nvarchar](255) NULL,
 [LONG_NAME] [nvarchar](255) NULL,
 [ISOSHRTNAM] [nvarchar](255) NULL,
 [UNSHRTNAM] [nvarchar](255) NULL,
 [LOCSHRTNAM] [nvarchar](255) NULL,
 [LOCLNGNAM] [nvarchar](255) NULL,
 [STATUS] [nvarchar](255) NULL,
 [POP2005] [bigint] NULL,
 [SQKM] [float] NULL,
 [SQMI] [float] NULL,
 [COLORMAP] [smallint] NULL,
 [geom] [geometry] NULL,
PRIMARY KEY CLUSTERED
(
 [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[CountrySpatial]  WITH CHECK ADD  CONSTRAINT [enforce_srid_geometry_CountrySpatial] CHECK  (([geom].[STSrid]=(0)))
GO

ALTER TABLE [dbo].[CountrySpatial] CHECK CONSTRAINT [enforce_srid_geometry_CountrySpatial]
GO
</code>```

答:
The first thing to comment is that earth surface points should be stored using Geography, not Geometry. There are differences to the storage and how the functions work (even if similarly named)

Here is a working example:

Simplified table:

```<code>CREATE TABLE CountrySpatial(
 ID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
 geog geography NULL)
GO
</code>```

Insert something that resembles a diamond around India

```<code>INSERT INTO CountrySpatial(geog)
VALUES (geography::STGeomFromText('POLYGON((' +
 '77.22702 28.67613, ' + -- new delhi (top)
 '72.566071 23.059516, ' + -- ahmedabad (left)
 '77.593689 13.005227, ' + -- bengaluru (bottom)
 '88.374023 22.614011, ' + -- kolkata (right)
 '77.22702 28.67613))', 4326));
</code>```

Find the match.  It is UNION-ed to the Point being sought.  STBuffer increases the point to a 100km radius, so that it will show up when viewed together with the Geography record found (switch to Spatial tab in the output)

```<code>select geog
from countryspatial
where geog.STIntersects(geography::STGeomFromText('POINT (78 22)', 4326))>0
union all
select geography::STGeomFromText('POINT (78 22)', 4326).STBuffer(100000)
</code>```

Body:
Using this Spatial Query I am trying to get all the country information which intersects the point 78,22. Expected result is information of "India", but this query is returning no rows.

select * from countryspatial
where
geom.STIntersects((geometry::STGeomFromText('POINT (78 22)', 4326)))>0;

This is the table definition:

CREATE TABLE [dbo].[CountrySpatial](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [ObjectID] [bigint] NULL,
 [FIPS_CNTRY] [nvarchar](255) NULL,
 [GMI_CNTRY] [nvarchar](255) NULL,
 [ISO_2DIGIT] [nvarchar](255) NULL,
 [ISO_3DIGIT] [nvarchar](255) NULL,
 [ISO_NUM] [int] NULL,
 [CNTRY_NAME] [nvarchar](255) NULL,
 [LONG_NAME] [nvarchar](255) NULL,
 [ISOSHRTNAM] [nvarchar](255) NULL,
 [UNSHRTNAM] [nvarchar](255) NULL,
 [LOCSHRTNAM] [nvarchar](255) NULL,
 [LOCLNGNAM] [nvarchar](255) NULL,
 [STATUS] [nvarchar](255) NULL,
 [POP2005] [bigint] NULL,
 [SQKM] [float] NULL,
 [SQMI] [float] NULL,
 [COLORMAP] [smallint] NULL,
 [geom] [geometry] NULL,
PRIMARY KEY CLUSTERED
(
 [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[CountrySpatial]  WITH CHECK ADD  CONSTRAINT [enforce_srid_geometry_CountrySpatial] CHECK  (([geom].[STSrid]=(0)))
GO

ALTER TABLE [dbo].[CountrySpatial] CHECK CONSTRAINT [enforce_srid_geometry_CountrySpatial]
GO

Body:
The first thing to comment is that earth surface points should be stored using Geography, not Geometry. There are differences to the storage and how the functions work (even if similarly named)

Here is a working example:

Simplified table:

CREATE TABLE CountrySpatial(
 ID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
 geog geography NULL)
GO

Insert something that resembles a diamond around India

INSERT INTO CountrySpatial(geog)
VALUES (geography::STGeomFromText('POLYGON((' +
 '77.22702 28.67613, ' + -- new delhi (top)
 '72.566071 23.059516, ' + -- ahmedabad (left)
 '77.593689 13.005227, ' + -- bengaluru (bottom)
 '88.374023 22.614011, ' + -- kolkata (right)
 '77.22702 28.67613))', 4326));

Find the match.  It is UNION-ed to the Point being sought.  STBuffer increases the point to a 100km radius, so that it will show up when viewed together with the Geography record found (switch to Spatial tab in the output)

select geog
from countryspatial
where geog.STIntersects(geography::STGeomFromText('POINT (78 22)', 4326))>0
union all
select geography::STGeomFromText('POINT (78 22)', 4326).STBuffer(100000)


问:
EF 6 Many To Many Navigation Property null
I have defined a Many to Many relationship between 2 objects. Each object exposes the same Navigation property in order for me to traverse the relationships by code. The setup is as  follows;

```<code>    public class Message : Entity<int>
    {
        public int UserId { get; set; }

        public User User { get; set; }

        public Guid Reference { get; set; } = Guid.NewGuid();

        public virtual ICollection<MessageGroup> MessageGroups { get; set; } = new HashSet<MessageGroup>();
    }
}

  public class Group : Entity<int>
    {
        public int UserId { get; set; }

        public User User { get; set; }

        public Guid Reference { get; set; } = Guid.NewGuid();

        public virtual ICollection<MessageGroup> MessageGroups { get; set; } = new HashSet<MessageGroup>();

    }

 public class MessageGroup
    {
        public int MessageId { get; set; }

        public Message Message { get; set; }

        public int GroupId { get; set; }

        public Group Group { get; set; }
    }
</code>```

and this in my Context;

```<code>   protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

                modelBuilder.Entity<MessageGroup>()
                       .HasKey(bc => new { bc.GroupId, bc.MessageId });

                modelBuilder.Entity<MessageGroup>()
                    .HasRequired(bc => bc.Group)
                    .WithMany(b => b.MessageGroups)
                    .HasForeignKey(bc => bc.GroupId)
                    .WillCascadeOnDelete(false);

                modelBuilder.Entity<MessageGroup>()
                    .HasRequired(bc => bc.Message)
                    .WithMany(c => c.MessageGroups)
                    .HasForeignKey(bc => bc.MessageId)
                    .WillCascadeOnDelete(false);

}
</code>```

However, when I attempt to load a Message that has multiple groups (records are correct in MessageGroup table), only the Messages are shown. For Information, I am loading these through the Messages DbSet. When I then load the Group through the Groups DbSet, the reverse happens, and only the Groups are shown.

Loaded from Messages DbSet;

Loaded from Group DbSet;

I can get both by using the MessageGroup DbSet and Including them;

```<code>var messageGroups = context.MessageGroups.Where(x => x.MessageId == id).Include(x => x.Group).Include(x => x.Message).ToList();
</code>```

but I want to be able to load my Message or Group and have these available.

For information, my context is wrapped around another layer and I have exposed a few methods for each Type but ultimately, I am calling;

```<code>   public T Get(U id)
        {
            return _dbSet.Find(id);
        }
</code>```

答:
When a collection navigation property is loaded, the EF navigation property fixup also loads the corresponding inverse navigation property. But other navigation properties must be loaded explicitly (eager, explicit or lazy).

Since you seem to rely on lazy loading the MessageGroups collection navigation properties, you should make the inverse reference navigation properties in MessageGroup virtual too:

```<code>public class MessageGroup
{
    public int MessageId { get; set; }

    public virtual Message Message { get; set; }

    public int GroupId { get; set; }

    public virtual Group Group { get; set; }
}
</code>```

Body:
I have defined a Many to Many relationship between 2 objects. Each object exposes the same Navigation property in order for me to traverse the relationships by code. The setup is as  follows;

    public class Message : Entity<int>
    {
        public int UserId { get; set; }

        public User User { get; set; }

        public Guid Reference { get; set; } = Guid.NewGuid();

        public virtual ICollection<MessageGroup> MessageGroups { get; set; } = new HashSet<MessageGroup>();
    }
}

  public class Group : Entity<int>
    {
        public int UserId { get; set; }

        public User User { get; set; }

        public Guid Reference { get; set; } = Guid.NewGuid();

        public virtual ICollection<MessageGroup> MessageGroups { get; set; } = new HashSet<MessageGroup>();

    }

 public class MessageGroup
    {
        public int MessageId { get; set; }

        public Message Message { get; set; }

        public int GroupId { get; set; }

        public Group Group { get; set; }
    }

and this in my Context;

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

                modelBuilder.Entity<MessageGroup>()
                       .HasKey(bc => new { bc.GroupId, bc.MessageId });

                modelBuilder.Entity<MessageGroup>()
                    .HasRequired(bc => bc.Group)
                    .WithMany(b => b.MessageGroups)
                    .HasForeignKey(bc => bc.GroupId)
                    .WillCascadeOnDelete(false);

                modelBuilder.Entity<MessageGroup>()
                    .HasRequired(bc => bc.Message)
                    .WithMany(c => c.MessageGroups)
                    .HasForeignKey(bc => bc.MessageId)
                    .WillCascadeOnDelete(false);

}

However, when I attempt to load a Message that has multiple groups (records are correct in MessageGroup table), only the Messages are shown. For Information, I am loading these through the Messages DbSet. When I then load the Group through the Groups DbSet, the reverse happens, and only the Groups are shown.

Loaded from Messages DbSet;

Loaded from Group DbSet;

I can get both by using the MessageGroup DbSet and Including them;

var messageGroups = context.MessageGroups.Where(x => x.MessageId == id).Include(x => x.Group).Include(x => x.Message).ToList();

but I want to be able to load my Message or Group and have these available.

For information, my context is wrapped around another layer and I have exposed a few methods for each Type but ultimately, I am calling;

   public T Get(U id)
        {
            return _dbSet.Find(id);
        }

Body:
When a collection navigation property is loaded, the EF navigation property fixup also loads the corresponding inverse navigation property. But other navigation properties must be loaded explicitly (eager, explicit or lazy).

Since you seem to rely on lazy loading the MessageGroups collection navigation properties, you should make the inverse reference navigation properties in MessageGroup virtual too:

public class MessageGroup
{
    public int MessageId { get; set; }

    public virtual Message Message { get; set; }

    public int GroupId { get; set; }

    public virtual Group Group { get; set; }
}


答:
First of all, this code:

```<code>while($row=mysqli_fetch_array($data))
{
    echo $row['name'];
}
</code>```

is not equivalent to:

```<code>$row=mysqli_fetch_array($data);
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
</code>```

But rather to something like (pseudocode):

```<code>$row = mysqli_fetch_array($data);
if (!$row) return; //break the loop
echo $row['name'];

$row = mysqli_fetch_array($data);
if (!$row) return; //break the loop
echo $row['name'];
...
</code>```

And you could just use multiple mysqli_fetch_array() calls to achieve what you need, but there are other ways to achieve it. One of which is the usage of mysqli_fetch_all(). Both work in a similar way, but mysqli_fetch_all() returns an array of all results you received from the query, rather than one result at a time.
Now, it returns an array of arrays, so to access it, rather than:

```<code>$row['name'];
</code>```

You would need to use:

```<code>$row[ROW_NUMBER]['name']
//example
$row[0]['name']
</code>```

Examples:

1) mysqli_fetch_array()

```<code>$row = mysqli_fetch_array($data);
echo $row['name']; //output name from the first row
$row = mysqli_fetch_array($data);
echo $row['name']; //output name from the second row
</code>```

2) mysqli_fetch_all()

```<code>$row = mysqli_fetch_all($data);
echo $row[0]['name']; //output name from the first row
echo $row[1]['name']; //output name from the second row
</code>```

Title: Output of mysqli_fetch_array($data) with loop and without loop

Body:
First of all, this code:

while($row=mysqli_fetch_array($data))
{
    echo $row['name'];
}

is not equivalent to:

$row=mysqli_fetch_array($data);
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];

But rather to something like (pseudocode):

$row = mysqli_fetch_array($data);
if (!$row) return; //break the loop
echo $row['name'];

$row = mysqli_fetch_array($data);
if (!$row) return; //break the loop
echo $row['name'];
...

And you could just use multiple mysqli_fetch_array() calls to achieve what you need, but there are other ways to achieve it. One of which is the usage of mysqli_fetch_all(). Both work in a similar way, but mysqli_fetch_all() returns an array of all results you received from the query, rather than one result at a time.
Now, it returns an array of arrays, so to access it, rather than:

$row['name'];

You would need to use:

$row[ROW_NUMBER]['name']
//example
$row[0]['name']

Examples:

1) mysqli_fetch_array()

$row = mysqli_fetch_array($data);
echo $row['name']; //output name from the first row
$row = mysqli_fetch_array($data);
echo $row['name']; //output name from the second row

2) mysqli_fetch_all()

$row = mysqli_fetch_all($data);
echo $row[0]['name']; //output name from the first row
echo $row[1]['name']; //output name from the second row


答:
A few problems. Suggested fixed code

```<code>grille  *creer_grille(int n)
{
    grille *g = malloc(sizeof(grille)); // A <=== Allocate Grille
    int    i;

    assert((n == 4 || n == 6 || n == 8) // B <=== ()
       && "Taille de la grille différent de 4,6 ou 8");
    g->n = n;
    g->tab = malloc(sizeof(cellule) * (n*n)); // C <=== sizeof(cellule)
    if (g->tab == NULL)
        exit(-1);
    for (i = 0; i < n*n; i++)
    {
        g->tab[i].val = -1;
        g->tab[i].initial = 0;
    }
    return g;
}

void detruire_grille(grille * g)
{
    free (g->tab);  // D <=== free first the Cellules
    free(g);
}
</code>```

Explanation

A) Need to allocate the Grille

B) Parentheses are necessary since && has more precedence than ||

C) use sizeof(cellule) and not sizeof(int)

D) The Cellules also have to be freed (and before Grille)

Title: Why this give me a segfault?

Body:
Here is my code, I'm getting a segmentation fault and I don't know why... I'm creating a grid which 'n' is its size, 'tab' is an array which his type is cellule : a cell has 2 values. So I'm creating in the function 'creer_grille' an array I malloc it (size can be 4 6 or 8) and I initialize the cells values with -1 and 0. Then in the following function I'm testing the 'creer_grille' function.

typedef struct
{
    int val;
    int initial;
} cellule;

typedef struct
{
    cellule  *tab;
    int      n;
} grille;

grille  *creer_grille(int n)
{
    grille *g;
  int    i;

  assert(n == 4 || n == 6 || n == 8 && "Taille de la grille différent de 4,6 ou 8");
    g->n = n;
    g = malloc(sizeof(int) * (n*n));
        if (g->tab == NULL)
                exit(-1);
    for (i = 0; i < n*n; i++)
      {
        g->tab[i].val = -1;
        g->tab[i].initial = 0;
      }
      return g;
}

void detruire_grille(grille * g)
{
  free(g);
}

void test_creer_grille(){
    int i,k;
    for(k = 4; k <= 8 ; k+=2){
        grille * g = creer_grille(k);
        assert(g->n == k && "Problème dans le champ n de la grille");

        //Vérification que les cellules sont vides
        for(i = 0 ; i < k * k ; i++){
            assert(g->tab[i].val == -1 && "Problème : cellule non vide !");
            assert(g->tab[i].initial == 0 && "Problème : cellule initiale !");
        }
        detruire_grille(g);
    }
    printf("Test de la fonction creer_grille OK !\n");
}

int    main()
{
   test_creer_grille();
}

Body:
A few problems. Suggested fixed code

grille  *creer_grille(int n)
{
    grille *g = malloc(sizeof(grille)); // A <=== Allocate Grille
    int    i;

    assert((n == 4 || n == 6 || n == 8) // B <=== ()
       && "Taille de la grille différent de 4,6 ou 8");
    g->n = n;
    g->tab = malloc(sizeof(cellule) * (n*n)); // C <=== sizeof(cellule)
    if (g->tab == NULL)
        exit(-1);
    for (i = 0; i < n*n; i++)
    {
        g->tab[i].val = -1;
        g->tab[i].initial = 0;
    }
    return g;
}

void detruire_grille(grille * g)
{
    free (g->tab);  // D <=== free first the Cellules
    free(g);
}

Explanation

A) Need to allocate the Grille

B) Parentheses are necessary since && has more precedence than ||

C) use sizeof(cellule) and not sizeof(int)

D) The Cellules also have to be freed (and before Grille)


问:
A simple socket server and client program using python
SocketServer Program

This code is in raspberry:

```<code>import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The request handler class for our server.

It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""

def handle(self):
    # self.request is the TCP socket connected to the client
    self.data = self.request.recv(1024).strip()
    print "{} wrote:".format(self.client_address[0])
    print self.data
    # just send back the same data, but upper-cased
    self.request.sendall(self.data)

if __name__ == "__main__":
HOST, PORT = "localhost", 9999

# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
</code>```

Socket Client Program

This code is in my laptop:

```<code>import socket
import sys

HOST, PORT = "192.168.1.40", 3360
data='Hello'
#data = data.join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(data + "\n")

    # Receive data from the server and shut down
    received = sock.recv(1024)
finally:
    sock.close()
print "Sent:     {}".format(data)
print "Received: {}".format(received)
</code>```

Here the data sent should be received to server and sent back to client.

This is the error:

[Errno 10061] No connection could be made because the target machine actively refused it.

答: Try changing to HOST, PORT = "0.0.0.0", 9999 in the server. Now the server should listen on all interfaces and not just the loopback interface. The same could also be achieved using an empty string i.e HOST, PORT = "", 9999.

Body:
SocketServer Program

This code is in raspberry:

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The request handler class for our server.

It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""

def handle(self):
    # self.request is the TCP socket connected to the client
    self.data = self.request.recv(1024).strip()
    print "{} wrote:".format(self.client_address[0])
    print self.data
    # just send back the same data, but upper-cased
    self.request.sendall(self.data)

if __name__ == "__main__":
HOST, PORT = "localhost", 9999

# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()

Socket Client Program

This code is in my laptop:

import socket
import sys

HOST, PORT = "192.168.1.40", 3360
data='Hello'
#data = data.join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(data + "\n")

    # Receive data from the server and shut down
    received = sock.recv(1024)
finally:
    sock.close()
print "Sent:     {}".format(data)
print "Received: {}".format(received)

Here the data sent should be received to server and sent back to client.

This is the error:

[Errno 10061] No connection could be made because the target machine actively refused it.


问:
Suddenly I can't load some newly upgraded modules in Python
I suddenly can't load newly upgraded modules modules, e.g scikit-learn, zope, but I can find other packages. Even though the path links from the import points to the correct anaconda folder, which contains all the code. Any ideas what might be wrong and how to fix it?

```<code>Python 2.7.13 |Anaconda custom (64-bit)| (default, Dec 20 2016, 23:09:15)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
>>> import sklearn
>>> from os import listdir
>>> print(dir(sklearn))
['_ASSUME_FINITE', '__SKLEARN_SETUP__', '__all__', '__builtins__', '__check_build', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_contextmanager', 'base', 'clone', 'config_context', 'exceptions', 'externals', 'get_config', 'logger', 'logging', 'os', 're', 'set_config', 'setup_module', 'sys', 'utils', 'warnings']
>>> print(listdir(sklearn.__path__[0]))
['exceptions.py', 'cross_validation.pyc', 'lda.py', 'naive_bayes.pyc', 'isotonic.py', '_build_utils', 'neighbors', 'cluster', 'naive_bayes.py', '__init__.pyc', 'multiclass.py', 'dummy.pyc', 'grid_search.pyc', 'tests', '__init__.py', 'calibration.py', '_isotonic.so', 'neural_network', 'datasets', 'preprocessing', '__check_build', 'random_projection.py', 'multiclass.pyc', 'model_selection', 'calibration.pyc', 'pipeline.pyc', 'qda.py', 'learning_curve.py', 'ensemble', 'tree', 'isotonic.pyc', 'kernel_ridge.py', 'gaussian_process', 'decomposition', 'base.pyc', 'dummy.py', 'utils', 'pipeline.py', 'cross_decomposition', 'covariance', 'qda.pyc', 'multioutput.pyc', 'lda.pyc', 'feature_selection', 'linear_model', 'metrics', 'kernel_ridge.pyc', 'setup.py', 'semi_supervised', 'exceptions.pyc', 'multioutput.py', 'cross_validation.py', 'discriminant_analysis.py', 'kernel_approximation.pyc', 'base.py', 'random_projection.pyc', 'setup.pyc', 'kernel_approximation.py', 'grid_search.py', 'discriminant_analysis.pyc', 'mixture', 'manifold', 'externals', 'svm', 'feature_extraction', 'learning_curve.pyc']
>>> import zope
>>> print(dir(zope))
['__doc__', '__name__', '__path__']
>>> print(listdir(zope.__path__[0]))
['interface']
>>> zope.interface
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'interface'
>>> sklearn.lda
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'lda'
</code>```

答:
sadly but true... your error is real..but the below warning message as well. Use sklearn.discriminant_analysis.LinearDiscriminantAnalysis from now on. How to deal with the other possible persisting error is also updated into my answer. Enjoy!

```<code>import warnings
from .discriminant_analysis import LinearDiscriminantAnalysis as _LDA

warnings.warn("lda.LDA has been moved to "
          "discriminant_analysis.LinearDiscriminantAnalysis "
          "in 0.17 and will be removed in 0.19", DeprecationWarning)

class LDA(_LDA):
    """
    Alias for
    :class:`sklearn.discriminant_analysis.LinearDiscriminantAnalysis`.

    .. deprecated:: 0.17
    This class will be removed in 0.19.
    Use
    :class:`sklearn.discriminant_analysis.LinearDiscriminantAnalysis`
    instead.
    """
    pass
</code>```

No errors when running below code:

```<code>import sklearn

from sklearn import discriminant_analysis
from os import listdir

print(dir(sklearn))

print(listdir(sklearn.__path__[0]))

print discriminant_analysis.LinearDiscriminantAnalysis()
</code>```

snippet output:

[Assume_FINITE', ...]

['base.py', ...]

LinearDiscriminantAnalysis(n_components=None, priors=None, shrinkage=None,
                solver='svd', store_covariance=False, tol=0.0001)

As it seems your code goes wrong somewhere and somehow. Your best option for now is:

1 - delete your scikit-image, sklearn and zope folders from folder ../site-packages;

2 - delete folders + content of scikit_image-0.13.0-py2.7.egg-info, scikit_learn-0.19.1-py2.7.egg-info and zope installer folder
 into the trashbin;

3 - delete folders from trashbin (prevents linkage to folders within the trashbin);

4 -run pip install scikit-image/sklearn/zope with option  --no-cache-dir;

5 Voila... you get a running skimage, sklearn and zope again.

Enjoy!

Body:
I suddenly can't load newly upgraded modules modules, e.g scikit-learn, zope, but I can find other packages. Even though the path links from the import points to the correct anaconda folder, which contains all the code. Any ideas what might be wrong and how to fix it?

Python 2.7.13 |Anaconda custom (64-bit)| (default, Dec 20 2016, 23:09:15)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
>>> import sklearn
>>> from os import listdir
>>> print(dir(sklearn))
['_ASSUME_FINITE', '__SKLEARN_SETUP__', '__all__', '__builtins__', '__check_build', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_contextmanager', 'base', 'clone', 'config_context', 'exceptions', 'externals', 'get_config', 'logger', 'logging', 'os', 're', 'set_config', 'setup_module', 'sys', 'utils', 'warnings']
>>> print(listdir(sklearn.__path__[0]))
['exceptions.py', 'cross_validation.pyc', 'lda.py', 'naive_bayes.pyc', 'isotonic.py', '_build_utils', 'neighbors', 'cluster', 'naive_bayes.py', '__init__.pyc', 'multiclass.py', 'dummy.pyc', 'grid_search.pyc', 'tests', '__init__.py', 'calibration.py', '_isotonic.so', 'neural_network', 'datasets', 'preprocessing', '__check_build', 'random_projection.py', 'multiclass.pyc', 'model_selection', 'calibration.pyc', 'pipeline.pyc', 'qda.py', 'learning_curve.py', 'ensemble', 'tree', 'isotonic.pyc', 'kernel_ridge.py', 'gaussian_process', 'decomposition', 'base.pyc', 'dummy.py', 'utils', 'pipeline.py', 'cross_decomposition', 'covariance', 'qda.pyc', 'multioutput.pyc', 'lda.pyc', 'feature_selection', 'linear_model', 'metrics', 'kernel_ridge.pyc', 'setup.py', 'semi_supervised', 'exceptions.pyc', 'multioutput.py', 'cross_validation.py', 'discriminant_analysis.py', 'kernel_approximation.pyc', 'base.py', 'random_projection.pyc', 'setup.pyc', 'kernel_approximation.py', 'grid_search.py', 'discriminant_analysis.pyc', 'mixture', 'manifold', 'externals', 'svm', 'feature_extraction', 'learning_curve.pyc']
>>> import zope
>>> print(dir(zope))
['__doc__', '__name__', '__path__']
>>> print(listdir(zope.__path__[0]))
['interface']
>>> zope.interface
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'interface'
>>> sklearn.lda
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'lda'

Body:
sadly but true... your error is real..but the below warning message as well. Use sklearn.discriminant_analysis.LinearDiscriminantAnalysis from now on. How to deal with the other possible persisting error is also updated into my answer. Enjoy!

import warnings
from .discriminant_analysis import LinearDiscriminantAnalysis as _LDA

warnings.warn("lda.LDA has been moved to "
          "discriminant_analysis.LinearDiscriminantAnalysis "
          "in 0.17 and will be removed in 0.19", DeprecationWarning)

class LDA(_LDA):
    """
    Alias for
    :class:`sklearn.discriminant_analysis.LinearDiscriminantAnalysis`.

    .. deprecated:: 0.17
    This class will be removed in 0.19.
    Use
    :class:`sklearn.discriminant_analysis.LinearDiscriminantAnalysis`
    instead.
    """
    pass

No errors when running below code:

import sklearn

from sklearn import discriminant_analysis
from os import listdir

print(dir(sklearn))

print(listdir(sklearn.__path__[0]))

print discriminant_analysis.LinearDiscriminantAnalysis()

snippet output:

[Assume_FINITE', ...]

['base.py', ...]

LinearDiscriminantAnalysis(n_components=None, priors=None, shrinkage=None,
                solver='svd', store_covariance=False, tol=0.0001)

As it seems your code goes wrong somewhere and somehow. Your best option for now is:

1 - delete your scikit-image, sklearn and zope folders from folder ../site-packages;

2 - delete folders + content of scikit_image-0.13.0-py2.7.egg-info, scikit_learn-0.19.1-py2.7.egg-info and zope installer folder
 into the trashbin;

3 - delete folders from trashbin (prevents linkage to folders within the trashbin);

4 -run pip install scikit-image/sklearn/zope with option  --no-cache-dir;

5 Voila... you get a running skimage, sklearn and zope again.

Enjoy!


问:
How was the first computer program created?

Possible Duplicate:

  How was the first compiler written?

This question has always been bothering me.
To compile a program, you need a compiler, which is also a type of program, so what compiled the compiler?
Somebody told me that the first compilers were written in assembly or machine code.
But thinking about that, that is still not the complete story. After all, how does the machine code go from the hard drive to RAM to the CPU without an operating system and drivers? The drivers had to have been programmed somehow.

I know that the very early computers had switches and allowed you to flip the switch to indicate bits. I am wondering how the leap was made from switches to a way to get the CPU to read machine code without needing a computer program to tell it to do so.

答:
In the early days of the microcomputer industry, you had to laboriously enter machine code directly using toggle switches. A classic example is the Altair 8800 (shown below though possibly a replica):

With this, you would set the binary switches for the address and/or data bits, then use one of the command toggle switches to either:

set the current address to whatever is indicated by the address switches; or

write the data from the data switches to the current/next address.

The Altair, after RESET, had the current address set to zero and, since this is where the CPU will start executing code, that was usually sufficient. Otherwise, you could set the address switches and toggle EXAMINE to set the current address to something else. That address selection process was also needed in the case where you had entered your program incorrectly and needed to patch it (rather than doing it all again from scratch).

Once the address was what you wanted (EXAMINE would show it on the address LEDs along with the current content on the data LEDs), you would toggle the data switches and do DEPOSIT to put that data into the current address (DEPOSIT-NEXT was identical but it first incremented the current address before depositing, useful for sequential entry).

The whole process can be found on sites like this one, with the basic idea being:

Write the program out by hand, in assembly language.

Hand-assemble that into binary code, using whatever manuals you have for the CPU, giving you a series of address/data pairs.

Use the EXAMINE/DEPOSIT/DEPOSIT-NEXT process to enter each byte into memory, being very careful that the LEDs correctly indicate the byte you just deposited.

That second bullet point is probably the hardest  bit since you need to adjust for jumping to instructions that may not have yet been assembled, so you're basically basically a slow, biological, multi-pass assembler.

For an example, consider the following (very simple) 8080 code, gleaned from online sources:

```<code>0000    c3 00 00    jmp 0000 ; Infinite loop.
</code>```

Note those data bytes c3 00 00 are hexadecimal but people often used octal since the Altair switches were grouped into three rather than four; that would give 303 000 000.

Hence, you would, for that specific program:

Toggle RESET, giving a current address of zero.

Enter binary data switches 101 000 101 for octal 303, the JMP opcode.

Toggle the DEPOSIT switch, putting that byte into memory location 0, and showing that address and the deposited data on the LEDs for checking.

Enter binary data switches 000 000 000 for octal 000, the first byte of the address to jump to.

Toggle the DEPOSIT-NEXT switch, advancing the current address to 1, depositing the byte in that address and again showing the address and data on the LEDs.

Toggle the DEPOSIT-NEXT switch again, advancing the current address to 2, depositing the byte in that address and again showing the address and data on the LEDs. There was no need to change the data switches as they were identical to the previous byte.

At that point, the program is in memory, and you can toggle RESET then RUN to see it in action. Though, if you wanted to see the LEDs change as it ran, you'd probably continuously toggle SINGLE-STEP instead.

The other thing to keep in mind is that there's no requirement that a program be written on the platform it's intended to run on. Cross-assemblers (or compilers) running on another platform can be used to bypass the laborious hand-assembling process described above.

You still have to get the bytes into the target platform but there were solutions for that as well. Paper tape readers could be added to Altair so, provided the cross-assembler system could produce the tapes, only a small loader program would be needed to load and run it.

For example, in the early embedded days (before "embedded" meant huge honkin' Linux boxes), I was part of a team developing operating system, drivers, and application code for a 6809-based device. The actual development tools were all hosted on an early UNIX system, and these were burnt onto EPROMS for insertion into the devices. No development at all took place on those devices, as they were very tailored toward their one real task.

Body:
In the early days of the microcomputer industry, you had to laboriously enter machine code directly using toggle switches. A classic example is the Altair 8800 (shown below though possibly a replica):

With this, you would set the binary switches for the address and/or data bits, then use one of the command toggle switches to either:

set the current address to whatever is indicated by the address switches; or

write the data from the data switches to the current/next address.

The Altair, after RESET, had the current address set to zero and, since this is where the CPU will start executing code, that was usually sufficient. Otherwise, you could set the address switches and toggle EXAMINE to set the current address to something else. That address selection process was also needed in the case where you had entered your program incorrectly and needed to patch it (rather than doing it all again from scratch).

Once the address was what you wanted (EXAMINE would show it on the address LEDs along with the current content on the data LEDs), you would toggle the data switches and do DEPOSIT to put that data into the current address (DEPOSIT-NEXT was identical but it first incremented the current address before depositing, useful for sequential entry).

The whole process can be found on sites like this one, with the basic idea being:

Write the program out by hand, in assembly language.

Hand-assemble that into binary code, using whatever manuals you have for the CPU, giving you a series of address/data pairs.

Use the EXAMINE/DEPOSIT/DEPOSIT-NEXT process to enter each byte into memory, being very careful that the LEDs correctly indicate the byte you just deposited.

That second bullet point is probably the hardest  bit since you need to adjust for jumping to instructions that may not have yet been assembled, so you're basically basically a slow, biological, multi-pass assembler.

For an example, consider the following (very simple) 8080 code, gleaned from online sources:

0000    c3 00 00    jmp 0000 ; Infinite loop.

Note those data bytes c3 00 00 are hexadecimal but people often used octal since the Altair switches were grouped into three rather than four; that would give 303 000 000.

Hence, you would, for that specific program:

Toggle RESET, giving a current address of zero.

Enter binary data switches 101 000 101 for octal 303, the JMP opcode.

Toggle the DEPOSIT switch, putting that byte into memory location 0, and showing that address and the deposited data on the LEDs for checking.

Enter binary data switches 000 000 000 for octal 000, the first byte of the address to jump to.

Toggle the DEPOSIT-NEXT switch, advancing the current address to 1, depositing the byte in that address and again showing the address and data on the LEDs.

Toggle the DEPOSIT-NEXT switch again, advancing the current address to 2, depositing the byte in that address and again showing the address and data on the LEDs. There was no need to change the data switches as they were identical to the previous byte.

At that point, the program is in memory, and you can toggle RESET then RUN to see it in action. Though, if you wanted to see the LEDs change as it ran, you'd probably continuously toggle SINGLE-STEP instead.

The other thing to keep in mind is that there's no requirement that a program be written on the platform it's intended to run on. Cross-assemblers (or compilers) running on another platform can be used to bypass the laborious hand-assembling process described above.

You still have to get the bytes into the target platform but there were solutions for that as well. Paper tape readers could be added to Altair so, provided the cross-assembler system could produce the tapes, only a small loader program would be needed to load and run it.

For example, in the early embedded days (before "embedded" meant huge honkin' Linux boxes), I was part of a team developing operating system, drivers, and application code for a 6809-based device. The actual development tools were all hosted on an early UNIX system, and these were burnt onto EPROMS for insertion into the devices. No development at all took place on those devices, as they were very tailored toward their one real task.

ContentLicense: CC BY-SA 4.0


问:
Scraping flight data with Python requests
The following URL shows a flight and offers further details (toggle e.g. "Flugweg" or "Statistik" on the left side). I would like to read this data and later convert that into lists.

https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729

So what I have been doing so far is the following:

```<code>import requests
API_url = "https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html"
response = requests.post(API_url)
</code>```

doing a response.text gives me a page back, basically telling me that "The requested page doesn't exist".

I then tried to add header information, as I read that sometimes this is a reason a request is denied:

```<code>headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
            "Referer":"https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729",
          "Origin":"https://www.onlinecontest.org"}
</code>```

And then have

```<code>response = requests.post(API_url, headers = headers)
</code>```

This did not change anything and is simply fishing in murky waters.

Searching with Chrome for XHR offers three files and they contain what I want, but I am running out of ideas, how to get them. What would be the correct approach to access the data?

答: The contend of this page is generated by javascript. In order to scrape the content you need to use some tool which processes and renders javascript generated objects, i.e. Selenium.</p>

Body:
The following URL shows a flight and offers further details (toggle e.g. "Flugweg" or "Statistik" on the left side). I would like to read this data and later convert that into lists.

https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729

So what I have been doing so far is the following:

import requests
API_url = "https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html"
response = requests.post(API_url)

doing a response.text gives me a page back, basically telling me that "The requested page doesn't exist".

I then tried to add header information, as I read that sometimes this is a reason a request is denied:

headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
            "Referer":"https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729",
          "Origin":"https://www.onlinecontest.org"}

And then have

response = requests.post(API_url, headers = headers)

This did not change anything and is simply fishing in murky waters.

Searching with Chrome for XHR offers three files and they contain what I want, but I am running out of ideas, how to get them. What would be the correct approach to access the data?


问:
Login is currently incompatible with git bash/cygwin
I just download this version Git-2.6.1-64-bit.exe my OS is windows 10 64bit.. why I cannot still log in it? is Git-2.6.1-64-bit.exe the latest one?

before it was MINWG32 now updated become MINWG64 but still I cannot login..help me solve this issues

I don't have any solution for this instead to use the cmd.exe.... but I need the flow of it...coz some of the commands cannot run in this environment...it's a big difference between a Linux-like environment... please post procedure/steps in deploying apps in heroku.

IT SAYS :
Login is currently incompatible with git bash/cygwin
In the meantime, login via cmd.exe
https://github.com/heroku/heroku-cli/issues/84

答:
Instead of typing heroku login , i had to type winpty heroku login . And that solved my problem.

i.e

```<code>winpty heroku login
</code>```

Body:
Instead of typing heroku login , i had to type winpty heroku login . And that solved my problem.

i.e

winpty heroku login


问:
How to add up the same 'items' in a dictionary of multiple dictionaries in Python?
How could I add up the speed of these characters even if they don't all have the attribute speed? This is an example, there are many other attributes. The characters are picked randomly and grouped together:

```<code>character_1 = {'Money': .3, 'Strength': .25, 'Speed': .05}
character_2 = {'Money': .3, 'Age': 25, 'Speed': .7}
character_3 = {'Money': .3, 'Strength': .25, 'Power': 5}
</code>```

How could I find out the combined speed, money, age etc of all these characters? (if age is not defined for others the right answer should be 25 years in total)
thank you!!

答:
You could loop through a list of the dicts and combine their values in a result dict like this:

```<code>character_1 = {'Money': .3, 'Strength': .25, 'Speed': .05}
character_2 = {'Money': .3, 'Age': 25, 'Speed': .7}
character_3 = {'Money': .3, 'Strength': .25, 'Power': 5}

dict_list = [character_1, character_2, character_3]

result = dict()

for d in dict_list:
    for k, v in d.items():
        if k in result:
            result[k] += v
        else:
            result[k] = v

print(result)

{'Money': 0.8999999999999999, 'Strength': 0.5, 'Speed': 0.75, 'Age': 25, 'Power': 5}
>>>
</code>```

Body:
How could I add up the speed of these characters even if they don't all have the attribute speed? This is an example, there are many other attributes. The characters are picked randomly and grouped together:

character_1 = {'Money': .3, 'Strength': .25, 'Speed': .05}
character_2 = {'Money': .3, 'Age': 25, 'Speed': .7}
character_3 = {'Money': .3, 'Strength': .25, 'Power': 5}

How could I find out the combined speed, money, age etc of all these characters? (if age is not defined for others the right answer should be 25 years in total)
thank you!!

Body:
You could loop through a list of the dicts and combine their values in a result dict like this:

character_1 = {'Money': .3, 'Strength': .25, 'Speed': .05}
character_2 = {'Money': .3, 'Age': 25, 'Speed': .7}
character_3 = {'Money': .3, 'Strength': .25, 'Power': 5}

dict_list = [character_1, character_2, character_3]

result = dict()

for d in dict_list:
    for k, v in d.items():
        if k in result:
            result[k] += v
        else:
            result[k] = v

print(result)

{'Money': 0.8999999999999999, 'Strength': 0.5, 'Speed': 0.75, 'Age': 25, 'Power': 5}
>>>


问:
PHP posting error
I keep getting a Cannot POST /app/newpost/newpost.php error when i try to post a HTML form and retrieve the data from another HTML page

HTML for the form is:

    Create a new forum post

<form action="newpost.php" method="POST" style="text-align:center">

Title: <input type="text" name="title" style="font-size:24px; font-family:verdana;">

Description: <input type="text" name="desc" style="font-size:24px; font-family:verdana;">

<input type="submit" action="window.location.href='/app/forum/forum.component.html'" style="background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: left; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;">
</form>```
</div>
</div>
</p>

<p>PHP file is </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
if (isset($_POST["submit"]))
{$title = $_POST['title'];
$desc = $_POST['desc']
}
?></code>```

im still very new to PHP someone pls help!
And how to retrieve the posted data on another html page?

答: You need a web server with PHP installed to test/run your PHP script. You cannot have it run from your file system directory. Depending on your environment you might want to installed something called WAMP, XAMP or MAMP.</p>

Title: PHP posting error

Body:
I keep getting a Cannot POST /app/newpost/newpost.php error when i try to post a HTML form and retrieve the data from another HTML page

HTML for the form is:

    Create a new forum post

<form action="newpost.php" method="POST" style="text-align:center">

Title: <input type="text" name="title" style="font-size:24px; font-family:verdana;">

Description: <input type="text" name="desc" style="font-size:24px; font-family:verdana;">

<input type="submit" action="window.location.href='/app/forum/forum.component.html'" style="background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: left; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;">
</form>

PHP file is

<?php
if (isset($_POST["submit"]))
{$title = $_POST['title'];
$desc = $_POST['desc']
}
?>

im still very new to PHP someone pls help!
And how to retrieve the posted data on another html page?


问:
CSS - Is it possible to add a black outline around each character in text?
I would like to add a black outline around each character, so if the font id on the same color background as the foreground it is still readable.

Can this be done in CSS with or without browser specific css?

答:
You can simulate it with the CSS 2.1 text-shadow property:

```<code>p {
    color: #fff;
    text-shadow: 1px 0 0 #000, 0 -1px 0 #000, 0 1px 0 #000, -1px 0 0 #000;
}
</code>```

This is, of course, not supported in IE9 and below. See: http://www.jsfiddle.net/yijiang/UCjgg/ for a simple demo.

Body:
You can simulate it with the CSS 2.1 text-shadow property:

p {
    color: #fff;
    text-shadow: 1px 0 0 #000, 0 -1px 0 #000, 0 1px 0 #000, -1px 0 0 #000;
}

This is, of course, not supported in IE9 and below. See: http://www.jsfiddle.net/yijiang/UCjgg/ for a simple demo.


问:
Can't append series to dataframe in some case
I'm a newbie pandas user and upsetting for some trouble.

Here's the case.
This is the initial dataframe.

```<code>In [9]: df
Out[9]:
  importance interval last_read                last_update    name trigger
0          2      NaN       NaN  2017-12-09 00:00:00+09:00  foobar     NaN
</code>```

And this is the record to append.

```<code>In [10]: record = df.iloc[0].copy()
</code>```

No error when appending this record.

```<code>In [11]: df.append(record)
Out[11]:
  importance interval last_read                last_update    name trigger
0          2      NaN       NaN  2017-12-09 00:00:00+09:00  foobar     NaN
0          2      NaN       NaN  2017-12-09 00:00:00+09:00  foobar     NaN
</code>```

Change a NaN value of record to int and append it, and no error occurs.

```<code>In [12]: record['interval'] = 1

In [13]: df.append(record)
Out[13]:
  importance interval last_read                last_update    name trigger
0          2      NaN       NaN  2017-12-09 00:00:00+09:00  foobar     NaN
0          2        1       NaN  2017-12-09 00:00:00+09:00  foobar     NaN
</code>```

Then change another NaN value of record to pd.Timestamp and append.
This occurs an error.

```<code>In [10]: record
Out[10]:
importance                             2
interval                             NaN
last_read                            NaN
last_update    2017-12-09 00:00:00+09:00
name                              foobar
trigger                              NaN
Name: 0, dtype: object

In [11]: record['trigger'] = record['last_update']

In [12]: record
Out[12]:
importance                             2
interval                             NaN
last_read                            NaN
last_update    2017-12-09 00:00:00+09:00
name                              foobar
trigger        2017-12-09 00:00:00+09:00
Name: 0, dtype: object

In [13]: df.append(record)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-7c027f1cbb54> in <module>()
----> 1 df.append(record)

~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in append(self, other, ignore_index, verify_integrity)
   4545             to_concat = [self, other]
   4546         return concat(to_concat, ignore_index=ignore_index,
-> 4547                       verify_integrity=verify_integrity)
   4548
   4549     def join(self, other, on=None, how='left', lsuffix='', rsuffix='',

~/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/concat.py in concat(objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, copy)
    205                        verify_integrity=verify_integrity,
    206                        copy=copy)
--> 207     return op.get_result()
    208
    209

~/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/concat.py in get_result(self)
    405             new_data = concatenate_block_managers(
    406                 mgrs_indexers, self.new_axes, concat_axis=self.axis,
--> 407                 copy=self.copy)
    408             if not self.copy:
    409                 new_data._consolidate_inplace()

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in concatenate_block_managers(mgrs_indexers, axes, concat_axis, copy)
   4830     blocks = [make_block(
   4831         concatenate_join_units(join_units, concat_axis, copy=copy),
-> 4832         placement=placement) for placement, join_units in concat_plan]
   4833
   4834     return BlockManager(blocks, axes)

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in <listcomp>(.0)
   4830     blocks = [make_block(
   4831         concatenate_join_units(join_units, concat_axis, copy=copy),
-> 4832         placement=placement) for placement, join_units in concat_plan]
   4833
   4834     return BlockManager(blocks, axes)

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in concatenate_join_units(join_units, concat_axis, copy)
   4937     to_concat = [ju.get_reindexed_values(empty_dtype=empty_dtype,
   4938                                          upcasted_na=upcasted_na)
-> 4939                  for ju in join_units]
   4940
   4941     if len(to_concat) == 1:

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in <listcomp>(.0)
   4937     to_concat = [ju.get_reindexed_values(empty_dtype=empty_dtype,
   4938                                          upcasted_na=upcasted_na)
-> 4939                  for ju in join_units]
   4940
   4941     if len(to_concat) == 1:

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in get_reindexed_values(self, empty_dtype, upcasted_na)
   5210                     pass
   5211                 else:
-> 5212                     missing_arr = np.empty(self.shape, dtype=empty_dtype)
   5213                     missing_arr.fill(fill_value)
   5214                     return missing_arr

TypeError: data type not understood
</code>```

My pandas version is 0.20.3

Could you give me some advice?

Thank you

答: You can try pd.to_datetime instead of timestamp and try</p>

Body:
I'm a newbie pandas user and upsetting for some trouble.

Here's the case.
This is the initial dataframe.

In [9]: df
Out[9]:
  importance interval last_read                last_update    name trigger
0          2      NaN       NaN  2017-12-09 00:00:00+09:00  foobar     NaN

And this is the record to append.

In [10]: record = df.iloc[0].copy()

No error when appending this record.

In [11]: df.append(record)
Out[11]:
  importance interval last_read                last_update    name trigger
0          2      NaN       NaN  2017-12-09 00:00:00+09:00  foobar     NaN
0          2      NaN       NaN  2017-12-09 00:00:00+09:00  foobar     NaN

Change a NaN value of record to int and append it, and no error occurs.

In [12]: record['interval'] = 1

In [13]: df.append(record)
Out[13]:
  importance interval last_read                last_update    name trigger
0          2      NaN       NaN  2017-12-09 00:00:00+09:00  foobar     NaN
0          2        1       NaN  2017-12-09 00:00:00+09:00  foobar     NaN

Then change another NaN value of record to pd.Timestamp and append.
This occurs an error.

In [10]: record
Out[10]:
importance                             2
interval                             NaN
last_read                            NaN
last_update    2017-12-09 00:00:00+09:00
name                              foobar
trigger                              NaN
Name: 0, dtype: object

In [11]: record['trigger'] = record['last_update']

In [12]: record
Out[12]:
importance                             2
interval                             NaN
last_read                            NaN
last_update    2017-12-09 00:00:00+09:00
name                              foobar
trigger        2017-12-09 00:00:00+09:00
Name: 0, dtype: object

In [13]: df.append(record)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-7c027f1cbb54> in <module>()
----> 1 df.append(record)

~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in append(self, other, ignore_index, verify_integrity)
   4545             to_concat = [self, other]
   4546         return concat(to_concat, ignore_index=ignore_index,
-> 4547                       verify_integrity=verify_integrity)
   4548
   4549     def join(self, other, on=None, how='left', lsuffix='', rsuffix='',

~/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/concat.py in concat(objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, copy)
    205                        verify_integrity=verify_integrity,
    206                        copy=copy)
--> 207     return op.get_result()
    208
    209

~/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/concat.py in get_result(self)
    405             new_data = concatenate_block_managers(
    406                 mgrs_indexers, self.new_axes, concat_axis=self.axis,
--> 407                 copy=self.copy)
    408             if not self.copy:
    409                 new_data._consolidate_inplace()

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in concatenate_block_managers(mgrs_indexers, axes, concat_axis, copy)
   4830     blocks = [make_block(
   4831         concatenate_join_units(join_units, concat_axis, copy=copy),
-> 4832         placement=placement) for placement, join_units in concat_plan]
   4833
   4834     return BlockManager(blocks, axes)

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in <listcomp>(.0)
   4830     blocks = [make_block(
   4831         concatenate_join_units(join_units, concat_axis, copy=copy),
-> 4832         placement=placement) for placement, join_units in concat_plan]
   4833
   4834     return BlockManager(blocks, axes)

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in concatenate_join_units(join_units, concat_axis, copy)
   4937     to_concat = [ju.get_reindexed_values(empty_dtype=empty_dtype,
   4938                                          upcasted_na=upcasted_na)
-> 4939                  for ju in join_units]
   4940
   4941     if len(to_concat) == 1:

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in <listcomp>(.0)
   4937     to_concat = [ju.get_reindexed_values(empty_dtype=empty_dtype,
   4938                                          upcasted_na=upcasted_na)
-> 4939                  for ju in join_units]
   4940
   4941     if len(to_concat) == 1:

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in get_reindexed_values(self, empty_dtype, upcasted_na)
   5210                     pass
   5211                 else:
-> 5212                     missing_arr = np.empty(self.shape, dtype=empty_dtype)
   5213                     missing_arr.fill(fill_value)
   5214                     return missing_arr

TypeError: data type not understood

My pandas version is 0.20.3

Could you give me some advice?

Thank you


问:
How to add custom code snippets in VSCode?
Is it possible to add custom code snippets in Visual Studio Code? And if so, how? VSCode is based on Atom, so it should be possible.</p>

答:
Option 1 - Use the Snippet Generator extension.

It supports code to JSON conversion with optional scope support and space to \t conversion.

Demo:

Option 2 - Another extension is snippet-creator (deprecated).

After installing it, all you have to do is to :

Select the code that you want to make a snippet.

Right-click on it and select "Command Palette"(or Ctrl+Shift+P).

Write "Create Snippet".

Choose the type of files needed to be watched to trigger your snippet shortcut.

Choose a snippet shortcut.

Choose a snippet name.

Option 3 - check this website. you can generate snippets for vs code, sublime text, and atom.

Once snippet being generated on this site. Go to the respective IDE's snippet file and paste the same. For example for a JS snippet in VS code go to File->preference->user snippet then it opens javascript.json file then paste the snippet code from an above site inside this and we are good to go.


问:
Why this give me a segfault?
Here is my code, I'm getting a segmentation fault and I don't know why... I'm creating a grid which 'n' is its size, 'tab' is an array which his type is cellule : a cell has 2 values. So I'm creating in the function 'creer_grille' an array I malloc it (size can be 4 6 or 8) and I initialize the cells values with -1 and 0. Then in the following function I'm testing the 'creer_grille' function.</p>

```<code>typedef struct
{
    int val;
    int initial;
} cellule;

typedef struct
{
    cellule  *tab;
    int      n;
} grille;

grille  *creer_grille(int n)
{
    grille *g;
  int    i;

  assert(n == 4 || n == 6 || n == 8 && "Taille de la grille différent de 4,6 ou 8");
    g->n = n;
    g = malloc(sizeof(int) * (n*n));
        if (g->tab == NULL)
                exit(-1);
    for (i = 0; i < n*n; i++)
      {
        g->tab[i].val = -1;
        g->tab[i].initial = 0;
      }
      return g;
}

void detruire_grille(grille * g)
{
  free(g);
}

void test_creer_grille(){
    int i,k;
    for(k = 4; k <= 8 ; k+=2){
        grille * g = creer_grille(k);
        assert(g->n == k && "Problème dans le champ n de la grille");

        //Vérification que les cellules sont vides
        for(i = 0 ; i < k * k ; i++){
            assert(g->tab[i].val == -1 && "Problème : cellule non vide !");
            assert(g->tab[i].initial == 0 && "Problème : cellule initiale !");
        }
        detruire_grille(g);
    }
    printf("Test de la fonction creer_grille OK !\n");
}

int    main()
{
   test_creer_grille();
}
</code>```

答:
The problem is in this function : creer_grille(int n)
the variable g is dynamically allocated with the size of sizeof(int)nn

but during the loop you are accessing the cellule field, that was not allocated explicitly.
You are allocation g and testing (g->tab == NULL). This works for you because malloc is not setting the allocated memory to 0. if you used calloc - you could see the problem.

When you will try to set the initial field in the cullule in the n*n'th iteration - you will get the segmentation fault.

Title: Why this give me a segfault?


问:
When to choose type `{}` over `object` or does it matter?
I am wondering about the (semantic) difference in Typescript between {} and object.

For example if you have a function which accepts an object, but you do not know or care about its shape, would you declare it as {} or object or does it not matter?

Here's an example:

```<code>export async function updateSomeUserData(
  userId: string,
  data: object
): Promise<void> {
  const ref = await getUserDataRef(userId);

  await ref.update({
    ...data
  });
}
</code>```

I real life you might want to strictly define all possible data properties with optional keys in a type, but I think this kind of situation can happen where you don't want to be so specific.

答:
The difference is quite subtle:

Something typed as {} or Object can represent any object.

Something typed as object can only represent non-primitive types - in other words, it cannot be a number, string, boolean, symbol, null or undefined.

In both cases, using the obj.member syntax will only allow you to access the members of the Object prototype.

This is what makes {} and Object differ from the any type - the latter doesn't give you any type safety, while the former will only give you type safety for Object prototype members.

To access an arbitrary key, you have to use the obj["member"] syntax, which effectively tells the type system 'I won't know if this member exists until runtime`. As such, you should make sure to null check it!

Body:
I am wondering about the (semantic) difference in Typescript between {} and object.

For example if you have a function which accepts an object, but you do not know or care about its shape, would you declare it as {} or object or does it not matter?

Here's an example:

export async function updateSomeUserData(
  userId: string,
  data: object
): Promise<void> {
  const ref = await getUserDataRef(userId);

  await ref.update({
    ...data
  });
}

I real life you might want to strictly define all possible data properties with optional keys in a type, but I think this kind of situation can happen where you don't want to be so specific.


问:
I am having trouble in displaying date beside the entered todo element. What is wrong with changeDate() function?
Entered todo is shown but the date is not being shown. Am i using any wrong command?? On entering a data, date should be shown on the left of the todo, just below the input area.

var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');

function store(ele) {
  if (event.keyCode == 13) {
    changeText();
  }
}

function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);
    changeDate();
  }
}

function changeDate() {
  var d = new Date();
  var dates = document.createElement("div");
  dates.className = "myClass";
  dates.innerHTML = document.createTextNode(d.toDateString());
  list2.innerHTML = dates;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>
    Your todos
  </h1>

  <input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">
  <div class="todos">
    <ul id="demo"></ul>
  </div>
</div></code>```

答:
instead of this:

```<code>function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);
    changeDate(list);
  }
}
</code>```

try this:

```<code>function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    changeDate(list); //call this before appending data
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);

  }
}
</code>```

and CSS:

```<code>li{
    display: inline-block;
}
</code>```

Body:
Entered todo is shown but the date is not being shown. Am i using any wrong command?? On entering a data, date should be shown on the left of the todo, just below the input area.

var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');

function store(ele) {
  if (event.keyCode == 13) {
    changeText();
  }
}

function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);
    changeDate();
  }
}

function changeDate() {
  var d = new Date();
  var dates = document.createElement("div");
  dates.className = "myClass";
  dates.innerHTML = document.createTextNode(d.toDateString());
  list2.innerHTML = dates;
}

    Your todos

  <input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">

Body:
instead of this:

function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);
    changeDate(list);
  }
}

try this:

function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    changeDate(list); //call this before appending data
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);

  }
}

and CSS:

li{
    display: inline-block;
}