问:
Is there better way to create lazy variable initialization?
I want to create code that initialize variable only when I really need it. But initializing in the regular way:

```<code>var = None

if var is None:
    var = factory()
var2 = var
</code>```

Make too much noise in the code.

I tried to create fast solution but I feel there is better option. This is my solution that is fast but can't get parameters and use defaultdict for this.

```<code>def lazy_variable(factory):
    data = defaultdict(factory)
    return lambda: data['']

var = lazy_variable(a_factory)
var2 = var()
</code>```

More questions:

is there fast python container that holds only one variable?

is there a way to return value without calling the function with parenthesis?

EDIT:

Please consider performance. I know i can create a class that can have this behavior, but it slower then the simple solution and also the default dict solution.

trying some of the solutions:

define:

```<code>import cachetools.func
import random

@cachetools.func.lru_cache(None)
def factory(i):
    return random.random()
</code>```

and run:

```<code>%%timeit

for i in xrange(100):
    q = factory(i)
    q = factory(i)
</code>```

got:

```<code>100 loops, best of 3: 2.63 ms per loop
</code>```

naive:

```<code>%%timeit

for i in xrange(100):
    a = None
    if a is None:
        a = random.random()
    q = a
    q = a
</code>```

got:

```<code>The slowest run took 4.71 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.8 µs per loop
</code>```

I'm not sure what was cached

defaultdict solution:

```<code>%%timeit

for i in xrange(100):
    a = lazy_variable(random.random)
    q = a()
    q = a()
</code>```

got:

```<code>The slowest run took 4.11 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 76.3 µs per loop
</code>```

Tnx!

答:
If I understand you correctly then some of the functionality you are interested in is provided by functools.lru_cache:

```<code>import functools as ft

@ft.lru_cache(None)
def lazy():
    print("I'm working soo hard")
    return sum(range(1000))

lazy() # 1st time factory is called
# I'm working soo hard
# 499500
lazy() # afterwards cached result is used
# 499500
</code>```

The decorated factory may also take parameters:

```<code>@ft.lru_cache(None)
def lazy_with_args(x):
    print("I'm working so hard")
    return sum((x+i)**2 for i in range(100))

lazy_with_args(3.4)
# I'm working so hard
# 363165.99999999994
lazy_with_args(3.4)
# 363165.99999999994
# new parametes, factory is used to compute new value
lazy_with_args(-1.2)
# I'm working so hard
# 316614.00000000006
lazy_with_args(-1.2)
# 316614.00000000006
# old value stays in cache
lazy_with_args(3.4)
# 363165.99999999994
</code>```

Body:
I want to create code that initialize variable only when I really need it. But initializing in the regular way:

var = None

if var is None:
    var = factory()
var2 = var

Make too much noise in the code.

I tried to create fast solution but I feel there is better option. This is my solution that is fast but can't get parameters and use defaultdict for this.

def lazy_variable(factory):
    data = defaultdict(factory)
    return lambda: data['']

var = lazy_variable(a_factory)
var2 = var()

More questions:

is there fast python container that holds only one variable?

is there a way to return value without calling the function with parenthesis?

EDIT:

Please consider performance. I know i can create a class that can have this behavior, but it slower then the simple solution and also the default dict solution.

trying some of the solutions:

define:

import cachetools.func
import random

@cachetools.func.lru_cache(None)
def factory(i):
    return random.random()

and run:

%%timeit

for i in xrange(100):
    q = factory(i)
    q = factory(i)

got:

100 loops, best of 3: 2.63 ms per loop

naive:

%%timeit

for i in xrange(100):
    a = None
    if a is None:
        a = random.random()
    q = a
    q = a

got:

The slowest run took 4.71 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.8 µs per loop

I'm not sure what was cached

defaultdict solution:

%%timeit

for i in xrange(100):
    a = lazy_variable(random.random)
    q = a()
    q = a()

got:

The slowest run took 4.11 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 76.3 µs per loop

Tnx!

Body:
If I understand you correctly then some of the functionality you are interested in is provided by functools.lru_cache:

import functools as ft

@ft.lru_cache(None)
def lazy():
    print("I'm working soo hard")
    return sum(range(1000))

lazy() # 1st time factory is called
# I'm working soo hard
# 499500
lazy() # afterwards cached result is used
# 499500

The decorated factory may also take parameters:

@ft.lru_cache(None)
def lazy_with_args(x):
    print("I'm working so hard")
    return sum((x+i)**2 for i in range(100))

lazy_with_args(3.4)
# I'm working so hard
# 363165.99999999994
lazy_with_args(3.4)
# 363165.99999999994
# new parametes, factory is used to compute new value
lazy_with_args(-1.2)
# I'm working so hard
# 316614.00000000006
lazy_with_args(-1.2)
# 316614.00000000006
# old value stays in cache
lazy_with_args(3.4)
# 363165.99999999994


来源: stackexchange

问:
Checking if all entries in a 2d Boolean array are true/false using a method in Java?
I'm working on a project but I feel stumped on this particular section. I need to create a method that returns a boolean value true if all entries in a 2d array are false, and returns false when as little as 1 of those values is true. currently, my code inside the method resembles this:

```<code>int counter = 0;
  for (int i = 0; i < lightArray.length; i++){
     for(int j = 0; j <lightArray[0].length; i++) {
        if (lightArray[i][j] == false) {
           counter++;
           if (counter == lightArray.length * lightArray[0].length) {
              return true;
           }
        }
        else {
           return false;
        }
     }
  }
</code>```

My initital thought was that i would use a 'counter' variable so that the if statement would only return true if there was a 'counter' for every value in lightArray. After testing, it doesn't seem to register when all values are set to false.

I also tried a version of the code where this section

```<code>if (lightArray[i][j] == false) {
           counter++;
           if (counter == lightArray.length * lightArray[0].length) {
              return true;
</code>```

}

just read as this:

```<code>if (lightArray[i][j] == false) {
              return true;
</code>```

with no 'counter' variable involved at all, but when that code is in place, the method returns true as soon as it hits a single false value.

Is there another way that I am just not thinking of that I can check every value in the 2D array before returning a boolean?

答:
Usually the logic like you have should be in this form:

```<code>loop{
    if (negative_condition) return false;
}
return true;
</code>```

Notice that return true is outside of the loop.

In your case you have nested loop which should looks like this:

```<code>loop{
    loop{
        if (negative_condition) return false;
    }
}
return true;
</code>```

Looking at the above pseudo code, your Java code should look like this:

```<code>for (int i = 0; i < lightArray.length; i++){
    for(int j = 0; j <lightArray[0].length; j++) {
       if (lightArray[i][j] == true) return false;
    }
 }

 return true;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a project but I feel stumped on this particular section. I need to create a method that returns a boolean value true if all entries in a 2d array are false, and returns false when as little as 1 of those values is true. currently, my code inside the method resembles this:

int counter = 0;
  for (int i = 0; i < lightArray.length; i++){
     for(int j = 0; j <lightArray[0].length; i++) {
        if (lightArray[i][j] == false) {
           counter++;
           if (counter == lightArray.length * lightArray[0].length) {
              return true;
           }
        }
        else {
           return false;
        }
     }
  }

My initital thought was that i would use a 'counter' variable so that the if statement would only return true if there was a 'counter' for every value in lightArray. After testing, it doesn't seem to register when all values are set to false.

I also tried a version of the code where this section

if (lightArray[i][j] == false) {
           counter++;
           if (counter == lightArray.length * lightArray[0].length) {
              return true;

}

just read as this:

if (lightArray[i][j] == false) {
              return true;

with no 'counter' variable involved at all, but when that code is in place, the method returns true as soon as it hits a single false value.

Is there another way that I am just not thinking of that I can check every value in the 2D array before returning a boolean?

Body:
Usually the logic like you have should be in this form:

loop{
    if (negative_condition) return false;
}
return true;

Notice that return true is outside of the loop.

In your case you have nested loop which should looks like this:

loop{
    loop{
        if (negative_condition) return false;
    }
}
return true;

Looking at the above pseudo code, your Java code should look like this:

for (int i = 0; i < lightArray.length; i++){
    for(int j = 0; j <lightArray[0].length; j++) {
       if (lightArray[i][j] == true) return false;
    }
 }

 return true;


问:
PHP by keypress jquery
I want to make search in my username database but it doesnt recognize keypress function. also, I want to prevent search.php on first load (can't use isset because there is no button) this is my index.php

<!DOCTYPE html>

  <title></title>
  <?php  include 'search.php'; ?>

  <form method="POST">
    enter keyword to search

    <input type="text" name="textbox1" id="textbox1">

  </form>

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

<p>This is my <em>search.php</em>. the <em>connection.php</em> is working proper. so I'm not pasting it here</p>

```<?php

    include 'connection.php';

    $search_value = $_POST['textbox1'];
    $query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
    $conn_status = mysqli_query($conn, $query);

    while($row = $conn_status->fetch_assoc())
    {
        echo $row['username'] . '
';
    }
?>
```

答:
You should send the field value to your PHP page as data in your ajax request like :

```<code>$.ajax({
    type: "GET",
    url: "search.php",
    data: {textbox1: $(this).val()},
    success: function (data) {
          $("#main").html(data);
    }
});
</code>```

NOTE : I suggest the use of input event in this case since it's more efficient when tracking the user input :

```<code>$("#textbox1").on('input', function(){
    //Your logic here
});
</code>```

Title: PHP by keypress jquery

Body:
I want to make search in my username database but it doesnt recognize keypress function. also, I want to prevent search.php on first load (can't use isset because there is no button) this is my index.php

<!DOCTYPE html>

  <title></title>
  <?php  include 'search.php'; ?>

  <form method="POST">
    enter keyword to search

    <input type="text" name="textbox1" id="textbox1">

  </form>

This is my search.php. the connection.php is working proper. so I'm not pasting it here

<?php

    include 'connection.php';

    $search_value = $_POST['textbox1'];
    $query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
    $conn_status = mysqli_query($conn, $query);

    while($row = $conn_status->fetch_assoc())
    {
        echo $row['username'] . '
';
    }
?>

Body:
You should send the field value to your PHP page as data in your ajax request like :

$.ajax({
    type: "GET",
    url: "search.php",
    data: {textbox1: $(this).val()},
    success: function (data) {
          $("#main").html(data);
    }
});

NOTE : I suggest the use of input event in this case since it's more efficient when tracking the user input :

$("#textbox1").on('input', function(){
    //Your logic here
});


问:
Access is denied when debugging Process.Start from Visual Studio
```<code>var chromePath = @"C:\""Program Files(x86)""\Google\Chrome\Application\chrome.exe";
Process.Start(chromePath);
</code>```

I was debugging in Visual Studio as Administrator. But still got the exception:

```<code>System.ComponentModel.Win32Exception: 'Access is denied'
---------------------------
Microsoft Visual Studio
---------------------------
An exception has been encountered. This may be caused by an extension.
</code>```

What could go wrong? Any thoughts?

答:
The exception message is misleading. The path is incorrect. Removing the double quotes and putting a space between Files and (x86) fixes it.

Try this:

```<code>        var chromePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
        Process.Start(chromePath);
</code>```

Body:
var chromePath = @"C:\""Program Files(x86)""\Google\Chrome\Application\chrome.exe";
Process.Start(chromePath);

I was debugging in Visual Studio as Administrator. But still got the exception:

System.ComponentModel.Win32Exception: 'Access is denied'
---------------------------
Microsoft Visual Studio
---------------------------
An exception has been encountered. This may be caused by an extension.

What could go wrong? Any thoughts?

Body:
The exception message is misleading. The path is incorrect. Removing the double quotes and putting a space between Files and (x86) fixes it.

Try this:

        var chromePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
        Process.Start(chromePath);


问:
Remove item from LinkedList
Small problem i am having with a program here. I am trying to create a program that adds Words to Linked Lists within a Array depending on their hashCode, determined by my hashFunction. If they have the same value for their hashCode they get added into a Linked List. I have a small count method that counts how many times a word is in the List. It works by computing the value for their hashFunction. It then goes to that value in the array, and iterates through the LinkedList until it reaches a Null value. It has a count variable which is incremented each time it finds the word in the list. This is my code:

```<code>public class test{

    public static class Node<T>{
       public T data;
       public Node<T> next;
       public Node(){

       }

       public Node(T data, Node<T> next)
       {
          this.data = data;
          this.next = next;
       }
    }

    static Node[] array = new Node[512];

    public static void add(String word){
        int position = hashFunction(word);
        if(array[position] == null){
            array[position] = new Node(word, null);
        }else{
            Node newHead = new Node(word, array[position]);
            array[position] = newHead;
        }
    }

    public static void remove(String word){
        int remove = hashFunction(word);
        Node head = array[remove];
        if(head.data == word){
            head = head.next;
            System.out.println("Found");
        }else if(head.data != word){
            for(; array[remove] != null; array[remove] = array[remove].next){
                if(array[remove].data == word){
                    array[remove] = array[remove].next;
                }
            }
            System.out.println("Yusuf");
        }
    }

    public static int count(String word){
        int number = 0;
        int position = hashFunction(word);
        for(; array[position] != null; array[position] = array[position].next){
            if(array[position].data == word){
                number++;
            }
        }
        System.out.println(number);
        return number;
    }

    public static int hashFunction(String a){
        int sum = 1;
            for(int i = 0; i<a.length(); i++){
                char b = a.charAt(i);
                int value = (int) b;
                sum *= value;
         }
         return sum % array.length;
     }

    public static void addthings(String word, int n){
        for(int i = 0; i<n; i++){
            add(word);
        }
    }

    public static void main(String[] args) {
        addthings("abc", 500000);
        count("abc");
        count("abc");
        count("abc");
        count("abc");
        }
}
</code>```

My issue is the first time I add values in it and check how many times it occurs it works fine, but any more calls to the Count method after that returns 0 for some reason.

I have another issue too which is my remove method isn't removing the items from the Linked List I want it too. The code iterates through the List, and when it finds the item which is meant to be removed, it removes the pointer from there and points it to the next value. This isn't working however.

Can someone show me how to fix these two issues please?

Thanks.

答:
In your function if you write something Node head it means you are creating some local instance for a Node. If you set head = head.next this will simply change the state of your local instance variable not the state of your array.

You are checking if the first node contains the data which you are looking and trying to remove it then you have to remove it from your source Array(Array in which your references reside).So you can write something like this:

```<code>if(head.data == word)
   array[remove] = head.next;
</code>```

This was an example. The point is that you are not chaning things in your array but in your local variable.

```<code> public static void remove(String word){
            int remove = hashFunction(word);
            Node head = array[remove];
            if(head.data == word){
                head = head.next;
                System.out.println("Found");
            }else if(head.data != word){
                for(; array[remove] != null; array[remove] = array[remove].next){
                    if(array[remove].data == word){
                        array[remove] = array[remove].next;
                    }
                }
                System.out.println("Yusuf");
            }
        }
</code>```

A second mistake is in second clause where you just set array[remove] = array[remove].next;
 It will break your linkedlist into two different linkedlist. Suppose you have 4 elements in linkedlist A,B,C,D and you remove B and there were pointers like this A->B->C->D then you are adding no pointers from A -> C. Here you break your linkedlist.

You can use while loop that will work easily.

Title: Remove item from LinkedList

Body:
Small problem i am having with a program here. I am trying to create a program that adds Words to Linked Lists within a Array depending on their hashCode, determined by my hashFunction. If they have the same value for their hashCode they get added into a Linked List. I have a small count method that counts how many times a word is in the List. It works by computing the value for their hashFunction. It then goes to that value in the array, and iterates through the LinkedList until it reaches a Null value. It has a count variable which is incremented each time it finds the word in the list. This is my code:

public class test{

    public static class Node<T>{
       public T data;
       public Node<T> next;
       public Node(){

       }

       public Node(T data, Node<T> next)
       {
          this.data = data;
          this.next = next;
       }
    }

    static Node[] array = new Node[512];

    public static void add(String word){
        int position = hashFunction(word);
        if(array[position] == null){
            array[position] = new Node(word, null);
        }else{
            Node newHead = new Node(word, array[position]);
            array[position] = newHead;
        }
    }

    public static void remove(String word){
        int remove = hashFunction(word);
        Node head = array[remove];
        if(head.data == word){
            head = head.next;
            System.out.println("Found");
        }else if(head.data != word){
            for(; array[remove] != null; array[remove] = array[remove].next){
                if(array[remove].data == word){
                    array[remove] = array[remove].next;
                }
            }
            System.out.println("Yusuf");
        }
    }

    public static int count(String word){
        int number = 0;
        int position = hashFunction(word);
        for(; array[position] != null; array[position] = array[position].next){
            if(array[position].data == word){
                number++;
            }
        }
        System.out.println(number);
        return number;
    }

    public static int hashFunction(String a){
        int sum = 1;
            for(int i = 0; i<a.length(); i++){
                char b = a.charAt(i);
                int value = (int) b;
                sum *= value;
         }
         return sum % array.length;
     }

    public static void addthings(String word, int n){
        for(int i = 0; i<n; i++){
            add(word);
        }
    }

    public static void main(String[] args) {
        addthings("abc", 500000);
        count("abc");
        count("abc");
        count("abc");
        count("abc");
        }
}

My issue is the first time I add values in it and check how many times it occurs it works fine, but any more calls to the Count method after that returns 0 for some reason.

I have another issue too which is my remove method isn't removing the items from the Linked List I want it too. The code iterates through the List, and when it finds the item which is meant to be removed, it removes the pointer from there and points it to the next value. This isn't working however.

Can someone show me how to fix these two issues please?

Thanks.

Body:
In your function if you write something Node head it means you are creating some local instance for a Node. If you set head = head.next this will simply change the state of your local instance variable not the state of your array.

You are checking if the first node contains the data which you are looking and trying to remove it then you have to remove it from your source Array(Array in which your references reside).So you can write something like this:

if(head.data == word)
   array[remove] = head.next;

This was an example. The point is that you are not chaning things in your array but in your local variable.

 public static void remove(String word){
            int remove = hashFunction(word);
            Node head = array[remove];
            if(head.data == word){
                head = head.next;
                System.out.println("Found");
            }else if(head.data != word){
                for(; array[remove] != null; array[remove] = array[remove].next){
                    if(array[remove].data == word){
                        array[remove] = array[remove].next;
                    }
                }
                System.out.println("Yusuf");
            }
        }

A second mistake is in second clause where you just set array[remove] = array[remove].next;
 It will break your linkedlist into two different linkedlist. Suppose you have 4 elements in linkedlist A,B,C,D and you remove B and there were pointers like this A->B->C->D then you are adding no pointers from A -> C. Here you break your linkedlist.

You can use while loop that will work easily.


问:
asp pages and paypal button
I have an asp.net page in 3.5 that I have a pay pal button on but when I click on the button it just refreshes the page.  I think I need to encapsulate the paypal button in something so it is not trigging the refresh but goes to pay pal.

Anyone know a solution?  Can I use an updatePanel or iframe?

答:
I had this same issue once, I just used the following code for my button:

```<code><asp:ImageButton ID="btnPayNow" runat="server" ImageUrl="~/images/Purchase/payNowButton.jpg" PostBackUrl="https://www.paypal.com/cgi-bin/webscr"/>
</code>```

Hope that helps!

ContentLicense: CC BY-SA 2.5

Title: asp pages and paypal button

Body:
I had this same issue once, I just used the following code for my button:

<asp:ImageButton ID="btnPayNow" runat="server" ImageUrl="~/images/Purchase/payNowButton.jpg" PostBackUrl="https://www.paypal.com/cgi-bin/webscr"/>

Hope that helps!


问:
How do you split data from a textfile on an array list?
I am trying to code an array list that contains information from a text file that should add all the characters of the names together to give me a total. I have done it but it adds the spaces to, i have tried using .split(" "); but it still didnt work.
here is my code so far

```<code>    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        tempLatinName.split(" ");
        latinLength = tempLatinName;
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);
</code>```

any suggestions?

答:
If you want to get the number of characters in your string, instead of tempLatinName.split(" "); you should try latinLength = tempLatinName.replace(" ",""); and then you would get the length with the string without spaces with latinLength.Length
 More about replace here
More about Length here

Body:
I am trying to code an array list that contains information from a text file that should add all the characters of the names together to give me a total. I have done it but it adds the spaces to, i have tried using .split(" "); but it still didnt work.
here is my code so far

    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        tempLatinName.split(" ");
        latinLength = tempLatinName;
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);

any suggestions?


问:
Import complex types from another XSD
I am finding difficulty in importing and referencing a complex type from one XSD file to another. Let me illustrate my scenario with an example

Student.xsd

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="xyz"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:common="xyz"
    xmlns="xyz"
    elementFormDefault="qualified">

    <xsd:element name="student" type="student" />

    <xsd:complexType name="student">
        <xsd:sequence>
            <xsd:element name="id" type="xsd:string" />
            <xsd:element name="birth-date" type="xsd:date" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>
</code>```

Here is another XSD, Teacher.xsd, where I would like to reference the complex type student from student.xsd

Teacher.xsd

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="xyz"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:common="xyz"
    xmlns="xyz"
    elementFormDefault="qualified">

    <xsd:import schemaLocation="student.xsd"
        namespace="xyzzz" />

    <xsd:element name="teacher" type="teacher" />

    <xsd:complexType name="teacher">
        <xsd:sequence>
            <xsd:element name="id" type="xsd:string" />
            <xsd:element name="name" type="xsd:string" />

            // TODO - Refer to student from student.xsd

        </xsd:sequence>
    </xsd:complexType>

</xsd:schema>
</code>```

I have seen other Stack Overflow posts regarding the syntax for achieving this like

```<code><xs:element name="teacher" type="teacher:teacher"/>
</code>```

along with import:

```<code><xsd:import schemaLocation="xyz" namespace="xyz"/>
</code>```

but nothing seems to be working.

Can someone help me achieve this ?

答:
Use xsd:include rather than xsd:import since the XSDs are in the same namespace.

Notes

You'll want to include Student.xsd, not common.xsd.

Since the type being referenced is in the same namespace, you don't need to specify a namespace prefix:

```<code><xsd:element name="student" type="student"/>
</code>```

It's better style to name your elements and attributes differently.

See also

What's the difference between xsd:include and xsd:import?

How to reference element in other XSD's namespace?  (for complete, working example of xsd:import use for when namespaces differ)

Title: Import complex types from another XSD

Body:
I am finding difficulty in importing and referencing a complex type from one XSD file to another. Let me illustrate my scenario with an example

Student.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="xyz"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:common="xyz"
    xmlns="xyz"
    elementFormDefault="qualified">

    <xsd:element name="student" type="student" />

    <xsd:complexType name="student">
        <xsd:sequence>
            <xsd:element name="id" type="xsd:string" />
            <xsd:element name="birth-date" type="xsd:date" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

Here is another XSD, Teacher.xsd, where I would like to reference the complex type student from student.xsd

Teacher.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="xyz"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:common="xyz"
    xmlns="xyz"
    elementFormDefault="qualified">

    <xsd:import schemaLocation="student.xsd"
        namespace="xyzzz" />

    <xsd:element name="teacher" type="teacher" />

    <xsd:complexType name="teacher">
        <xsd:sequence>
            <xsd:element name="id" type="xsd:string" />
            <xsd:element name="name" type="xsd:string" />

            // TODO - Refer to student from student.xsd

        </xsd:sequence>
    </xsd:complexType>

</xsd:schema>

I have seen other Stack Overflow posts regarding the syntax for achieving this like

<xs:element name="teacher" type="teacher:teacher"/>

along with import:

<xsd:import schemaLocation="xyz" namespace="xyz"/>

but nothing seems to be working.

Can someone help me achieve this ?

Body:
Use xsd:include rather than xsd:import since the XSDs are in the same namespace.

Notes

You'll want to include Student.xsd, not common.xsd.

Since the type being referenced is in the same namespace, you don't need to specify a namespace prefix:

<xsd:element name="student" type="student"/>

It's better style to name your elements and attributes differently.

See also

What's the difference between xsd:include and xsd:import?

How to reference element in other XSD's namespace?  (for complete, working example of xsd:import use for when namespaces differ)


问:
Trouble installing Django: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-rcF9a5/Django/
I'm trying to install Django via command prompt. I used pip install Django but got this message:

```<code>Collecting Django
  Using cached `Django-2.0.tar.gz`
</code>```

Complete output from command python setup.py egg_info:

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-rcF9a5/Django/setup.py", line 32, in <module>
    version = __import__('django').get_version()
  File "django/__init__.py", line 1, in <module>
    from django.utils.version import get_version
  File "django/utils/version.py", line 61, in <module>
    @functools.lru_cache()
AttributeError: 'module' object has no attribute 'lru_cache'
</code>```

```<code>Command **`"python setup.py egg_info"`** failed with error code 1 in **/tmp/pip-build-rcF9a5/Django/**
</code>```

How do I fix this?

答:
Pip is trying to install Django 2.0, which is incompatible with Python 2. You can install the latest 1.11.x release with

```<code>pip install "Django<2"
</code>```

There’s an open issue on the Django ticket tracker to make pip install the correct version.

If you are just starting out with Django, it would be much better to use Python 3, because 1.11 is the last version to support Python 2.

Body:
I'm trying to install Django via command prompt. I used pip install Django but got this message:

Collecting Django
  Using cached `Django-2.0.tar.gz`

Complete output from command python setup.py egg_info:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-rcF9a5/Django/setup.py", line 32, in <module>
    version = __import__('django').get_version()
  File "django/__init__.py", line 1, in <module>
    from django.utils.version import get_version
  File "django/utils/version.py", line 61, in <module>
    @functools.lru_cache()
AttributeError: 'module' object has no attribute 'lru_cache'

Command **`"python setup.py egg_info"`** failed with error code 1 in **/tmp/pip-build-rcF9a5/Django/**

How do I fix this?

Body:
Pip is trying to install Django 2.0, which is incompatible with Python 2. You can install the latest 1.11.x release with

pip install "Django<2"

There’s an open issue on the Django ticket tracker to make pip install the correct version.

If you are just starting out with Django, it would be much better to use Python 3, because 1.11 is the last version to support Python 2.


问:
SailsJS : Mysterious null values
my problem is that whenever a new client is created, all the values are null in the database except the id, the name, responsable and the logo. i dont think i did a programmation mistake, so i think it is a case of callbacks race but i cant found the solution.
P.S : the problem occure only if i select and send an image file to be uploaded, in the other case, the client values are stored correctly.
P.S 2 : the problem occure in my remote server only, in local environnement all is ok !

Than you very much !

UPDATE : i included the code for my create.ejs view

This is the code of the store method in my ClientService :

```<code>store: function(req, done) {
  var name = req.param('name'),
    town = req.param('town'),
    adress = req.param('adress'),
    postalCode = req.param('postalCode'),
    telephone = req.param('telephone'),
    email = req.param('email'),
    fax = req.param('fax'),
    responsable = req.param('responsable'),
    website = req.param('website'),
    activity = req.param('activity');
  comments = req.param('comments');

  Client.create({
    name: name,
    town: town,
    adress: adress,
    postalCode: postalCode,
    telephone: telephone,
    fax: fax,
    responsable: responsable,
    website: website,
    activity: activity,
    email: email,
    comments: comments
  }).exec(function(err, client) {
    if (err) console.log(err);
    req.file('logo').upload(
      {
        dirname: sails.config.appPath + sails.config.params.logos
      },
      function(err, logo) {
        if (err) return done(err, null);
        if (logo.length !== 0) {
          client.logo = require('path').basename(logo[0].fd);
        } else {
          client.logo = 'default.png';
        }
        client.save(function(err) {
          return done(null, client);
        });
      }
    );
  });
}
</code>```

And this is the code for the EJS view :

```<code><div class="portlet-body form">
                        <!-- BEGIN FORM-->
                        <form action="store" method="POST" class="form-horizontal" enctype="multipart/form-data">
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="name">
                                                <label for="form_control_1">Nom du Client</label>
                                                <i class="fa fa-institution"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="activity">
                                                <label for="form_control_1">Activité</label>
                                                <i class="icon-star"></i>
                                            </div>
                                        </div>
                                    </div>
                                    </div>
                                <div class="row">
                                    <div class="col-md-6">
                                         <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="responsable">
                                                <label for="form_control_1">Responsable</label>
                                                <i class="icon-user"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                     <div class="form-group" style="margin-left:15px;">
                                        <div class="form-photo-label-form" >
                                                  <i class="icon-picture icon-create"></i>
                                                <label for="form_control_1" class="form-photo-create" >Photo </label>
                                        </div>
                                        <br>
                                        <div class="fileinput fileinput-new" data-provides="fileinput">
                                                    <span class="btn green btn-file">
                                                    <span class="fileinput-new"> Selectionner Fichier </span>
                                                    <span class="fileinput-exists"> Changer </span>
                                                    <input type="file" name="logo"> </span>
                                                    <span class="fileinput-filename"> </span>
                                                     <a href="javascript:;" class="close fileinput-exists" data-dismiss="fileinput"> </a>
                                        </div>
                                    </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                         <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="email">
                                                <label for="form_control_1">Email</label>
                                                <i class="fa fa-inbox"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                         <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="adress">
                                                <label for="form_control_1">Adresse</label>
                                                <i class="icon-home"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                     <div class="col-md-6">
                                        <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="postalCode">
                                                <label for="form_control_1">Code postale</label>
                                                <i class="fa fa-send"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="town">
                                                <label for="form_control_1">Ville</label>
                                                <i class=" fa fa-map"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <!--/span-->
                                </div>
                                <div class="row">
                                     <div class="col-md-6">
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                                <div class="input-icon">
                                                <textarea class="form-control" rows="3" style="height: 192px; resize:none " name="comments"></textarea>
                                                <label for="form_control_1">Commentaire</label>
                                                <i class=" fa fa-edit"></i>
                                                </div>
                                            </div>
                                            </div>
                                        </div>
                                     </div>
                                     <div class="col-md-6">
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                                    <div class="input-icon">
                                                        <input type="text" class="form-control" name="telephone">
                                                        <label for="form_control_1">Telephone</label>
                                                        <i class="icon-screen-smartphone"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                                    <div class="input-icon">
                                                        <input type="text" class="form-control" name="fax">
                                                        <label for="form_control_1">Fax</label>
                                                    <i class="fa fa-fax"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                                    <div class="input-icon">
                                                        <input type="text" class="form-control" name="website">
                                                        <label for="form_control_1">Site Internet</label>
                                                        <i class=" fa fa-internet-explorer"></i>
                                                     </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>

                    <div class="form-actions right">
                        <button type="button" class="btn default">Annuler</button>
                        <button type="submit" class="btn green"><i class="fa fa-check"></i> Enregistrer</button>
                    </div>
                </form>
</code>```

答: Thanks everybody. I solved the problem by putting the file input at the end the form. Like you suggested, the values after the file input were reset after the upload of the file</p>

Title: SailsJS : Mysterious null values

Body:
my problem is that whenever a new client is created, all the values are null in the database except the id, the name, responsable and the logo. i dont think i did a programmation mistake, so i think it is a case of callbacks race but i cant found the solution.
P.S : the problem occure only if i select and send an image file to be uploaded, in the other case, the client values are stored correctly.
P.S 2 : the problem occure in my remote server only, in local environnement all is ok !

Than you very much !

UPDATE : i included the code for my create.ejs view

This is the code of the store method in my ClientService :

store: function(req, done) {
  var name = req.param('name'),
    town = req.param('town'),
    adress = req.param('adress'),
    postalCode = req.param('postalCode'),
    telephone = req.param('telephone'),
    email = req.param('email'),
    fax = req.param('fax'),
    responsable = req.param('responsable'),
    website = req.param('website'),
    activity = req.param('activity');
  comments = req.param('comments');

  Client.create({
    name: name,
    town: town,
    adress: adress,
    postalCode: postalCode,
    telephone: telephone,
    fax: fax,
    responsable: responsable,
    website: website,
    activity: activity,
    email: email,
    comments: comments
  }).exec(function(err, client) {
    if (err) console.log(err);
    req.file('logo').upload(
      {
        dirname: sails.config.appPath + sails.config.params.logos
      },
      function(err, logo) {
        if (err) return done(err, null);
        if (logo.length !== 0) {
          client.logo = require('path').basename(logo[0].fd);
        } else {
          client.logo = 'default.png';
        }
        client.save(function(err) {
          return done(null, client);
        });
      }
    );
  });
}

And this is the code for the EJS view :

                        <form action="store" method="POST" class="form-horizontal" enctype="multipart/form-data">

                                                <input type="text" class="form-control" name="name">
                                                Nom du Client

                                                <input type="text" class="form-control" name="activity">
                                                Activité

                                                <input type="text" class="form-control" name="responsable">
                                                Responsable

                                                Photo

                                                     Selectionner Fichier
                                                     Changer
                                                    <input type="file" name="logo">

                                                <input type="text" class="form-control" name="email">
                                                Email

                                                <input type="text" class="form-control" name="adress">
                                                Adresse

                                                <input type="text" class="form-control" name="postalCode">
                                                Code postale

                                                <input type="text" class="form-control" name="town">
                                                Ville

                                                <textarea class="form-control" rows="3" style="height: 192px; resize:none " name="comments"></textarea>
                                                Commentaire

                                                        <input type="text" class="form-control" name="telephone">
                                                        Telephone

                                                        <input type="text" class="form-control" name="fax">
                                                        Fax

                                                        <input type="text" class="form-control" name="website">
                                                        Site Internet

                        <button type="button" class="btn default">Annuler</button>
                        <button type="submit" class="btn green"> Enregistrer</button>

                </form>


问:
Is "JavaScript alert() function" a function declaration or function expression?
I know that alert() is built-in function in JavaScript.

But is it a function declaration:

```<code>function alert() { ... }
</code>```

or function expression?

```<code>var alert = function() { ... }
</code>```

So, are we using the function's name or the variable's name when we call it?
and likewise prompt() and confirm() ..

Thanks in advance.

答:
But is it a function declaration or function expression?

Neither. It is a function.

Function expressions and declarations are bits of JavaScript syntax used to create functions. How alert is created is an implementation detail of the browser (and you'll probably find that it is written in C++ and exposed to the JS engine as a library).

So, are we using the function's name or the variable's name when we call it?

You use a variable (or a property, or a constant) to get a reference to the function, which you then call.

The name is mostly used by debugging tools to report on which function is being used for something.

Body:
I know that alert() is built-in function in JavaScript.

But is it a function declaration:

function alert() { ... }

or function expression?

var alert = function() { ... }

So, are we using the function's name or the variable's name when we call it?
and likewise prompt() and confirm() ..

Thanks in advance.


问:
Laravel 5.5 form confirmed by password
Im making form via LaravelCollective forms in my app.
I have email changing form with fields:
New e-mail
Confirm Email
Password

I need to validate user password on this form with user password in database. Can i do it via Validate?

My form:

```<code>{{ Form::model($user, ['route' => ['profile.email.update']]) }}
<div class="form-group row">
    <div class="col-md-12">
        <h2>Edytuj email</h2>
        <div class="form-group">
            <label for="edit-page-email">Nowy adres email</label>

            {{Form::text('email',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}
        </div>
        <div class="form-group">
            <label for="edit-page-repemail">Nowy adres email (powtórz)</label>
            {{Form::text('email_confirmation',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}
        </div>
        <div class="form-group">
            <label for="edit-page-pass">Twoje hasło</label>
                {{Form::password('password',['class' => 'form-control', 'id'=>'edit-page-npass'])}}
        </div>
        <div class="col-md-12 text-center">
                {{Form::submit('Zapisz zmiany',['class' => 'btn btn-primary btm-sm']) }}
            <a href="#" class="btn btn-link btn-sm font-red" title="Anuluj">Anuluj</a>
        </div>
    </div>
</div>
{{Form::close()}}
</code>```

And validation is:

```<code> $request->validate([
            'email' => 'required|confirmed',
            'email_confirmation' => 'required',
            'password' => 'required|confirmed',
        ]);
</code>```

Any ideas how can i do this?

答:
Not sure when you say I need to validate user password on this form with user password in database

However the password and password confirm validation should look like the following

```<code>{{ Form::password('password',['class'=> 'form-control','placeholder'=>'Enter your Password']) }}
{{ Form::password('password_confirmation', ['class' => 'form-control','placeholder'=>'Re-enter your Password']) }}
</code>```

Now your validation rules should be

```<code>'password'   => 'required|confirmed',
</code>```

Title: Laravel 5.5 form confirmed by password

Body:
Im making form via LaravelCollective forms in my app.
I have email changing form with fields:
New e-mail
Confirm Email
Password

I need to validate user password on this form with user password in database. Can i do it via Validate?

My form:

{{ Form::model($user, ['route' => ['profile.email.update']]) }}

Edytuj email

            Nowy adres email

            {{Form::text('email',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}

            Nowy adres email (powtórz)
            {{Form::text('email_confirmation',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}

            Twoje hasło
                {{Form::password('password',['class' => 'form-control', 'id'=>'edit-page-npass'])}}

                {{Form::submit('Zapisz zmiany',['class' => 'btn btn-primary btm-sm']) }}
            Anuluj

{{Form::close()}}

And validation is:

 $request->validate([
            'email' => 'required|confirmed',
            'email_confirmation' => 'required',
            'password' => 'required|confirmed',
        ]);

Any ideas how can i do this?

Body:
Not sure when you say I need to validate user password on this form with user password in database

However the password and password confirm validation should look like the following

{{ Form::password('password',['class'=> 'form-control','placeholder'=>'Enter your Password']) }}
{{ Form::password('password_confirmation', ['class' => 'form-control','placeholder'=>'Re-enter your Password']) }}

Now your validation rules should be

'password'   => 'required|confirmed',


问:
Compare end punctuation in columns A and B in Excel (VBA?)
I'm trying to catch and resolve instances in Excel where the end punctuation (in my case an empty line) in cells in column B doesn't match the end punctuation in cells in column A. For background, column A contains English text and column B contains translated version of the very same content. The problem is - in some cases the source text has empty/blank lines at the end of text in cells, while some translated text doesn't and I need to find and fix those instances.

So, I'm trying to:

1) Compare the last line of each cell in column A to the adjacent cell in the same row in column B.

2) If the cell in column A has a blank line at the end and corresponding cell in column B doesn't, add such blank line to the end of cell in column B.

Example:

```<code>         **Column A**    **Column B**
Row 1       Text X          Text Y
            \n
Row 2       Text X          Text Y
Row 3       Text X          Text Y
            \n
Row 4       Text X          Text Y
            \n              \n
</code>```

So, in the example above, I need to flag cells B1 and B3 because they don't have a line feed (\n) at the end, similar to their counterparts in cells A1 and A3.

Thank you in advance!

答:
This would look for at whether there is a line feed in the cell and if there is it will add it to column B too.

```<code>Sub foo2()
FindString = "/n"
LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row in column A with data
For i = 1 To LastRow
Set Rng = Sheet1.Cells(i, 1).Find(What:=FindString) 'look for the line feed at in this cell
            If Not Rng Is Nothing Then 'if found
                Sheet1.Cells(i, 2).Value = Sheet1.Cells(i, 2).Value & "/n" 'add line feed to column B
            End If
Next i
End Sub
</code>```

Or if you are not looking for the string "/n" and you are looking for the line feed then I believe something like this would do it:

```<code>Sub foo2()
LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row in column A with data
For i = 1 To LastRow
Set Rng = Sheet1.Cells(i, 1).Find(What:= vbLf) 'look for the line feed at in this cell
            If Not Rng Is Nothing Then 'if found
                Sheet1.Cells(i, 2).Value = Sheet1.Cells(i, 2).Value & vbLf 'add line feed to column B
            End If
Next i
End Sub
</code>```

UPDATE:

```<code>Sub foo2()
Dim Str as Variant
    LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row in column A with data
    For i = 1 To LastRow
        Str = Sheet1.Cells(i, 1).Value
        If Right(Str, 1) = vbLf Then 'if found
                Sheet1.Cells(i, 2).Value = Sheet1.Cells(i, 2).Value & vbLf 'add line feed to column B
            End If
Next i
End Sub
</code>```

Body:
I'm trying to catch and resolve instances in Excel where the end punctuation (in my case an empty line) in cells in column B doesn't match the end punctuation in cells in column A. For background, column A contains English text and column B contains translated version of the very same content. The problem is - in some cases the source text has empty/blank lines at the end of text in cells, while some translated text doesn't and I need to find and fix those instances.

So, I'm trying to:

1) Compare the last line of each cell in column A to the adjacent cell in the same row in column B.

2) If the cell in column A has a blank line at the end and corresponding cell in column B doesn't, add such blank line to the end of cell in column B.

Example:

         **Column A**    **Column B**
Row 1       Text X          Text Y
            \n
Row 2       Text X          Text Y
Row 3       Text X          Text Y
            \n
Row 4       Text X          Text Y
            \n              \n

So, in the example above, I need to flag cells B1 and B3 because they don't have a line feed (\n) at the end, similar to their counterparts in cells A1 and A3.

Thank you in advance!

Body:
This would look for at whether there is a line feed in the cell and if there is it will add it to column B too.

Sub foo2()
FindString = "/n"
LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row in column A with data
For i = 1 To LastRow
Set Rng = Sheet1.Cells(i, 1).Find(What:=FindString) 'look for the line feed at in this cell
            If Not Rng Is Nothing Then 'if found
                Sheet1.Cells(i, 2).Value = Sheet1.Cells(i, 2).Value & "/n" 'add line feed to column B
            End If
Next i
End Sub

Or if you are not looking for the string "/n" and you are looking for the line feed then I believe something like this would do it:

Sub foo2()
LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row in column A with data
For i = 1 To LastRow
Set Rng = Sheet1.Cells(i, 1).Find(What:= vbLf) 'look for the line feed at in this cell
            If Not Rng Is Nothing Then 'if found
                Sheet1.Cells(i, 2).Value = Sheet1.Cells(i, 2).Value & vbLf 'add line feed to column B
            End If
Next i
End Sub

UPDATE:

Sub foo2()
Dim Str as Variant
    LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row in column A with data
    For i = 1 To LastRow
        Str = Sheet1.Cells(i, 1).Value
        If Right(Str, 1) = vbLf Then 'if found
                Sheet1.Cells(i, 2).Value = Sheet1.Cells(i, 2).Value & vbLf 'add line feed to column B
            End If
Next i
End Sub


问:
Why do I get an error of can't make a table of more 2^31 elements in R
Hello I have a dataframe record in R of dimension  8 obs 60 variables , with the missing values replaced by NA and the other values being words.

When I try to tabulate the dataframe like this feeds<-table(record) I get an error saying :

```<code>Error in table(record) : attempt to make a table with >= 2^31 elements
</code>```

Some sample elements/structure of my dataframe are

```<code>INC - CORP Application Issue    INC - CORP Issue    INC - PC Software Issue
Affected User                   Affected User       Affected User
Attachment                      Attachment          Attachment
Description / Priority          Business Critica..  Configuration Item
Knowledge Search                Client ID           Contact Info
NA                              Description / Pr..  NA
</code>```

I don't understand the error as the elements in the dataframe are clearly not even close to 2^31.

Thanks for your time.

答:
its old topic but it might help someone else that reason I posting it.
I had the same problem and I found it online solution from somewhere I don't remember and  it worked for me perfectly.
hopefully works for someone who needs.</p>

```<code>solution<-as.data.frame(table(unlist(record)))
</code>```

Body:
Hello I have a dataframe record in R of dimension  8 obs 60 variables , with the missing values replaced by NA and the other values being words.

When I try to tabulate the dataframe like this feeds<-table(record) I get an error saying :

Error in table(record) : attempt to make a table with >= 2^31 elements

Some sample elements/structure of my dataframe are

INC - CORP Application Issue    INC - CORP Issue    INC - PC Software Issue
Affected User                   Affected User       Affected User
Attachment                      Attachment          Attachment
Description / Priority          Business Critica..  Configuration Item
Knowledge Search                Client ID           Contact Info
NA                              Description / Pr..  NA

I don't understand the error as the elements in the dataframe are clearly not even close to 2^31.

Thanks for your time.

Body:
its old topic but it might help someone else that reason I posting it.
I had the same problem and I found it online solution from somewhere I don't remember and  it worked for me perfectly.
hopefully works for someone who needs.

solution<-as.data.frame(table(unlist(record)))


问:
Hexagonal binning with exponential random numbers
I have been following the block that uses hexagonal binning of random points with the normal distribution but instead trying to tailor it to the exponential distribution.

The code runs, but the output seems to show a mirror along the x-axis. That is, the points are all clustered along the upper-left instead of lower-left. I've been playing with the transform function but can't quite get it. What am I missing? JSFiddle

```<code><!DOCTYPE html>
<style>

.hexagon {
  stroke: #000;
  stroke-width: 0.5px;
}

</style>
<svg width="500" height="200"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
<script>

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var randomX = d3.randomExponential(1 / 30),
    randomY = d3.randomExponential(1 / 30),
    points = d3.range(2000).map(function() { return [randomX(), randomY()]; });

var color = d3.scaleSequential(d3.interpolateLab("white", "steelblue"))
    .domain([0, 20]);

var hexbin = d3.hexbin()
    .radius(5)
    .extent([[0, 0], [width, height]]);

var x = d3.scaleLinear()
    .domain([0, width])
    .range([0, width]);

var y = d3.scaleLinear()
    .domain([0, height])
    .range([height, 0]);

g.append("clipPath")
    .attr("id", "clip")
  .append("rect")
    .attr("width", width)
    .attr("height", height);

g.append("g")
    .attr("class", "hexagon")
    .attr("clip-path", "url(#clip)")
  .selectAll("path")
  .data(hexbin(points))
  .enter().append("path")
    .attr("d", hexbin.hexagon())
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
    .attr("fill", function(d) { return color(d.length); });

</script>
</code>```

答:
You set your scales, but you never use them:

```<code>.attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")";
})
</code>```

Solution: use your scales:

```<code>.attr("transform", function(d) {
    return "translate(" + x(d.x) + "," + y(d.y) + ")";
    //scales here --------^--------------^
})
</code>```

Here is your code with that change:

var svg = d3.select("svg"),
  margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom,
  g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var randomX = d3.randomExponential(1 / 30),
  randomY = d3.randomExponential(1 / 30),
  points = d3.range(2000).map(function() {
    return [randomX(), randomY()];
  });

var color = d3.scaleSequential(d3.interpolateLab("white", "steelblue"))
  .domain([0, 20]);

var hexbin = d3.hexbin()
  .radius(5)
  .extent([
    [0, 0],
    [width, height]
  ]);

var x = d3.scaleLinear()
  .domain([0, width])
  .range([0, width]);

var y = d3.scaleLinear()
  .domain([0, height])
  .range([height, 0]);

g.append("clipPath")
  .attr("id", "clip")
  .append("rect")
  .attr("width", width)
  .attr("height", height);

g.append("g")
  .attr("class", "hexagon")
  .attr("clip-path", "url(#clip)")
  .selectAll("path")
  .data(hexbin(points))
  .enter().append("path")
  .attr("d", hexbin.hexagon())
  .attr("transform", function(d) {
    return "translate(" + x(d.x) + "," + y(d.y) + ")";
  })
  .attr("fill", function(d) {
    return color(d.length);
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hexagon {
  stroke: #000;
  stroke-width: 0.5px;
}</code>```

<svg width="500" height="200"></svg>

```

Body:
I have been following the block that uses hexagonal binning of random points with the normal distribution but instead trying to tailor it to the exponential distribution.

The code runs, but the output seems to show a mirror along the x-axis. That is, the points are all clustered along the upper-left instead of lower-left. I've been playing with the transform function but can't quite get it. What am I missing? JSFiddle

<!DOCTYPE html>

<svg width="500" height="200"></svg>

Body:
You set your scales, but you never use them:

.attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")";
})

Solution: use your scales:

.attr("transform", function(d) {
    return "translate(" + x(d.x) + "," + y(d.y) + ")";
    //scales here --------^--------------^
})

Here is your code with that change:

var svg = d3.select("svg"),
  margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom,
  g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var randomX = d3.randomExponential(1 / 30),
  randomY = d3.randomExponential(1 / 30),
  points = d3.range(2000).map(function() {
    return [randomX(), randomY()];
  });

var color = d3.scaleSequential(d3.interpolateLab("white", "steelblue"))
  .domain([0, 20]);

var hexbin = d3.hexbin()
  .radius(5)
  .extent([
    [0, 0],
    [width, height]
  ]);

var x = d3.scaleLinear()
  .domain([0, width])
  .range([0, width]);

var y = d3.scaleLinear()
  .domain([0, height])
  .range([height, 0]);

g.append("clipPath")
  .attr("id", "clip")
  .append("rect")
  .attr("width", width)
  .attr("height", height);

g.append("g")
  .attr("class", "hexagon")
  .attr("clip-path", "url(#clip)")
  .selectAll("path")
  .data(hexbin(points))
  .enter().append("path")
  .attr("d", hexbin.hexagon())
  .attr("transform", function(d) {
    return "translate(" + x(d.x) + "," + y(d.y) + ")";
  })
  .attr("fill", function(d) {
    return color(d.length);
  });

.hexagon {
  stroke: #000;
  stroke-width: 0.5px;
}

<svg width="500" height="200"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>


问:
How can I calculate Precision and Recall for sentiment analysis multi-class classifier using Confusion Matrix?
I wonder how to compute precision and recall using a confusion matrix  sentiment analysis multi-class classifier using Confusion Matrix. I have a dataset of 5000 texts and I did human labeling for a sample of 100. Now, I would like to compute the Precision and Recall for the classifier based on this sample of data. I have three classes; Positive, Neutral and Negative.

So how can I compute these metrics for each class?

As I am new here in stackoverflow, I couldn't illustrate the confusion matrix I have, so let us assume that we have the following confusion matrix:

```<code>red color   > Negative
green color > Positive
purple color> Neutral
</code>```

答:
you can measure

precision=TPos/(TPos+TNeg+TNeu)  i.e 30/(30+20+10)=50% ,

recall=TPos/(TPos+FNeg+FNeu) i.e 30/(30+50+20)=30% ,

F-measure=2*precision*recall/(precision+recall)=37.5% ,and

Accuracy(all true)/(all data) =30+60+80/300=56.7% .

for more http://blog.kaggle.com/2015/10/23/scikit-learn-video-9-better-evaluation-of-classification-models/

Body:
I wonder how to compute precision and recall using a confusion matrix  sentiment analysis multi-class classifier using Confusion Matrix. I have a dataset of 5000 texts and I did human labeling for a sample of 100. Now, I would like to compute the Precision and Recall for the classifier based on this sample of data. I have three classes; Positive, Neutral and Negative.

So how can I compute these metrics for each class?

As I am new here in stackoverflow, I couldn't illustrate the confusion matrix I have, so let us assume that we have the following confusion matrix:

red color   > Negative
green color > Positive
purple color> Neutral


问:
Decrease the increase of value in database
My starting value is 18, for every +1 increase in that number the increase of value should decrease. Basically so it gets harder to inrease this value if you have more of it. The increase should be of 2% less that the previous increase as shown below.

Right now i only got a steady increase of 2 for every run.

```<code>$Strengthvalue = 2 + $row['strength'];
</code>```

18 = +2 (increase)

19 = +1.96 (increase)

20 = +1.92 (increase)

答:
i think you need to change the sign value to - as such :</p>

```<code>$Strengthvalue = 2 + $row['strength'];
$stengthvalue = -0.04 + $Strengthvalue // to decrease current value
</code>```

Body:
My starting value is 18, for every +1 increase in that number the increase of value should decrease. Basically so it gets harder to inrease this value if you have more of it. The increase should be of 2% less that the previous increase as shown below.

Right now i only got a steady increase of 2 for every run.

$Strengthvalue = 2 + $row['strength'];

18 = +2 (increase)

19 = +1.96 (increase)

20 = +1.92 (increase)

Body:
i think you need to change the sign value to - as such :

$Strengthvalue = 2 + $row['strength'];
$stengthvalue = -0.04 + $Strengthvalue // to decrease current value


问:
'No such file or directory' yet it exists?
I am relatively new to Stack Overflow and Python so please excuse me.
I ran into an issue with Jupyter trying to open my notebook.  Specifically, this error is:

```<code>Unreadable Notebook: /home/vagrant/Notebook 1.ipynb NotJSONError('Notebook does not appear to be JSON: u\'{\\n "cells": [\\n {\\n "cell_type": "...',)
</code>```

I am trying to recover this file as it is pretty crucial!  I discovered there is hidden folder accessible by the terminal called .ipynb_checkpoints and after listing all contents in this folder I am presented with this.

```<code>-rw-rw-r-- 1 vagrant vagrant 656710 Dec  6 17:25 Notebook 1-checkpoint.ipynb

-rw-rw-r-- 1 vagrant vagrant  26332 Oct 19 21:47 Lab08-checkpoint.ipynb

-rw-rw-r-- 1 vagrant vagrant     72 Nov 17 16:35 Untitled-checkpoint.ipynb
</code>```

The top one Notebook 1-checkpoint.ipynb is the file I would like to recover.  Can anyone please help me with this?

When I try to do this:

```<code>cp Notebook 1-checkpoint.ipynb /home/vagrant/Desktop/
</code>```

I am presented with this:

```<code>cp: cannot stat ‘Notebook’: No such file or directory
cp: cannot stat ‘1-checkpoint.ipynb’: No such file or directory
</code>```

答:
You need to use the escape charachter '\' before spaces as stated by @theBrainyGeek
or quotes:
cp "40126684_Notebook 1-checkpoint.ipynb" /home/vagrant/Desktop/

Body:
I am relatively new to Stack Overflow and Python so please excuse me.
I ran into an issue with Jupyter trying to open my notebook.  Specifically, this error is:

Unreadable Notebook: /home/vagrant/Notebook 1.ipynb NotJSONError('Notebook does not appear to be JSON: u\'{\\n "cells": [\\n {\\n "cell_type": "...',)

I am trying to recover this file as it is pretty crucial!  I discovered there is hidden folder accessible by the terminal called .ipynb_checkpoints and after listing all contents in this folder I am presented with this.

-rw-rw-r-- 1 vagrant vagrant 656710 Dec  6 17:25 Notebook 1-checkpoint.ipynb

-rw-rw-r-- 1 vagrant vagrant  26332 Oct 19 21:47 Lab08-checkpoint.ipynb

-rw-rw-r-- 1 vagrant vagrant     72 Nov 17 16:35 Untitled-checkpoint.ipynb

The top one Notebook 1-checkpoint.ipynb is the file I would like to recover.  Can anyone please help me with this?

When I try to do this:

cp Notebook 1-checkpoint.ipynb /home/vagrant/Desktop/

I am presented with this:

cp: cannot stat ‘Notebook’: No such file or directory
cp: cannot stat ‘1-checkpoint.ipynb’: No such file or directory


问:
How to know it is auto reply mail in Microsoft Graph?
I am using Microsoft Graph API to get mails.

```<code>GET /v1.0/me/messages
</code>```

It returns

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('576552d5-3bc0-42a6-a23d-bfceb405db23')/messages",
    "@odata.nextLink": "https://graph.microsoft.com/v1.0/me/messages?$skip=11",
    "value": [
        {
            "@odata.etag": "W/\"HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi2tx\"",
            "id": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI2MgBGAAAAAACUbnk-iwQZRbXMgkfKtmYhBwCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAACpTc-InBsuTYwTUBb_VIb4AACqNTk9AAA=",
            "createdDateTime": "2017-12-06T21:57:09Z",
            "lastModifiedDateTime": "2017-12-06T21:57:19Z",
            "changeKey": "HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi8tx",
            "categories": [],
            "receivedDateTime": "2017-12-06T21:57:09Z",
            "sentDateTime": "2017-12-06T21:56:16Z",
            "hasAttachments": false,
            "internetMessageId": "<e74a536a53d245e49d779d47f774f4a0@CO2PR00MB0214.namprd00.prod.outlook.com>",
            "subject": "Automatic reply: Hi",
            "bodyPreview": "I am OOF.",
            "importance": "normal",
            "parentFolderId": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAuAAAAAACUbnk-iwQZRbXMgkfKtmYhAQCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAAA=",
            "conversationId": "AAQkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAQAPekscpearpHmBFbhG0DKuc=",
            "isDeliveryReceiptRequested": null,
            "isReadReceiptRequested": false,
            "isRead": true,
            "isDraft": false,
            "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI5MgBGAAAAAACUbnk%2FiwQZRbXMgkfKtmYhBwCpTc%2FInBsuTYwTUBb%2BVIb4AAAAAAEMAACpTc%2FInBsuTYwTUBb%2BVIb4AACqNTk2AAA%3D&exvsurl=2&viewmodel=ReadMessageItem",
            "inferenceClassification": "focused",
            "body": {
                "contentType": "html",
                "content": "hi"
            },
            "sender": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "from": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "toRecipients": [
                {
                    "emailAddress": {
                        "name": "Rose",
                        "address": "rose@example.com"
                    }
                }
            ],
            "ccRecipients": [],
            "bccRecipients": [],
            "replyTo": []
        }
    ]
}
</code>```

I didn't find any field related with determine whether it is an auto reply mail.

Right now I am using

```<code>mail.subject.startsWith('Automatic reply:')
</code>```

to determine whether is auto reply mail in code.

However, it is not reliable. Because sometimes I got mails starting with a different language such as Resposta automática:.

So how to know it is auto reply mail correctly?

答:
Just found another interesting API getMailTips, however this can only help determine the auto mail if the other user is Outlook or Office 365 user.

Copy the demo below for convenience.

```<code>POST https://graph.microsoft.com/api/beta/users/{id|userPrincipalName}/getMailTips

{
    "EmailAddresses": [
        "danas@contoso.onmicrosoft.com",
        "fannyd@contoso.onmicrosoft.com"
    ],
    "MailTipsOptions": "automaticReplies, mailboxFullStatus"
}
</code>```

It will return something like

```<code>{
    "@odata.context":"https://graph.microsoft.com/api/beta/$metadata#Collection(microsoft.graph.mailTips)",
    "value":[
        {
            "emailAddress":{
                "name":"",
                "address":"danas@contoso.onmicrosoft.com"
            },
            "automaticReplies":{
                "message":"<style type=\"text/css\" style=\"\">\r\n<!--\r\np\r\n\t{margin-top:0;\r\n\tmargin-bottom:0}\r\n-->\r\n</style>\r\n<div dir=\"ltr\">\r\n<div id=\"x_divtagdefaultwrapper\" style=\"font-size:12pt; color:#000000; background-color:#FFFFFF; font-family:Calibri,Arial,Helvetica,sans-serif\">\r\n<p>Hi, I am on vacation right now. I'll get back to you after I return.<br>\r\n</p>\r\n</div>\r\n</div>",
                "messageLanguage":{
                    "locale":"en-US",
                    "displayName":"English (United States)"
                }
            },
            "mailboxFull":false
        },
        {
            "emailAddress":{
                "name":"",
                "address":"fannyd@contoso.onmicrosoft.com"
            },
            "automaticReplies":{
                "message":""
            },
            "mailboxFull":false
        }
    ]
}
</code>```

Body:
I am using Microsoft Graph API to get mails.

GET /v1.0/me/messages

It returns

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('576552d5-3bc0-42a6-a23d-bfceb405db23')/messages",
    "@odata.nextLink": "https://graph.microsoft.com/v1.0/me/messages?$skip=11",
    "value": [
        {
            "@odata.etag": "W/\"HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi2tx\"",
            "id": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI2MgBGAAAAAACUbnk-iwQZRbXMgkfKtmYhBwCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAACpTc-InBsuTYwTUBb_VIb4AACqNTk9AAA=",
            "createdDateTime": "2017-12-06T21:57:09Z",
            "lastModifiedDateTime": "2017-12-06T21:57:19Z",
            "changeKey": "HwAAABYAAACpTc/InBsuTYwTUBb+VIb4AACqi8tx",
            "categories": [],
            "receivedDateTime": "2017-12-06T21:57:09Z",
            "sentDateTime": "2017-12-06T21:56:16Z",
            "hasAttachments": false,
            "internetMessageId": "<e74a536a53d245e49d779d47f774f4a0@CO2PR00MB0214.namprd00.prod.outlook.com>",
            "subject": "Automatic reply: Hi",
            "bodyPreview": "I am OOF.",
            "importance": "normal",
            "parentFolderId": "AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAuAAAAAACUbnk-iwQZRbXMgkfKtmYhAQCpTc-InBsuTYwTUBb_VIb4AAAAAAEMAAA=",
            "conversationId": "AAQkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA2ODZlMDI5MgAQAPekscpearpHmBFbhG0DKuc=",
            "isDeliveryReceiptRequested": null,
            "isReadReceiptRequested": false,
            "isRead": true,
            "isDraft": false,
            "webLink": "https://outlook.office365.com/owa/?ItemID=AAMkADBlZTUwNTkxLWVmODgtNDVhNC1iZjhlLTdjNjA1ODZlMDI5MgBGAAAAAACUbnk%2FiwQZRbXMgkfKtmYhBwCpTc%2FInBsuTYwTUBb%2BVIb4AAAAAAEMAACpTc%2FInBsuTYwTUBb%2BVIb4AACqNTk2AAA%3D&exvsurl=2&viewmodel=ReadMessageItem",
            "inferenceClassification": "focused",
            "body": {
                "contentType": "html",
                "content": "hi"
            },
            "sender": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "from": {
                "emailAddress": {
                    "name": "Jack",
                    "address": "jack@example.com"
                }
            },
            "toRecipients": [
                {
                    "emailAddress": {
                        "name": "Rose",
                        "address": "rose@example.com"
                    }
                }
            ],
            "ccRecipients": [],
            "bccRecipients": [],
            "replyTo": []
        }
    ]
}

I didn't find any field related with determine whether it is an auto reply mail.

Right now I am using

mail.subject.startsWith('Automatic reply:')

to determine whether is auto reply mail in code.

However, it is not reliable. Because sometimes I got mails starting with a different language such as Resposta automática:.

So how to know it is auto reply mail correctly?

Body:
Just found another interesting API getMailTips, however this can only help determine the auto mail if the other user is Outlook or Office 365 user.

Copy the demo below for convenience.

POST https://graph.microsoft.com/api/beta/users/{id|userPrincipalName}/getMailTips

{
    "EmailAddresses": [
        "danas@contoso.onmicrosoft.com",
        "fannyd@contoso.onmicrosoft.com"
    ],
    "MailTipsOptions": "automaticReplies, mailboxFullStatus"
}

It will return something like

{
    "@odata.context":"https://graph.microsoft.com/api/beta/$metadata#Collection(microsoft.graph.mailTips)",
    "value":[
        {
            "emailAddress":{
                "name":"",
                "address":"danas@contoso.onmicrosoft.com"
            },
            "automaticReplies":{
                "message":"<style type=\"text/css\" style=\"\">\r\n<!--\r\np\r\n\t{margin-top:0;\r\n\tmargin-bottom:0}\r\n-->\r\n</style>\r\n<div dir=\"ltr\">\r\n<div id=\"x_divtagdefaultwrapper\" style=\"font-size:12pt; color:#000000; background-color:#FFFFFF; font-family:Calibri,Arial,Helvetica,sans-serif\">\r\n<p>Hi, I am on vacation right now. I'll get back to you after I return.<br>\r\n</p>\r\n</div>\r\n</div>",
                "messageLanguage":{
                    "locale":"en-US",
                    "displayName":"English (United States)"
                }
            },
            "mailboxFull":false
        },
        {
            "emailAddress":{
                "name":"",
                "address":"fannyd@contoso.onmicrosoft.com"
            },
            "automaticReplies":{
                "message":""
            },
            "mailboxFull":false
        }
    ]
}


问:
How to create .certSigningRequest and .p12 file using fastlane
I created a new mobile provisioning profile and certificate using fastlane.

Found the certificate xxxxxxxx (iOS Distribution) which is installed on the local machine. Using this one.

"Creating new provisioning profile for 'xxxxxxxxx' with name 'xxxxxxxxxxx AppStore' for 'ios' platform".

So now i have to create the .certSigningRequest and .p12 for push Notification configuration. How do i do this using fastlane.

答:
You can use pem, another fastlane tool, to take care of your push notification profiles:
https://docs.fastlane.tools/actions/pem/

Running fastlane pem will:

Create a new signing request

Create a new push certification

Download the certificate

Generate a new .pem file in the current working directory, which you can upload to your server

Magic :)


答:
It's a javascript predefined window.alert() method.
You call the method into action when you use alert();</p>

Title: Is "JavaScript alert() function" a function declaration or function expression?


问:
I can't install python-ldap
When I run the following command:

```<code>sudo pip install python-ldap
</code>```

I get this error:

In file included from Modules/LDAPObject.c:9:

Modules/errors.h:8: fatal error: lber.h: No such file or directory

Any ideas how to fix this?

答:
The python-ldap is based on OpenLDAP, so you need to have the development files (headers) in order to compile the Python module. If you're on Ubuntu, the package is called libldap2-dev.

Debian/Ubuntu:

```<code>sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev
</code>```

RedHat/CentOS:

```<code>sudo yum install python-devel openldap-devel
</code>```

Title: I can't install python-ldap

Body:
When I run the following command:

sudo pip install python-ldap

I get this error:

In file included from Modules/LDAPObject.c:9:

Modules/errors.h:8: fatal error: lber.h: No such file or directory

Any ideas how to fix this?

Body:
The python-ldap is based on OpenLDAP, so you need to have the development files (headers) in order to compile the Python module. If you're on Ubuntu, the package is called libldap2-dev.

Debian/Ubuntu:

sudo apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev

RedHat/CentOS:

sudo yum install python-devel openldap-devel

ContentLicense: CC BY-SA 4.0


问:
Assistance with LEFT JOIN.
Trying to get a null value when the count = 0. Below is the code that I using to count the number of sites that fit a certain criteria. In this case, code beginning with 11 or 21. There is a question of similar construct but it seems as if mine is of a simpler nature.

```<code> SELECT
 [Area],
 COUNT(*) AS [Number of Sites]
 FROM
 dbo.sizeclassreport
 Where area='000005' and (code like '11%' or code like '21%')
 GROUP BY
 [area]
 UNION ALL
</code>```

So from responses, it seems as if I need to construct an additional table (tally table as the other question says) that lists the areas then do a left join. Below is my first attempt at this.

```<code> Create TABLE areas
 (
 Area char(6), NOT NULL
 CONSTRAINT PK_AREAS PRIMARY KEY (areas)

 Select * from areas
 LEFT JOIN dbo.sizeclassreport ON areas.areas = area.sizeclassreport
 COUNT(*) AS [Number of Sites]
 FROM
 dbo.sizeclassreport
 Where area='000005' and (code like '11%' or code like '21%')
 GROUP BY
 [area]
 UNION ALL
</code>```

答:
If there is no data you don't get a row to present the zero against. You can force a row to exist however, then if data exists it will be presented, if not you get zero via the coalesce() function.

```<code>SELECT
       '000005' as area
     , COALESCE((SELECT COUNT(*) FROM dbo.sizeclassreport
           WHERE area = '000005' AND code LIKE '11%' OR code LIKE '21%'), 0)
</code>```

Title: Assistance with LEFT JOIN.

Body:
Trying to get a null value when the count = 0. Below is the code that I using to count the number of sites that fit a certain criteria. In this case, code beginning with 11 or 21. There is a question of similar construct but it seems as if mine is of a simpler nature.

 SELECT
 [Area],
 COUNT(*) AS [Number of Sites]
 FROM
 dbo.sizeclassreport
 Where area='000005' and (code like '11%' or code like '21%')
 GROUP BY
 [area]
 UNION ALL

So from responses, it seems as if I need to construct an additional table (tally table as the other question says) that lists the areas then do a left join. Below is my first attempt at this.

 Create TABLE areas
 (
 Area char(6), NOT NULL
 CONSTRAINT PK_AREAS PRIMARY KEY (areas)

 Select * from areas
 LEFT JOIN dbo.sizeclassreport ON areas.areas = area.sizeclassreport
 COUNT(*) AS [Number of Sites]
 FROM
 dbo.sizeclassreport
 Where area='000005' and (code like '11%' or code like '21%')
 GROUP BY
 [area]
 UNION ALL

Body:
If there is no data you don't get a row to present the zero against. You can force a row to exist however, then if data exists it will be presented, if not you get zero via the coalesce() function.

SELECT
       '000005' as area
     , COALESCE((SELECT COUNT(*) FROM dbo.sizeclassreport
           WHERE area = '000005' AND code LIKE '11%' OR code LIKE '21%'), 0)


问:
WSO2 Governance Registry - Solr index problems
We're having some problems about the assets in Publisher/Store in WSO2 using MySQL. We load our database of assets into WSO2 but not all of the assets show up in the store or publisher when queried. This also occuries when we try to get the assets using API.

But the missing assets can be found by:

Calling the database directly

looking them up in carbon

using the store or publisher url with the asset id

the governance rest api through id only

Using WSO2 database default (H2), this issue didn't happened.

After some research about this issue, we have found some solutions like "deleting solr and update registry.xml" to reindex all the assets that are missing but without success.

This question represents a lot of our issues with missing assets.

WSO2 Governance Not Finding All Assets in JDBC Database

If someone went through this, any help would be appreciated.

答:
In the link you posted for 'WSO2 Governance Not Finding All Assets in JDBC Database' my answer was this:

I found that some entries weren't in the REG_LOG table and some dates in the REG_LOG table made entries not be indexed. The solution for this was adding to the REG_LOG table with current timestamps which forced a reindex and then the missing assets were able to be searched for in the web ui.

Basically what we did was create a script that inserted into the REG_LOG table for each asset so each would havea timestamp of NOW() in the table and would be indexed