问:
Generic RedBlack Driver
I'm Trying to insert data threw my driver but it is nothing is working I keep getting my inset highlighted red and telling me that it is not the correct data type.The main problem is I don't understand how to set a generic type Node.Thank you for your help.

Driver(I've been trying diffrent things no progrees):

```<code>public class Driver {
    public static <E> void main(String[] args){
          RedBlack<Integer> rb = new RedBlack<Integer>( );
          Node<Integer> item=32;
          rb.insert(item);
       }//close main
}//close driver
</code>```

REDBLACK CODE:

```<code>import java.util.NoSuchElementException;
public class RedBlack<E extends Comparable<? super E>>{
////////////////////////////////SETUP//////////////////////////////////////////
   private final static int Red=0;
   private final static int Black=1;
   private Node<E> nil;
   private Node<E> root;

   public RedBlack() {
      nil=new Node<E>(null);
      nil.left=nil.right=nil;
      root=new Node<E>(null);
      root.left=root.right=nil;
   }

   static class Node<E>{
      Node(E theData){
         this(theData,null,null);
      }

      Node(E theData,Node<E> lt,Node<E> rt){
            data=theData;
            left=lt;
            right=rt;
            color=RedBlack.Black;
      }

      E data;              // The data in the Node
      Node<E> left;        // Left child
      Node<E> right;       // Right child
      Node<E> parent;      // Above Node
      int color=Black;     // Color of Node
   }
////////////////////////////////INSERT////////////////////////////////
   public void insert(Node<E> item) {
      if(item==null) {
         throw new NoSuchElementException("Inset was null");
      }//close if
      Node<E> temp=root;
      if(root==nil) {
         root= item;
         item.color=Black;
         item.parent=nil;
      }//close if
      else {
         item.color=Red;
         while(item!=root) {
            if(compare(item.data,temp.data)<0) {
               if(temp.right==nil) {
                  temp.right=item;
                  item.parent=temp;
                  break;
               }//close if
               else {
                  temp=temp.right;
               }//close else
            }//close if
            else if(compare(item.data,temp.data)>0){
               if(temp.left==nil) {
                  temp.left=item;
                  item.parent=temp;
                  break;
               }//close if
               else {
                  temp=temp.left;
               }//close else
            }//close else if
         }//close while
         adjustment(item);
      }//close else
   }//close insert

   private void adjustment(Node<E> item) {
      while(item.parent.color==Red) {
         Node<E> uncle;
         if(item.parent==item.parent.parent.left) {
            uncle=item.parent.parent.right;
            if(uncle.color==Red && uncle!=nil) {   //the uncle needs to exist and and be red to recolored
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
               continue;
            }//close if
            if(item==item.parent.right) {
               item=item.parent;
               lR(item);
            }//close if
            item.parent.color=Black;
            item.parent.parent.color=Red;
            rR(item.parent.parent);
         }//close if
         else {
            uncle=item.parent.parent.left;
            if(uncle.color==Red&&uncle!=nil) {
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
               continue;
            }//close if
            if(item==item.parent.left) {
               item=item.parent;
               rR(item);
            }//close if
            item.parent.color=Black;
            item.parent.parent.color=Red;
            lR(item.parent.parent);
         }//close else
      }//close while
      root.color=Black;
   }//close adjustment

   private int compare(E item,E x) {
      if(x==root) {
         return 1;   //same as root will be placed on the right
      }//close if
      else return item.compareTo(x);
   }//close compare
////////////////////////////////ROTATE////////////////////////////////
   private void rR(Node<E> node) {
      if(node.parent!=nil) {
         if(node==node.parent.left) {
            node.parent.left=node.left;
         }//close if
         else {
            node.parent.right=node.left;
         }//close else
         node.left.parent=node.parent;
         node.parent=node.left;
         if(node.left.right!=nil) {
            node.left.right.parent=node;
         }//close if
         Node<E> left=root.left;
         root.left=root.left.right;
         left.right.parent=nil;
         root=left;
      }//close if
   }//close rR
   private void lR(Node<E> node) {
      if(node.parent!=nil) {
        if(node==node.parent.left) {
           node.parent.left=node.right;
        }//close if
        else {
           node.parent.right=node.right;
        }//close else
        node.right.parent=node.parent;
        node.parent=node.parent;
        if(node.right.left!=nil) {
           node.right.left.parent=node;
        }//close if
        node.right=node.right.left;
        node.parent.left=node;
      }//close if
      else {
         Node<E> right=root.right;
         root.right=right.left;
         right.left.parent=root;
         root.parent=right;
         right.left=root;
         right.parent=nil;
         root=right;
      }//close else
   }//close lR
////////////////////////////////DELETE////////////////////////////////
   public void delete(Node<E> node) {
      if((node=find(node,root))==null) {
         System.out.println("Node does not exist");
         return;
      }
      Node<E> node2;
      Node<E> temp=node;
      int tempColor=node.color;

      if(node.left==nil) {
         node2=node.right;
         switchNodes(node,node.right);
      }
      else if(node.right==nil) {
         node2=node.left;
         switchNodes(node,node.left);
      }
      else {
         temp=subTree(node.right);
         tempColor=temp.color;
         node2=temp.right;
         if(temp.parent==node) {
            node2.parent=temp;
         }
         else {
            switchNodes(temp,temp.right);
            temp.right=node.right;
            temp.right.parent=temp;
         }
         switchNodes(node,temp);
         temp.left=node.left;
         temp.left.parent=temp;
         temp.color=node.color;
      }
      if(tempColor==Black) {
         deleteAdjustment(node2);
      }
   }//close delete

   public void switchNodes(Node<E> node,Node<E> nodeOther) {
      if(node.parent==nil) {
         root=nodeOther;
      }
      else if(node==node.parent.left) {
         nodeOther.parent.left=nodeOther;
      }
      else {
         node.parent.right=nodeOther;
      }
      nodeOther.parent=node.parent;
   }

   public Node<E> subTree(Node<E> subRoot) {
      while(subRoot!=nil) {
         subRoot=subRoot.left;
      }
      return subRoot;
   }

   public void deleteAdjustment(Node<E> node) {
      while(node!=root && node.color==Black) {
         if(node==node.parent.left) {
            Node<E> brother=node.parent.right;
            if(brother.color==Red) {
               brother.color=Black;
               node.parent.color=Red;
               lR(node.parent);
               brother=node.parent.right;
            }//close if
            if(brother.left.color==Black && brother.right.color==Black) {
               brother.color=Red;
               node=node.parent;
               continue;
            }//close if
            else if(brother.right.color==Black) {
               brother.left.color=Black;
               brother.color=Red;
               rR(brother);
               brother=node.parent.right;
            }//close else if
            if(brother.right.color==Red) {
               brother.color=node.parent.color;
               node.parent.color=Black;
               brother.right.color=Black;
               lR(node.parent);
               node=root;
            }//close if
         }//close if
         else {
            Node<E> brother=node.parent.left;
            if(brother.color==Red) {
               brother.color=Black;
               node.parent.color=Red;
               rR(node.parent);
               brother=node.parent.left;
            }//close if
            if(brother.right.color==Black&&brother.left.color==Black) {
               brother.color=Red;
               node=node.parent;
               continue;
            }//close if
            else if(brother.left.color==Black) {
               brother.right.color=Black;
               brother.color=Red;
               lR(brother);
               brother=node.parent.left;
            }//close else if
            if(brother.left.color==Red) {
               brother.color=node.parent.color;
               node.parent.color=Black;
               brother.left.color=Black;
               rR(node.parent);
               node=root;
            }//close if
         }//close else
      }//close while
      node.color=Black;
   }//close deleteAdjustment
////////////////////////////////FIND////////////////////////////////

   public Node<E> find(Node<E> item) {
      if(item==null) {
         throw new NoSuchElementException("Item was null.");
      }//close if
      return find(item,root);
   }//close find

   private Node<E> find(Node<E> findNode,Node<E> node) {
      if(root==nil) {
         return null;
      }//close if
      if(compare(findNode.data,node.data)<0) {
         if (node.right != nil) {
            return find(findNode,node.right);
         }
      }
      else if(compare(findNode.data,node.data)>0) {
         if (node.left != nil) {
            return find(findNode,node.left);
         }//close if
      }//close if
      else if(findNode.data==node.data) {
         return node;
      }
      return null;
   }

////////////////////////////////Print////////////////////////////////

   public void printInOrder() {
      if(root==nil) {
         return;
      }//close if
      System.out.print("Key: "+root.data+"-Black");
      printTree(root);
   }//close printInOrder

   public void printTree(Node<E> node) {
      if(node==nil) {
         return;
      }//close if
      printTree(node.left);
      if(node.color==Black) {
         System.out.print("Key: "+node.data+"-Black");
      }//close if
      else {
         System.out.print("Key: "+node.data+"-Red");
      }//close else
      printTree(node.right);
   }//close printTree
}//close class
</code>```

答:
The immediate issue is

```<code>Node<Integer> item=32;
</code>```

This should be

```<code>Node<Integer> item = new Node<>(32);
</code>```

That creates a new Node with the value 32.

Also, remove the <E> in the declaration of the main() method.

Title: Generic RedBlack Driver

Body:
I'm Trying to insert data threw my driver but it is nothing is working I keep getting my inset highlighted red and telling me that it is not the correct data type.The main problem is I don't understand how to set a generic type Node.Thank you for your help.

Driver(I've been trying diffrent things no progrees):

public class Driver {
    public static <E> void main(String[] args){
          RedBlack<Integer> rb = new RedBlack<Integer>( );
          Node<Integer> item=32;
          rb.insert(item);
       }//close main
}//close driver

REDBLACK CODE:

import java.util.NoSuchElementException;
public class RedBlack<E extends Comparable<? super E>>{
////////////////////////////////SETUP//////////////////////////////////////////
   private final static int Red=0;
   private final static int Black=1;
   private Node<E> nil;
   private Node<E> root;

   public RedBlack() {
      nil=new Node<E>(null);
      nil.left=nil.right=nil;
      root=new Node<E>(null);
      root.left=root.right=nil;
   }

   static class Node<E>{
      Node(E theData){
         this(theData,null,null);
      }

      Node(E theData,Node<E> lt,Node<E> rt){
            data=theData;
            left=lt;
            right=rt;
            color=RedBlack.Black;
      }

      E data;              // The data in the Node
      Node<E> left;        // Left child
      Node<E> right;       // Right child
      Node<E> parent;      // Above Node
      int color=Black;     // Color of Node
   }
////////////////////////////////INSERT////////////////////////////////
   public void insert(Node<E> item) {
      if(item==null) {
         throw new NoSuchElementException("Inset was null");
      }//close if
      Node<E> temp=root;
      if(root==nil) {
         root= item;
         item.color=Black;
         item.parent=nil;
      }//close if
      else {
         item.color=Red;
         while(item!=root) {
            if(compare(item.data,temp.data)<0) {
               if(temp.right==nil) {
                  temp.right=item;
                  item.parent=temp;
                  break;
               }//close if
               else {
                  temp=temp.right;
               }//close else
            }//close if
            else if(compare(item.data,temp.data)>0){
               if(temp.left==nil) {
                  temp.left=item;
                  item.parent=temp;
                  break;
               }//close if
               else {
                  temp=temp.left;
               }//close else
            }//close else if
         }//close while
         adjustment(item);
      }//close else
   }//close insert

   private void adjustment(Node<E> item) {
      while(item.parent.color==Red) {
         Node<E> uncle;
         if(item.parent==item.parent.parent.left) {
            uncle=item.parent.parent.right;
            if(uncle.color==Red && uncle!=nil) {   //the uncle needs to exist and and be red to recolored
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
               continue;
            }//close if
            if(item==item.parent.right) {
               item=item.parent;
               lR(item);
            }//close if
            item.parent.color=Black;
            item.parent.parent.color=Red;
            rR(item.parent.parent);
         }//close if
         else {
            uncle=item.parent.parent.left;
            if(uncle.color==Red&&uncle!=nil) {
               item.parent.color=Black;
               item.parent.parent.color=Red;
               uncle.color=Black;
               continue;
            }//close if
            if(item==item.parent.left) {
               item=item.parent;
               rR(item);
            }//close if
            item.parent.color=Black;
            item.parent.parent.color=Red;
            lR(item.parent.parent);
         }//close else
      }//close while
      root.color=Black;
   }//close adjustment

   private int compare(E item,E x) {
      if(x==root) {
         return 1;   //same as root will be placed on the right
      }//close if
      else return item.compareTo(x);
   }//close compare
////////////////////////////////ROTATE////////////////////////////////
   private void rR(Node<E> node) {
      if(node.parent!=nil) {
         if(node==node.parent.left) {
            node.parent.left=node.left;
         }//close if
         else {
            node.parent.right=node.left;
         }//close else
         node.left.parent=node.parent;
         node.parent=node.left;
         if(node.left.right!=nil) {
            node.left.right.parent=node;
         }//close if
         Node<E> left=root.left;
         root.left=root.left.right;
         left.right.parent=nil;
         root=left;
      }//close if
   }//close rR
   private void lR(Node<E> node) {
      if(node.parent!=nil) {
        if(node==node.parent.left) {
           node.parent.left=node.right;
        }//close if
        else {
           node.parent.right=node.right;
        }//close else
        node.right.parent=node.parent;
        node.parent=node.parent;
        if(node.right.left!=nil) {
           node.right.left.parent=node;
        }//close if
        node.right=node.right.left;
        node.parent.left=node;
      }//close if
      else {
         Node<E> right=root.right;
         root.right=right.left;
         right.left.parent=root;
         root.parent=right;
         right.left=root;
         right.parent=nil;
         root=right;
      }//close else
   }//close lR
////////////////////////////////DELETE////////////////////////////////
   public void delete(Node<E> node) {
      if((node=find(node,root))==null) {
         System.out.println("Node does not exist");
         return;
      }
      Node<E> node2;
      Node<E> temp=node;
      int tempColor=node.color;

      if(node.left==nil) {
         node2=node.right;
         switchNodes(node,node.right);
      }
      else if(node.right==nil) {
         node2=node.left;
         switchNodes(node,node.left);
      }
      else {
         temp=subTree(node.right);
         tempColor=temp.color;
         node2=temp.right;
         if(temp.parent==node) {
            node2.parent=temp;
         }
         else {
            switchNodes(temp,temp.right);
            temp.right=node.right;
            temp.right.parent=temp;
         }
         switchNodes(node,temp);
         temp.left=node.left;
         temp.left.parent=temp;
         temp.color=node.color;
      }
      if(tempColor==Black) {
         deleteAdjustment(node2);
      }
   }//close delete

   public void switchNodes(Node<E> node,Node<E> nodeOther) {
      if(node.parent==nil) {
         root=nodeOther;
      }
      else if(node==node.parent.left) {
         nodeOther.parent.left=nodeOther;
      }
      else {
         node.parent.right=nodeOther;
      }
      nodeOther.parent=node.parent;
   }

   public Node<E> subTree(Node<E> subRoot) {
      while(subRoot!=nil) {
         subRoot=subRoot.left;
      }
      return subRoot;
   }

   public void deleteAdjustment(Node<E> node) {
      while(node!=root && node.color==Black) {
         if(node==node.parent.left) {
            Node<E> brother=node.parent.right;
            if(brother.color==Red) {
               brother.color=Black;
               node.parent.color=Red;
               lR(node.parent);
               brother=node.parent.right;
            }//close if
            if(brother.left.color==Black && brother.right.color==Black) {
               brother.color=Red;
               node=node.parent;
               continue;
            }//close if
            else if(brother.right.color==Black) {
               brother.left.color=Black;
               brother.color=Red;
               rR(brother);
               brother=node.parent.right;
            }//close else if
            if(brother.right.color==Red) {
               brother.color=node.parent.color;
               node.parent.color=Black;
               brother.right.color=Black;
               lR(node.parent);
               node=root;
            }//close if
         }//close if
         else {
            Node<E> brother=node.parent.left;
            if(brother.color==Red) {
               brother.color=Black;
               node.parent.color=Red;
               rR(node.parent);
               brother=node.parent.left;
            }//close if
            if(brother.right.color==Black&&brother.left.color==Black) {
               brother.color=Red;
               node=node.parent;
               continue;
            }//close if
            else if(brother.left.color==Black) {
               brother.right.color=Black;
               brother.color=Red;
               lR(brother);
               brother=node.parent.left;
            }//close else if
            if(brother.left.color==Red) {
               brother.color=node.parent.color;
               node.parent.color=Black;
               brother.left.color=Black;
               rR(node.parent);
               node=root;
            }//close if
         }//close else
      }//close while
      node.color=Black;
   }//close deleteAdjustment
////////////////////////////////FIND////////////////////////////////

   public Node<E> find(Node<E> item) {
      if(item==null) {
         throw new NoSuchElementException("Item was null.");
      }//close if
      return find(item,root);
   }//close find

   private Node<E> find(Node<E> findNode,Node<E> node) {
      if(root==nil) {
         return null;
      }//close if
      if(compare(findNode.data,node.data)<0) {
         if (node.right != nil) {
            return find(findNode,node.right);
         }
      }
      else if(compare(findNode.data,node.data)>0) {
         if (node.left != nil) {
            return find(findNode,node.left);
         }//close if
      }//close if
      else if(findNode.data==node.data) {
         return node;
      }
      return null;
   }

////////////////////////////////Print////////////////////////////////

   public void printInOrder() {
      if(root==nil) {
         return;
      }//close if
      System.out.print("Key: "+root.data+"-Black");
      printTree(root);
   }//close printInOrder

   public void printTree(Node<E> node) {
      if(node==nil) {
         return;
      }//close if
      printTree(node.left);
      if(node.color==Black) {
         System.out.print("Key: "+node.data+"-Black");
      }//close if
      else {
         System.out.print("Key: "+node.data+"-Red");
      }//close else
      printTree(node.right);
   }//close printTree
}//close class

Body:
The immediate issue is

Node<Integer> item=32;

This should be

Node<Integer> item = new Node<>(32);

That creates a new Node with the value 32.

Also, remove the <E> in the declaration of the main() method.


来源: stackexchange

问:
Make a sidebar float on a Github wiki (i.e. so that as I scroll down the page it will stay visible)
I'd like to make a sidebar float on a Github wiki (i.e. so that as I scroll down the page it will stay visible). Does anyone know how to to this? I don't think you can use CSS or jQuery as per this post.</p>

答:
I sent a message to Github and got this response:

It's currently not possible to do that, but I can see how that'd be
  handy. I can't make any promises regarding implementation, but I'll
  pass on your feedback for the team to consider!

ContentLicense: CC BY-SA 3.0


问:
BeautifulSoup: find all tags before stopping condition is met
I'm trying to extract a class tag from an HTML file, but only if it is located before a given stopping point. What I have is:

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("https://mysite")
soup = BeautifulSoup(page.content, 'html.parser')
class_extr = soup.find_all("span", class_="myclass")
</code>```

This works, but it finds all instances of myclass, and i only want those before the following text shows in the soup:

```<code><h4 class="cat-title" id="55">
 Title text N1
 <small>
  Title text N2.
 </small>
</h4>
</code>```

The thing that makes this block unique are the Title text N lines, especially the Title text N2. line. There are many cat-title tags before, so I can't use that as a stopping condition.

The code surrounding this block looks like this:

```<code>...
<div class="myc">
<a class="bbb" href="linkhere_893">
<span class="myclass">Text893</span>
<img data-lazy="https://link893.jpg"/>
</a>
</div>
<div class="myc">
<a class="bbb" href="linkhere_96">
<span class="myclass">Text96</span>
<img data-lazy="https://link96.jpg"/>
</a>
</div>
</div><!-- This closes a list that starts above -->
<h4 class="cat-title" id="55">Title text N1 <small> Title text N2.</small></h4>
<div class="list" id="55">
<div class="myc">
<a class="bbb" href="linkhere_34">
<span class="myclass">Text34</span>
<img data-lazy="https://link34.jpg"/>
</a>
</div>
<div class="myc">
...
</code>```

continuing both above and below.

How can I do this?

答:
How about this:

```<code>page = requests.get("https://mysite")
# Split your page and unwanted string, then parse with BeautifulSoup
text = page.text.split('Title text N2.')
soup = BeautifulSoup(text[0], 'html.parser')
class_extr = soup.find_all("span", class_="myclass")
</code>```

Body:
I'm trying to extract a class tag from an HTML file, but only if it is located before a given stopping point. What I have is:

import requests
from bs4 import BeautifulSoup

page = requests.get("https://mysite")
soup = BeautifulSoup(page.content, 'html.parser')
class_extr = soup.find_all("span", class_="myclass")

This works, but it finds all instances of myclass, and i only want those before the following text shows in the soup:

 Title text N1

  Title text N2.

The thing that makes this block unique are the Title text N lines, especially the Title text N2. line. There are many cat-title tags before, so I can't use that as a stopping condition.

The code surrounding this block looks like this:

...

Text893

Text96

Title text N1  Title text N2.

Text34

...

continuing both above and below.

How can I do this?

Body:
How about this:

page = requests.get("https://mysite")
# Split your page and unwanted string, then parse with BeautifulSoup
text = page.text.split('Title text N2.')
soup = BeautifulSoup(text[0], 'html.parser')
class_extr = soup.find_all("span", class_="myclass")


问:
MemoryError using MLPClassifier from sklearn.neural_network
I'm running python 3.5 on a windows 10 64-bit operating system.

When I try to implement MLPClassifier the code runs for a while and then gives me a MemoryError.

I think it's due to the size of the hidden layer that I'm asking it to run but I need to  run this size to collect my data. How can I circumvent this error?

Code

```<code>gamma=[1,10,100,1000,10000,100000]#create array for range of gamma values
score_train=[]
score_test=[]
for j in gamma:
    mlp = MLPClassifier(solver='lbfgs', random_state=0, hidden_layer_sizes=[j,j], activation='tanh').fit(data_train, classes_train)
    score_train.append(mlp.score(data_train,classes_train))
    score_test.append(mlp.score(data_test,classes_test))
print (score_train)
print (score_test)
</code>```

Error

Memory Erroy Traceback

答:
the code runs for a while and then gives me a MemoryError. I think it's due to the size of the hidden layer that I'm asking it to run but I need to run this size to collect my data.

Yes, it's the size of the hidden-layers! And the remaining part of that sentence does not make much sense (continue reading)!

Please make sure to read read the tutorial and API-docs

Now some more specific remarks:

The sizes of the hidden-layer does not have anything to do with the collection of your data!

input- and output-layers will be build based on the sizes of your X,y!

hidden_layer_sizes=[j,j] is actually creating 2 hidden-layers!

In the MLP, all layers are fully connected!

a call with hidden_layer_sizes=[100000, 100000] as you try to do will use ~76 gigabytes of memory (assuming 64-bit doubles) just for these weights connecting these 2 layers alone!

and this is just one connection-layer: input-h0 and h1-output are still missing

lbfgs is a completely different solver than all the others. Don't use it without some understanding of the implications! It's not default!

It's a full-batch method and therefore uses a lot more memory when sample-size is big!

Additionally, there are more internal reasons to use more memory compared to the other (first-order-) methods

Not that precise, but the docs already gave some hints: Note: The default solver ‘adam’ works pretty well on relatively large datasets (with thousands of training samples or more) in terms of both training time and validation score. For small datasets, however, ‘lbfgs’ can converge faster and perform better.

ContentLicense: CC BY-SA 4.0

Body:
I'm running python 3.5 on a windows 10 64-bit operating system.

When I try to implement MLPClassifier the code runs for a while and then gives me a MemoryError.

I think it's due to the size of the hidden layer that I'm asking it to run but I need to  run this size to collect my data. How can I circumvent this error?

Code

gamma=[1,10,100,1000,10000,100000]#create array for range of gamma values
score_train=[]
score_test=[]
for j in gamma:
    mlp = MLPClassifier(solver='lbfgs', random_state=0, hidden_layer_sizes=[j,j], activation='tanh').fit(data_train, classes_train)
    score_train.append(mlp.score(data_train,classes_train))
    score_test.append(mlp.score(data_test,classes_test))
print (score_train)
print (score_test)

Error

Memory Erroy Traceback


问:
System.out.print keeps looping error
Hello there guys I've been trying to help my friend with this code that almost works. It's a simple Blackjack game which asks the user if they want another card write yes and if user writes no then his turn is ended and it should be the dealer's turn. The problem I'm having is that when I write no to end my turn it just keeps asking me the question if I want another card in the console. Thank you for you help.
Ex.

```<code>Another Card (yes/no)?: nO
Another Card (yes/no)?: no
Another Card (yes/no)?: no
Another Card (yes/no)?: no
Another Card (yes/no)?: nO
Another Card (yes/no)?: no
</code>```

this is my code below:

```<code>while (playing == true ){
        System.out.print("Another Card (yes/no)?: ");
        anotherCard = keyboard.nextLine();

        if (anotherCard.equals("yes")) {

            nextCard = random.nextInt(10) + 1;
            cardTotal += nextCard;
            System.out.println("Card: " + nextCard);
            System.out.println("Total: " + cardTotal);

            if (cardTotal > 21) {
            System.out.println("You busted, Dealer Wins");
            playing = false;
            }
            if (cardTotal == 21) {
            System.out.println("Player Wins");
            playing = false;
            }

            }
           if (anotherCard.equals("no")) {
           dealerturn = true;

           if ((dealerturn == true) && (dTotal < 17)) {
                nextCard = random.nextInt(10) + 1;
                dTotal += nextCard;

                if (dTotal > 21) {
                System.out.println("Dealer Busts, You Win!");
                playing = false;

                }
            }
            else if ((dealerturn == true) && (dTotal > 17))  {
             if (dTotal > 21) {
                System.out.println("Dealer Busts, You Win!");
                playing = false;
                }
             }
           }
        }
     }
</code>```

答:
That's because you don't change playing to contain false when the user doesn't want to play:

```<code>if (anotherCard.equals("yes")) {
    ...
} else { // you should add this case:
    playing = false;
}
</code>```

Title: System.out.print keeps looping error

Body:
Hello there guys I've been trying to help my friend with this code that almost works. It's a simple Blackjack game which asks the user if they want another card write yes and if user writes no then his turn is ended and it should be the dealer's turn. The problem I'm having is that when I write no to end my turn it just keeps asking me the question if I want another card in the console. Thank you for you help.
Ex.

Another Card (yes/no)?: nO
Another Card (yes/no)?: no
Another Card (yes/no)?: no
Another Card (yes/no)?: no
Another Card (yes/no)?: nO
Another Card (yes/no)?: no

this is my code below:

while (playing == true ){
        System.out.print("Another Card (yes/no)?: ");
        anotherCard = keyboard.nextLine();

        if (anotherCard.equals("yes")) {

            nextCard = random.nextInt(10) + 1;
            cardTotal += nextCard;
            System.out.println("Card: " + nextCard);
            System.out.println("Total: " + cardTotal);

            if (cardTotal > 21) {
            System.out.println("You busted, Dealer Wins");
            playing = false;
            }
            if (cardTotal == 21) {
            System.out.println("Player Wins");
            playing = false;
            }

            }
           if (anotherCard.equals("no")) {
           dealerturn = true;

           if ((dealerturn == true) && (dTotal < 17)) {
                nextCard = random.nextInt(10) + 1;
                dTotal += nextCard;

                if (dTotal > 21) {
                System.out.println("Dealer Busts, You Win!");
                playing = false;

                }
            }
            else if ((dealerturn == true) && (dTotal > 17))  {
             if (dTotal > 21) {
                System.out.println("Dealer Busts, You Win!");
                playing = false;
                }
             }
           }
        }
     }

Body:
That's because you don't change playing to contain false when the user doesn't want to play:

if (anotherCard.equals("yes")) {
    ...
} else { // you should add this case:
    playing = false;
}


问:
undefined reference to `main' collect2: error: ld returned 1 exit status
I am trying to create a phonebook using sqlite, and I get compilation errors, I was able to debug a few syntax errors, but the problem I am now having is making sure that the following error is corrected.

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20):
</code>```

I will appreciate explaining the error and providing some solution

```#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i = 0; i<argc; i++) {
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("...................................................\n");
   return 0;

int main(int argc, char* argv[]) {
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   char *sql;
   const char* data = "Callback function called";

if (argc == 3 && (0 == strcmp(argv[1], "-f"))) {
    if(argc == 1){

   rc = sqlite3_open("test.db", &db);
     if( rc ) {
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   } else {
   /* Create SQL statement */
   sql = "CREATE TABLE CONTACTS("  \
         "ID INT PRIMARY KEY     NOT NULL," \
         "FIRSTNAME      TEXT    NOT NULL," \
         "LASTNAME       TEXT    NOT NULL," \
         "MOBILEPHONE       TEXT    NOT NULL," \
         "CITY            TEXT     NOT NULL," \
         "ADDRESS        CHAR(50)," \
         "COUNTRY         TEXT );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
   if( rc != SQLITE_OK ){
   fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Table created successfully\n");
   }
   sqlite3_close(db);
   return 0;
  }
 }
 }
}
void MainMenu()
{
        int optn; // option value
        int valid; //check if option is valid
        system("clear");
      valid = 0;
        while( valid == 0 )
       {
       printf("---------------DELIMITER---------------\n");
       printf("Phone book Menu\n");
       printf("(1) Add new record to phone book\n");
       printf("(2) Search phone book\n");
       printf("(3) Update phone book\n");
       printf("(4) Delete record from phone book\n");
       printf("(5) Quit\n");
       printf("---------------DELIMITER---------------\n");
       printf("Please choose your operation: ");

                if(scanf("%d", &optn) == 1)
                {
                        if(optn > 0 && optn < 6)
                        {
                                valid = 1;
                        }else{
                                printf("Error: Invalid option selected, please try again\n\n");
                }

        }
        //start the operations
        if(optn == 1)
        {
            AddMenu();
        }else if (optn == 2)
        {

                SearchMenu();
        }else if (optn == 3)
        {
                UpdateMenu();
        }else if (optn == 4)
        {
                DeleteMenu();
        }else{
                exit(0);
        }
    }
}
//search menu
void SearchMenu()
{
        int optn; // option value
        int valid; //check if option is valid
        int display_search; //allow csv file export
        char ch; //repeat option value
        sqlite3 *db;
        char *zErrMsg = 0;
         int rc;
         char *sql;
         const char* data;

        printf("\tSearch PhoneBook\n");
        printf("================================\n\n");
        valid = 0;
        while( valid == 0 )
        {
                printf("Select a search option:\n");
                printf("-----------------------\n");
                printf(" 1) Display search result\n");
                printf(" 2) Back\n\n");
                printf("Choose an option: ");

                if(scanf("%d", &optn) == 1)
                {
                        if(optn > 0 && optn < 3)
                        {
                                valid = 1;
                        }else{
                                printf("Error: Invalid option selected, please try again\n\n");
                        }
                }
        //start the operations
        if(optn == 1)
        {
         sql = "SELECT * from CONTACTS";

   /* Execute SQL statement */
        rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
  if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
  }

}

}
void AddMenu()
{
char *sql;
        char statement[512];
        char *fname = malloc(50);
        char *lname = malloc(50);
        char *city= malloc(50);
        char *country= malloc(50);
        sqlite3 *db;
        char *zErrMsg = 0;
         int rc;
        printf("Enter the First Name: ");
        scanf("%[^\n]s", fname);

        printf("Enter the Last Name: ");
        scanf("%[^\n]s", lname);

        printf("Enter the Mobile Phone: ");
        scanf("%[^\n]s", mobile);

        printf("Enter the City: ");
        scanf("%[^\n]s", city);

          printf("Enter the Country: ");
        scanf("%[^\n]s", country);

     //run SQL Statements

        sql = "INSERT INTO CONTACT (FirstName,LastName,MobilePhone,City,Country) "  \
         "VALUES ('%s','%s','%s','%s','%s' );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);

   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Records created successfully\n");
   }
   sqlite3_close(db);
   return;
}
void UpdateMenu()
{
char id;
int valid;
char *fname = malloc(50);
char *lname = malloc(50);
char *mobile= malloc(20);
char *city= malloc(50);
char *country= malloc(50);
char statement[512];
char values_cut[512];
char fname_out[50];
char lname_out[50];
char mobile_out[20];
char city_out[50];
char country_out[50];
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data;

if(do_search(0) == 0){

        valid = 0;
        while( valid == 0 )
        {
                printf("Enter the Number you want to update: ");

                if(scanf("%s", &id) == 1)
                        {
                                if(id > 0 )
                                {
                                        valid = 1;

                                        printf("\nUpdate the values, press enter if you do not want to change a field\n");
                                        printf("---------------------------------------------------------------------\n");

                                        //get the update values
                                        printf("Enter the First Name: ");
                                        if((scanf("%[^\n]s", fname) != 0)){
                                                snprintf(fname_out, sizeof fname_out, "FirstName='%s',",fname);
                                        }else{
                                                snprintf(fname_out,sizeof fname_out, "");
                                        }
                                        fname = fname_out;

                                        printf("Enter the Last Name: ");
                                        if((scanf("%[^\n]s", lname)!=0)){
                                                snprintf(lname_out,sizeof lname_out, "LastName='%s',",lname);
                                        }else{
                                                snprintf(lname_out,sizeof lname_out, "");
                                        }
                                        lname=lname_out;

                                     printf("Enter the Mobile Phone: ");
                                        if((scanf("%[^\n]s", mobile)!=0)){
                                                snprintf(mobile_out,sizeof mobile_out, "MobilePhone='%s',",mobile);
                                        }else{
                                                snprintf(mobile_out,sizeof mobile_out, "");
                                        }
                                        mobile=mobile_out;

                                        printf("Enter the City: ");
                                        if((scanf("%[^\n]s", city)!=0)){
                                                snprintf(city_out,sizeof city_out, "City='%s',",city);
                                        }else{
                                                snprintf(city_out,sizeof city_out, "");
                                        }
                                        city=city_out;

                                        printf("Enter the Country: ");
                                        if((scanf("%[^\n]s", country)!=0)){
                                                snprintf(country_out,sizeof country_out, "Country='%s',",country);
                                                                   }else{
                                                snprintf(country_out,sizeof country_out, "");
                                        }
                                        country=country_out;

                                        //remove the last comma from the query
                                        snprintf(values_cut,sizeof values_cut, "%s%s%s%s%s",fname,lname,mobile,city,country);

                                                }
                                        }

/* Create merged SQL statement */
   sql = "UPDATE CONTACT set %s where ID=%s";
         "SELECT * from CONTACT  where ID=%s";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);

   if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
}

}

}
//Delete menu
void DeleteMenu()
{
        int valid;
        int id, good;
        char *sql;
        char statement[512];
        sqlite3 *db;
        char *zErrMsg = 0;
        int rc;
        const char* data;
        int optn;
        //search first
        if(do_search(0)==0){

        valid = 0;
        while( valid == 0 )
        {
                printf("Enter the number you want to delete: ");

                if(scanf("%s", &id) == 1)
                        {
                                if(id > 0 )
                                {
                                        valid = 1;
/* Create merged SQL statement */
   sql = "DELETE from CONTACT where ID=%s; " \
         "SELECT * from CONTACT";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);

   if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
      }
   }while(optn!=5);
 }
}
}
}

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i = 0; i<argc; i++) {
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("...................................................\n");
   return 0;

int main(int argc, char* argv[]) {
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   char *sql;
   const char* data = "Callback function called";

if (argc == 3 && (0 == strcmp(argv[1], "-f"))) {
    if(argc == 1){

   rc = sqlite3_open("test.db", &db);
     if( rc ) {
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   } else {
   /* Create SQL statement */
   sql = "CREATE TABLE CONTACTS("  \
         "ID INT PRIMARY KEY     NOT NULL," \
         "FIRSTNAME      TEXT    NOT NULL," \
         "LASTNAME       TEXT    NOT NULL," \
         "MOBILEPHONE       TEXT    NOT NULL," \
         "CITY            TEXT     NOT NULL," \
         "ADDRESS        CHAR(50)," \
         "COUNTRY         TEXT );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
   if( rc != SQLITE_OK ){
   fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Table created successfully\n");
   }
   sqlite3_close(db);
   return 0;
  }
 }
 }
}
void MainMenu()
{
        int optn; // option value
        int valid; //check if option is valid
        system("clear");
      valid = 0;
        while( valid == 0 )
       {
       printf("---------------DELIMITER---------------\n");
       printf("Phone book Menu\n");
       printf("(1) Add new record to phone book\n");
       printf("(2) Search phone book\n");
       printf("(3) Update phone book\n");
       printf("(4) Delete record from phone book\n");
       printf("(5) Quit\n");
       printf("---------------DELIMITER---------------\n");
       printf("Please choose your operation: ");

                if(scanf("%d", &optn) == 1)
                {
                        if(optn > 0 && optn < 6)
                        {
                                valid = 1;
                        }else{
                                printf("Error: Invalid option selected, please try again\n\n");
                }

        }
        //start the operations
        if(optn == 1)
        {
            AddMenu();
        }else if (optn == 2)
        {

                SearchMenu();
        }else if (optn == 3)
        {
                UpdateMenu();
        }else if (optn == 4)
        {
                DeleteMenu();
        }else{
                exit(0);
        }
    }
}
//search menu
void SearchMenu()
{
        int optn; // option value
        int valid; //check if option is valid
        int display_search; //allow csv file export
        char ch; //repeat option value
        sqlite3 *db;
        char *zErrMsg = 0;
         int rc;
         char *sql;
         const char* data;

        printf("\tSearch PhoneBook\n");
        printf("================================\n\n");
        valid = 0;
        while( valid == 0 )
        {
                printf("Select a search option:\n");
                printf("-----------------------\n");
                printf(" 1) Display search result\n");
                printf(" 2) Back\n\n");
                printf("Choose an option: ");

                if(scanf("%d", &optn) == 1)
                {
                        if(optn > 0 && optn < 3)
                        {
                                valid = 1;
                        }else{
                                printf("Error: Invalid option selected, please try again\n\n");
                        }
                }
        //start the operations
        if(optn == 1)
        {
         sql = "SELECT * from CONTACTS";

   /* Execute SQL statement */
        rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
  if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
  }

}

}
void AddMenu()
{
char *sql;
        char statement[512];
        char *fname = malloc(50);
        char *lname = malloc(50);
        char *city= malloc(50);
        char *country= malloc(50);
        sqlite3 *db;
        char *zErrMsg = 0;
         int rc;
        printf("Enter the First Name: ");
        scanf("%[^\n]s", fname);

        printf("Enter the Last Name: ");
        scanf("%[^\n]s", lname);

        printf("Enter the Mobile Phone: ");
        scanf("%[^\n]s", mobile);

        printf("Enter the City: ");
        scanf("%[^\n]s", city);

          printf("Enter the Country: ");
        scanf("%[^\n]s", country);

     //run SQL Statements

        sql = "INSERT INTO CONTACT (FirstName,LastName,MobilePhone,City,Country) "  \
         "VALUES ('%s','%s','%s','%s','%s' );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);

   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Records created successfully\n");
   }
   sqlite3_close(db);
   return;
}
void UpdateMenu()
{
char id;
int valid;
char *fname = malloc(50);
char *lname = malloc(50);
char *mobile= malloc(20);
char *city= malloc(50);
char *country= malloc(50);
char statement[512];
char values_cut[512];
char fname_out[50];
char lname_out[50];
char mobile_out[20];
char city_out[50];
char country_out[50];
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data;

if(do_search(0) == 0){

        valid = 0;
        while( valid == 0 )
        {
                printf("Enter the Number you want to update: ");

                if(scanf("%s", &id) == 1)
                        {
                                if(id > 0 )
                                {
                                        valid = 1;

                                        printf("\nUpdate the values, press enter if you do not want to change a field\n");
                                        printf("---------------------------------------------------------------------\n");

                                        //get the update values
                                        printf("Enter the First Name: ");
                                        if((scanf("%[^\n]s", fname) != 0)){
                                                snprintf(fname_out, sizeof fname_out, "FirstName='%s',",fname);
                                        }else{
                                                snprintf(fname_out,sizeof fname_out, "");
                                        }
                                        fname = fname_out;

                                        printf("Enter the Last Name: ");
                                        if((scanf("%[^\n]s", lname)!=0)){
                                                snprintf(lname_out,sizeof lname_out, "LastName='%s',",lname);
                                        }else{
                                                snprintf(lname_out,sizeof lname_out, "");
                                        }
                                        lname=lname_out;

                                     printf("Enter the Mobile Phone: ");
                                        if((scanf("%[^\n]s", mobile)!=0)){
                                                snprintf(mobile_out,sizeof mobile_out, "MobilePhone='%s',",mobile);
                                        }else{
                                                snprintf(mobile_out,sizeof mobile_out, "");
                                        }
                                        mobile=mobile_out;

                                        printf("Enter the City: ");
                                        if((scanf("%[^\n]s", city)!=0)){
                                                snprintf(city_out,sizeof city_out, "City='%s',",city);
                                        }else{
                                                snprintf(city_out,sizeof city_out, "");
                                        }
                                        city=city_out;

                                        printf("Enter the Country: ");
                                        if((scanf("%[^\n]s", country)!=0)){
                                                snprintf(country_out,sizeof country_out, "Country='%s',",country);
                                                                   }else{
                                                snprintf(country_out,sizeof country_out, "");
                                        }
                                        country=country_out;

                                        //remove the last comma from the query
                                        snprintf(values_cut,sizeof values_cut, "%s%s%s%s%s",fname,lname,mobile,city,country);

                                                }
                                        }

/* Create merged SQL statement */
   sql = "UPDATE CONTACT set %s where ID=%s";
         "SELECT * from CONTACT  where ID=%s";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);

   if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
}

}

}
//Delete menu
void DeleteMenu()
{
        int valid;
        int id, good;
        char *sql;
        char statement[512];
        sqlite3 *db;
        char *zErrMsg = 0;
        int rc;
        const char* data;
        int optn;
        //search first
        if(do_search(0)==0){

        valid = 0;
        while( valid == 0 )
        {
                printf("Enter the number you want to delete: ");

                if(scanf("%s", &id) == 1)
                        {
                                if(id > 0 )
                                {
                                        valid = 1;
/* Create merged SQL statement */
   sql = "DELETE from CONTACT where ID=%s; " \
         "SELECT * from CONTACT";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);

   if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
      }
   }while(optn!=5);
 }
}
}
}
```

<p>when i  compile this c code on putty using</p>

```gcc insertno.c -o insertno -lsqlite3
```

<p>i get this error below, solution will be much appreciated.thanks</p>

```/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20):
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20):
```

答:
The body of your function callback() has not been properly closed off.

```<code>static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i = 0; i<argc; i++) {
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("...................................................\n");
   return 0;
} // THIS WAS MISSING
</code>```

The reason GCC didn't flag an error when it encountered a function definition within the callback() function is that GCC has an extension called nested functions.

Body:
I am trying to create a phonebook using sqlite, and I get compilation errors, I was able to debug a few syntax errors, but the problem I am now having is making sure that the following error is corrected.

/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20):

I will appreciate explaining the error and providing some solution

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i = 0; i<argc; i++) {
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("...................................................\n");
   return 0;

int main(int argc, char* argv[]) {
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   char *sql;
   const char* data = "Callback function called";

if (argc == 3 && (0 == strcmp(argv[1], "-f"))) {
    if(argc == 1){

   rc = sqlite3_open("test.db", &db);
     if( rc ) {
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   } else {
   /* Create SQL statement */
   sql = "CREATE TABLE CONTACTS("  \
         "ID INT PRIMARY KEY     NOT NULL," \
         "FIRSTNAME      TEXT    NOT NULL," \
         "LASTNAME       TEXT    NOT NULL," \
         "MOBILEPHONE       TEXT    NOT NULL," \
         "CITY            TEXT     NOT NULL," \
         "ADDRESS        CHAR(50)," \
         "COUNTRY         TEXT );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
   if( rc != SQLITE_OK ){
   fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Table created successfully\n");
   }
   sqlite3_close(db);
   return 0;
  }
 }
 }
}
void MainMenu()
{
        int optn; // option value
        int valid; //check if option is valid
        system("clear");
      valid = 0;
        while( valid == 0 )
       {
       printf("---------------DELIMITER---------------\n");
       printf("Phone book Menu\n");
       printf("(1) Add new record to phone book\n");
       printf("(2) Search phone book\n");
       printf("(3) Update phone book\n");
       printf("(4) Delete record from phone book\n");
       printf("(5) Quit\n");
       printf("---------------DELIMITER---------------\n");
       printf("Please choose your operation: ");

                if(scanf("%d", &optn) == 1)
                {
                        if(optn > 0 && optn < 6)
                        {
                                valid = 1;
                        }else{
                                printf("Error: Invalid option selected, please try again\n\n");
                }

        }
        //start the operations
        if(optn == 1)
        {
            AddMenu();
        }else if (optn == 2)
        {

                SearchMenu();
        }else if (optn == 3)
        {
                UpdateMenu();
        }else if (optn == 4)
        {
                DeleteMenu();
        }else{
                exit(0);
        }
    }
}
//search menu
void SearchMenu()
{
        int optn; // option value
        int valid; //check if option is valid
        int display_search; //allow csv file export
        char ch; //repeat option value
        sqlite3 *db;
        char *zErrMsg = 0;
         int rc;
         char *sql;
         const char* data;

        printf("\tSearch PhoneBook\n");
        printf("================================\n\n");
        valid = 0;
        while( valid == 0 )
        {
                printf("Select a search option:\n");
                printf("-----------------------\n");
                printf(" 1) Display search result\n");
                printf(" 2) Back\n\n");
                printf("Choose an option: ");

                if(scanf("%d", &optn) == 1)
                {
                        if(optn > 0 && optn < 3)
                        {
                                valid = 1;
                        }else{
                                printf("Error: Invalid option selected, please try again\n\n");
                        }
                }
        //start the operations
        if(optn == 1)
        {
         sql = "SELECT * from CONTACTS";

   /* Execute SQL statement */
        rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
  if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
  }

}

}
void AddMenu()
{
char *sql;
        char statement[512];
        char *fname = malloc(50);
        char *lname = malloc(50);
        char *city= malloc(50);
        char *country= malloc(50);
        sqlite3 *db;
        char *zErrMsg = 0;
         int rc;
        printf("Enter the First Name: ");
        scanf("%[^\n]s", fname);

        printf("Enter the Last Name: ");
        scanf("%[^\n]s", lname);

        printf("Enter the Mobile Phone: ");
        scanf("%[^\n]s", mobile);

        printf("Enter the City: ");
        scanf("%[^\n]s", city);

          printf("Enter the Country: ");
        scanf("%[^\n]s", country);

     //run SQL Statements

        sql = "INSERT INTO CONTACT (FirstName,LastName,MobilePhone,City,Country) "  \
         "VALUES ('%s','%s','%s','%s','%s' );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);

   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Records created successfully\n");
   }
   sqlite3_close(db);
   return;
}
void UpdateMenu()
{
char id;
int valid;
char *fname = malloc(50);
char *lname = malloc(50);
char *mobile= malloc(20);
char *city= malloc(50);
char *country= malloc(50);
char statement[512];
char values_cut[512];
char fname_out[50];
char lname_out[50];
char mobile_out[20];
char city_out[50];
char country_out[50];
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data;

if(do_search(0) == 0){

        valid = 0;
        while( valid == 0 )
        {
                printf("Enter the Number you want to update: ");

                if(scanf("%s", &id) == 1)
                        {
                                if(id > 0 )
                                {
                                        valid = 1;

                                        printf("\nUpdate the values, press enter if you do not want to change a field\n");
                                        printf("---------------------------------------------------------------------\n");

                                        //get the update values
                                        printf("Enter the First Name: ");
                                        if((scanf("%[^\n]s", fname) != 0)){
                                                snprintf(fname_out, sizeof fname_out, "FirstName='%s',",fname);
                                        }else{
                                                snprintf(fname_out,sizeof fname_out, "");
                                        }
                                        fname = fname_out;

                                        printf("Enter the Last Name: ");
                                        if((scanf("%[^\n]s", lname)!=0)){
                                                snprintf(lname_out,sizeof lname_out, "LastName='%s',",lname);
                                        }else{
                                                snprintf(lname_out,sizeof lname_out, "");
                                        }
                                        lname=lname_out;

                                     printf("Enter the Mobile Phone: ");
                                        if((scanf("%[^\n]s", mobile)!=0)){
                                                snprintf(mobile_out,sizeof mobile_out, "MobilePhone='%s',",mobile);
                                        }else{
                                                snprintf(mobile_out,sizeof mobile_out, "");
                                        }
                                        mobile=mobile_out;

                                        printf("Enter the City: ");
                                        if((scanf("%[^\n]s", city)!=0)){
                                                snprintf(city_out,sizeof city_out, "City='%s',",city);
                                        }else{
                                                snprintf(city_out,sizeof city_out, "");
                                        }
                                        city=city_out;

                                        printf("Enter the Country: ");
                                        if((scanf("%[^\n]s", country)!=0)){
                                                snprintf(country_out,sizeof country_out, "Country='%s',",country);
                                                                   }else{
                                                snprintf(country_out,sizeof country_out, "");
                                        }
                                        country=country_out;

                                        //remove the last comma from the query
                                        snprintf(values_cut,sizeof values_cut, "%s%s%s%s%s",fname,lname,mobile,city,country);

                                                }
                                        }

/* Create merged SQL statement */
   sql = "UPDATE CONTACT set %s where ID=%s";
         "SELECT * from CONTACT  where ID=%s";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);

   if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
}

}

}
//Delete menu
void DeleteMenu()
{
        int valid;
        int id, good;
        char *sql;
        char statement[512];
        sqlite3 *db;
        char *zErrMsg = 0;
        int rc;
        const char* data;
        int optn;
        //search first
        if(do_search(0)==0){

        valid = 0;
        while( valid == 0 )
        {
                printf("Enter the number you want to delete: ");

                if(scanf("%s", &id) == 1)
                        {
                                if(id > 0 )
                                {
                                        valid = 1;
/* Create merged SQL statement */
   sql = "DELETE from CONTACT where ID=%s; " \
         "SELECT * from CONTACT";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);

   if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
      }
   }while(optn!=5);
 }
}
}
}

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i = 0; i<argc; i++) {
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("...................................................\n");
   return 0;

int main(int argc, char* argv[]) {
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   char *sql;
   const char* data = "Callback function called";

if (argc == 3 && (0 == strcmp(argv[1], "-f"))) {
    if(argc == 1){

   rc = sqlite3_open("test.db", &db);
     if( rc ) {
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      return(0);
   } else {
   /* Create SQL statement */
   sql = "CREATE TABLE CONTACTS("  \
         "ID INT PRIMARY KEY     NOT NULL," \
         "FIRSTNAME      TEXT    NOT NULL," \
         "LASTNAME       TEXT    NOT NULL," \
         "MOBILEPHONE       TEXT    NOT NULL," \
         "CITY            TEXT     NOT NULL," \
         "ADDRESS        CHAR(50)," \
         "COUNTRY         TEXT );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
   if( rc != SQLITE_OK ){
   fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Table created successfully\n");
   }
   sqlite3_close(db);
   return 0;
  }
 }
 }
}
void MainMenu()
{
        int optn; // option value
        int valid; //check if option is valid
        system("clear");
      valid = 0;
        while( valid == 0 )
       {
       printf("---------------DELIMITER---------------\n");
       printf("Phone book Menu\n");
       printf("(1) Add new record to phone book\n");
       printf("(2) Search phone book\n");
       printf("(3) Update phone book\n");
       printf("(4) Delete record from phone book\n");
       printf("(5) Quit\n");
       printf("---------------DELIMITER---------------\n");
       printf("Please choose your operation: ");

                if(scanf("%d", &optn) == 1)
                {
                        if(optn > 0 && optn < 6)
                        {
                                valid = 1;
                        }else{
                                printf("Error: Invalid option selected, please try again\n\n");
                }

        }
        //start the operations
        if(optn == 1)
        {
            AddMenu();
        }else if (optn == 2)
        {

                SearchMenu();
        }else if (optn == 3)
        {
                UpdateMenu();
        }else if (optn == 4)
        {
                DeleteMenu();
        }else{
                exit(0);
        }
    }
}
//search menu
void SearchMenu()
{
        int optn; // option value
        int valid; //check if option is valid
        int display_search; //allow csv file export
        char ch; //repeat option value
        sqlite3 *db;
        char *zErrMsg = 0;
         int rc;
         char *sql;
         const char* data;

        printf("\tSearch PhoneBook\n");
        printf("================================\n\n");
        valid = 0;
        while( valid == 0 )
        {
                printf("Select a search option:\n");
                printf("-----------------------\n");
                printf(" 1) Display search result\n");
                printf(" 2) Back\n\n");
                printf("Choose an option: ");

                if(scanf("%d", &optn) == 1)
                {
                        if(optn > 0 && optn < 3)
                        {
                                valid = 1;
                        }else{
                                printf("Error: Invalid option selected, please try again\n\n");
                        }
                }
        //start the operations
        if(optn == 1)
        {
         sql = "SELECT * from CONTACTS";

   /* Execute SQL statement */
        rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
  if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
  }

}

}
void AddMenu()
{
char *sql;
        char statement[512];
        char *fname = malloc(50);
        char *lname = malloc(50);
        char *city= malloc(50);
        char *country= malloc(50);
        sqlite3 *db;
        char *zErrMsg = 0;
         int rc;
        printf("Enter the First Name: ");
        scanf("%[^\n]s", fname);

        printf("Enter the Last Name: ");
        scanf("%[^\n]s", lname);

        printf("Enter the Mobile Phone: ");
        scanf("%[^\n]s", mobile);

        printf("Enter the City: ");
        scanf("%[^\n]s", city);

          printf("Enter the Country: ");
        scanf("%[^\n]s", country);

     //run SQL Statements

        sql = "INSERT INTO CONTACT (FirstName,LastName,MobilePhone,City,Country) "  \
         "VALUES ('%s','%s','%s','%s','%s' );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);

   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Records created successfully\n");
   }
   sqlite3_close(db);
   return;
}
void UpdateMenu()
{
char id;
int valid;
char *fname = malloc(50);
char *lname = malloc(50);
char *mobile= malloc(20);
char *city= malloc(50);
char *country= malloc(50);
char statement[512];
char values_cut[512];
char fname_out[50];
char lname_out[50];
char mobile_out[20];
char city_out[50];
char country_out[50];
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data;

if(do_search(0) == 0){

        valid = 0;
        while( valid == 0 )
        {
                printf("Enter the Number you want to update: ");

                if(scanf("%s", &id) == 1)
                        {
                                if(id > 0 )
                                {
                                        valid = 1;

                                        printf("\nUpdate the values, press enter if you do not want to change a field\n");
                                        printf("---------------------------------------------------------------------\n");

                                        //get the update values
                                        printf("Enter the First Name: ");
                                        if((scanf("%[^\n]s", fname) != 0)){
                                                snprintf(fname_out, sizeof fname_out, "FirstName='%s',",fname);
                                        }else{
                                                snprintf(fname_out,sizeof fname_out, "");
                                        }
                                        fname = fname_out;

                                        printf("Enter the Last Name: ");
                                        if((scanf("%[^\n]s", lname)!=0)){
                                                snprintf(lname_out,sizeof lname_out, "LastName='%s',",lname);
                                        }else{
                                                snprintf(lname_out,sizeof lname_out, "");
                                        }
                                        lname=lname_out;

                                     printf("Enter the Mobile Phone: ");
                                        if((scanf("%[^\n]s", mobile)!=0)){
                                                snprintf(mobile_out,sizeof mobile_out, "MobilePhone='%s',",mobile);
                                        }else{
                                                snprintf(mobile_out,sizeof mobile_out, "");
                                        }
                                        mobile=mobile_out;

                                        printf("Enter the City: ");
                                        if((scanf("%[^\n]s", city)!=0)){
                                                snprintf(city_out,sizeof city_out, "City='%s',",city);
                                        }else{
                                                snprintf(city_out,sizeof city_out, "");
                                        }
                                        city=city_out;

                                        printf("Enter the Country: ");
                                        if((scanf("%[^\n]s", country)!=0)){
                                                snprintf(country_out,sizeof country_out, "Country='%s',",country);
                                                                   }else{
                                                snprintf(country_out,sizeof country_out, "");
                                        }
                                        country=country_out;

                                        //remove the last comma from the query
                                        snprintf(values_cut,sizeof values_cut, "%s%s%s%s%s",fname,lname,mobile,city,country);

                                                }
                                        }

/* Create merged SQL statement */
   sql = "UPDATE CONTACT set %s where ID=%s";
         "SELECT * from CONTACT  where ID=%s";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);

   if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
}

}

}
//Delete menu
void DeleteMenu()
{
        int valid;
        int id, good;
        char *sql;
        char statement[512];
        sqlite3 *db;
        char *zErrMsg = 0;
        int rc;
        const char* data;
        int optn;
        //search first
        if(do_search(0)==0){

        valid = 0;
        while( valid == 0 )
        {
                printf("Enter the number you want to delete: ");

                if(scanf("%s", &id) == 1)
                        {
                                if(id > 0 )
                                {
                                        valid = 1;
/* Create merged SQL statement */
   sql = "DELETE from CONTACT where ID=%s; " \
         "SELECT * from CONTACT";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);

   if( rc != SQLITE_OK ) {
      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
   return;
      }
   }while(optn!=5);
 }
}
}
}

when i  compile this c code on putty using

gcc insertno.c -o insertno -lsqlite3

i get this error below, solution will be much appreciated.thanks

/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20):
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20):

Body:
The body of your function callback() has not been properly closed off.

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i = 0; i<argc; i++) {
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("...................................................\n");
   return 0;
} // THIS WAS MISSING

The reason GCC didn't flag an error when it encountered a function definition within the callback() function is that GCC has an extension called nested functions.


答:
Look at the structure of what you have to work with, starting from the top:
You have a JSONObject which has 5 fields. Key "cod" which holds a string value of "200", key "message" which has a numeric value of 0.4667, key "cnt" which has a numeric value of 7, key "list" which has a value which is a JSONArray, and key "country" which holds a string value of "IE". That is the outermost JSON object. from that you want to parse the JSONArray value from the key "list". So far, you're good! But if you look at each one of the JSONObjects in the JSONArray, you'll see that the second key in each one, "main", the value for it is another JSONObject! It gets better, because "weather" holds a JSONArray which only has one JSONObject in it for the first one, but by being an array you can figure that it may hold more than one object so you have to iterate through that too. It's going to be a bit involved, but is doable, you just have to look closely at what the expected format is and correctly identify the parts.</p>

Title: How to parse OpenWeatherMap 16-day json?

Body:
Hi I'm trying to create an android application that will display the weather from opneweathermap. So far I have the application displaying today's weather, but I'm not able to parse 16-day JSON. I am trying to get the min and max temp of each of the days. Any help will be appreciated.

{"cod":"200","message":0.4667,"cnt":7,"list":[{"dt":1512777600,"main":{"temp":0.71,"temp_min":0.71,"temp_max":5.21,"pressure":1030.25,"sea_level":1035.12,"grnd_level":1030.25,"humidity":100,"temp_kf":-4.5},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":8.86,"deg":304.5},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-09 00:00:00"},{"dt":1512788400,"main":{"temp":1.35,"temp_min":1.35,"temp_max":4.72,"pressure":1029.09,"sea_level":1034,"grnd_level":1029.09,"humidity":100,"temp_kf":-3.38},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":8.07,"deg":292},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-09 03:00:00"},{"dt":1512799200,"main":{"temp":2.21,"temp_min":2.21,"temp_max":4.46,"pressure":1027.47,"sea_level":1032.37,"grnd_level":1027.47,"humidity":100,"temp_kf":-2.25},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":7.66,"deg":280.001},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-09 06:00:00"},{"dt":1512810000,"main":{"temp":3.35,"temp_min":3.35,"temp_max":4.47,"pressure":1025.64,"sea_level":1030.48,"grnd_level":1025.64,"humidity":100,"temp_kf":-1.13},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"clouds":{"all":48},"wind":{"speed":6.69,"deg":275.001},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-09 09:00:00"},{"dt":1512820800,"main":{"temp":5.02,"temp_min":5.02,"temp_max":5.02,"pressure":1023.2,"sea_level":1028.06,"grnd_level":1023.2,"humidity":100,"temp_kf":0},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"clouds":{"all":68},"wind":{"speed":6.12,"deg":266},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-09 12:00:00"},{"dt":1512831600,"main":{"temp":5.29,"temp_min":5.29,"temp_max":5.29,"pressure":1019.44,"sea_level":1024.28,"grnd_level":1019.44,"humidity":100,"temp_kf":0},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"clouds":{"all":44},"wind":{"speed":4.76,"deg":266.002},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-09 15:00:00"},{"dt":1512842400,"main":{"temp":4.54,"temp_min":4.54,"temp_max":4.54,"pressure":1016.14,"sea_level":1021.07,"grnd_level":1016.14,"humidity":100,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":3.37,"deg":254.504},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-09 18:00:00"}],"city":{"id":2964574,"name":"Dublin","coord":{"lat":53.344,"lon":-6.2672},"country":"IE"}}

private void renderWeather(JSONObject json)
{
    /*
    //minField.setText(json.toString());

    try
    {
        JSONArray resultArray = json.getJSONArray("list");
        for(int i = 0; i < resultArray.length(); i++)
        {
            JSONObject obj = resultArray.getJSONObject(i);
            //store your variable
            String tempMin = obj.getString("temp_min");
            Log.i("TAG","Temp Min " + i + ": "+ tempMin);
        }
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    */

    String yourJsonString = json.toString();

    JSONArray jsonArray = null;
    try
    {
        jsonArray = new JSONArray(yourJsonString);

        for (int i = 0; i < jsonArray.length(); i++)
        {
            JSONObject obj1 = jsonArray.getJSONObject(i);
            JSONArray results = obj1.getJSONArray("list");
            String tempMin =  results.getJSONObject(0).getString("temp_min");
            Log.i("TAG","Temp Min " + i + ": "+ tempMin);
        }
    }

    catch (JSONException e)
    {
        e.printStackTrace();
    }
}

I've tried the two ways shown in the code and neither work. The first way gets a JSONException: No value for temp_min error. The second way gets a JSONException: Value error.


问:
Decoding RTP G,711 A-Law Packet Problem , difference between c# & c++
first sorry for my English

by using c#
I'm  try to decoding RTP  A-Law Packet but it is gave me a noise,
i checked my code with wireshark code  which can gave me the voice without noise  , i can not get the difference between   wireshark  code (c++) and my code (c#) which because I can not Debugging  wireshark   , but i get the  difference Bytes  resulting from my code and wireshark  code

i will write the Bytes result  from two code and simple of my code and  wireshark

for example :

when the alaw_exp_table[data[i]] = -8

in my cod the bytes result  are            : 248 , 255

in wireshark  code the bytes result  are   :  255 , 248

are you see 248,255  :  255,248  i think it was a reflection but  the next example not

when the alaw_exp_table[data[i]] = 8

in my cod the bytes result  are :  8 , 0

in wireshark  code the bytes result  are  : 0 , 0

this wireshark

```<code> int
    decodeG711a(void *input, int inputSizeBytes, void *output, int *outputSizeBytes)

    {

    guint8 *dataIn = (guint8 *)input;

    gint16 *dataOut = (gint16 *)output;

     int i;

    for (i=0; i<inputSizeBytes; i++)

     {

     dataOut[i] = alaw_exp_table[dataIn[i]];

    }

     *outputSizeBytes = inputSizeBytes * 2;

     return 0;

    }

   static  short[] alaw_exp_table= {
      -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
      -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
      -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
      -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
     -22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
     -30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
     -11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472,
     -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
       -344,  -328,  -376,  -360,  -280,  -264,  -312,  -296,
       -472,  -456,  -504,  -488,  -408,  -392,  -440,  -424,
        -88,   -72,  -120,  -104,   -24,    -8,   -56,   -40,
       -216,  -200,  -248,  -232,  -152,  -136,  -184,  -168,
      -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
      -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
       -688,  -656,  -752,  -720,  -560,  -528,  -624,  -592,
       -944,  -912, -1008,  -976,  -816,  -784,  -880,  -848,
       5504,  5248,  6016,  5760,  4480,  4224,  4992,  4736,
       7552,  7296,  8064,  7808,  6528,  6272,  7040,  6784,
       2752,  2624,  3008,  2880,  2240,  2112,  2496,  2368,
       3776,  3648,  4032,  3904,  3264,  3136,  3520,  3392,
      22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
      30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
      11008, 10496, 12032, 11520,  8960,  8448,  9984,  9472,
      15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
        344,   328,   376,   360,   280,   264,   312,   296,
        472,   456,   504,   488,   408,   392,   440,   424,
         88,    72,   120,   104,    24,     8,    56,    40,
        216,   200,   248,   232,   152,   136,   184,   168,
       1376,  1312,  1504,  1440,  1120,  1056,  1248,  1184,
       1888,  1824,  2016,  1952,  1632,  1568,  1760,  1696,
        688,   656,   752,   720,   560,   528,   624,   592,
        944,   912,  1008,   976,   816,   784,   880,   848};
</code>```

and this is my code

```<code> public static void ALawDecode(byte data, out byte[] decoded)
        {
            int size = data.Length;
            decoded = new byte[size * 2];
            for (int i = 0; i < size; i++)
            {
                 //First byte is the less significant byte
                decoded[2 * i] = (byte)(alaw_exp_table[data[i]] & 0xff);
                //Second byte is the more significant byte
                decoded[2 * i + 1] = (byte)(alaw_exp_table[data[i]] >> 8);
            }
        }
</code>```

the alaw_exp_table is same in my code and wireshark code

please tell me  what is the wrong in my code which do that noise ?

thanks in advance

答:
Your are probably handling the endianess incorrectly.

Try swapping the the two decoding operations in your C# sample. Eg:

```<code>decoded[2 * i + 1] = (byte)(alaw_exp_table[data[i]] & 0xff);
decoded[2 * i] = (byte)(alaw_exp_table[data[i]] >> 8);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
first sorry for my English

by using c#
I'm  try to decoding RTP  A-Law Packet but it is gave me a noise,
i checked my code with wireshark code  which can gave me the voice without noise  , i can not get the difference between   wireshark  code (c++) and my code (c#) which because I can not Debugging  wireshark   , but i get the  difference Bytes  resulting from my code and wireshark  code

i will write the Bytes result  from two code and simple of my code and  wireshark

for example :

when the alaw_exp_table[data[i]] = -8

in my cod the bytes result  are            : 248 , 255

in wireshark  code the bytes result  are   :  255 , 248

are you see 248,255  :  255,248  i think it was a reflection but  the next example not

when the alaw_exp_table[data[i]] = 8

in my cod the bytes result  are :  8 , 0

in wireshark  code the bytes result  are  : 0 , 0

this wireshark

 int
    decodeG711a(void *input, int inputSizeBytes, void *output, int *outputSizeBytes)

    {

    guint8 *dataIn = (guint8 *)input;

    gint16 *dataOut = (gint16 *)output;

     int i;

    for (i=0; i<inputSizeBytes; i++)

     {

     dataOut[i] = alaw_exp_table[dataIn[i]];

    }

     *outputSizeBytes = inputSizeBytes * 2;

     return 0;

    }

   static  short[] alaw_exp_table= {
      -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
      -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
      -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
      -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
     -22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
     -30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
     -11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472,
     -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
       -344,  -328,  -376,  -360,  -280,  -264,  -312,  -296,
       -472,  -456,  -504,  -488,  -408,  -392,  -440,  -424,
        -88,   -72,  -120,  -104,   -24,    -8,   -56,   -40,
       -216,  -200,  -248,  -232,  -152,  -136,  -184,  -168,
      -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
      -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
       -688,  -656,  -752,  -720,  -560,  -528,  -624,  -592,
       -944,  -912, -1008,  -976,  -816,  -784,  -880,  -848,
       5504,  5248,  6016,  5760,  4480,  4224,  4992,  4736,
       7552,  7296,  8064,  7808,  6528,  6272,  7040,  6784,
       2752,  2624,  3008,  2880,  2240,  2112,  2496,  2368,
       3776,  3648,  4032,  3904,  3264,  3136,  3520,  3392,
      22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
      30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
      11008, 10496, 12032, 11520,  8960,  8448,  9984,  9472,
      15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
        344,   328,   376,   360,   280,   264,   312,   296,
        472,   456,   504,   488,   408,   392,   440,   424,
         88,    72,   120,   104,    24,     8,    56,    40,
        216,   200,   248,   232,   152,   136,   184,   168,
       1376,  1312,  1504,  1440,  1120,  1056,  1248,  1184,
       1888,  1824,  2016,  1952,  1632,  1568,  1760,  1696,
        688,   656,   752,   720,   560,   528,   624,   592,
        944,   912,  1008,   976,   816,   784,   880,   848};

and this is my code

 public static void ALawDecode(byte data, out byte[] decoded)
        {
            int size = data.Length;
            decoded = new byte[size * 2];
            for (int i = 0; i < size; i++)
            {
                 //First byte is the less significant byte
                decoded[2 * i] = (byte)(alaw_exp_table[data[i]] & 0xff);
                //Second byte is the more significant byte
                decoded[2 * i + 1] = (byte)(alaw_exp_table[data[i]] >> 8);
            }
        }

the alaw_exp_table is same in my code and wireshark code

please tell me  what is the wrong in my code which do that noise ?

thanks in advance

Body:
Your are probably handling the endianess incorrectly.

Try swapping the the two decoding operations in your C# sample. Eg:

decoded[2 * i + 1] = (byte)(alaw_exp_table[data[i]] & 0xff);
decoded[2 * i] = (byte)(alaw_exp_table[data[i]] >> 8);


问:
websocketpp asio listen error
I have a multi-threaded websocketpp server. With no clients connected when I quit the program and relaunch, it works with no issues.

However when a client is connected and I quit/relaunch, the program throws this error

```<code>[2017-08-06 15:36:05] [info] asio listen error: system:98 ()
terminate called after throwing an instance of 'websocketpp::exception'
   what():  Underlying Transport Error
Aborted
</code>```

I believe I have a proper disconnect sequence going and I have the following message (my own debug info) when I initiate the quit sequence

```<code>[2017-08-06 15:35:55] [control] Control frame received with opcode 8
on_close
[2017-08-06 15:35:55] [disconnect] Disconnect close local:[1000] remote:[1000]
Quitting :3
Waiting for thread
</code>```

What does the asio error mean? I am hoping someone has seen this before so that I can begin troubleshooting. Thanks!

EDIT:
I am adapting the stock broadcast_server example where

```<code>typedef std::map<connection_hdl, connection_data, std::owner_less<connection_hdl> > con_list;
con_list m_connections;
</code>```

Code to close connections.

```<code>lock_guard<mutex> guard(m_connection_lock);
std::cout << "Closing Server" << std::endl;
con_list::iterator it;
for (it = m_connections.begin(); it != m_connections.end(); ++it)
{
    m_server.close(it->first, websocketpp::close::status::normal, "", ec);
    if (ec)
    {
        std::cout << "> Error initiating client close: " << ec.message() << std::endl;
    }
    m_connections.erase(it->first);
}
</code>```

Also in destructor for broadcast_server class I have a m_server.stop()

答:
Whenever there's a websocketpp::exception, I first check anywhere I'm explicitly using the endpoint, in your case m_server.

For instance, it could be somewhere where you are calling m_server.send(...). Since you're multithreading, it's very possible that one of the threads may be trying to utilize a connection_hdl while it has already been closed by a different thread.

In that case, it's usually a websocketpp::exception invalid state. <s>I'm not sure for the Underlying Transport Error.</s>

You can use breakpoints to spot the culprit (or put a bunch of cout sequences in different methods, and see which sequence is broken before the exception is thrown), or use a try/catch:

```<code>try {
    m_server.send(hdl, ...);
    // or
    m_server.close(hdl, ...);
    // or really anything you're trying to do using `m_server`.
} catch (const websocketpp::exception &e) {//by safety, I just go with `const std::exception` so that it grabs any potential exceptions out there.
    std::cout << "Exception in method foo() because: " << e.what() /* log the cause of the exception */ << std::endl;
}
</code>```

Otherwise, I have noticed that it will sometimes throw an exception when you're trying to close a connection_hdl, even if no other thread is seemingly accessing it. But if you put it in a try/catch, although it still throws the exception, since it doesn't terminate the program, it eventually closes the handler.

Also, maybe try m_server.pause_reading(it->first) before calling close() to freeze activity from that handler.

After second look, I think the exception you're getting is thrown where you listen with m_server.listen(...). Try surrounding it with a try/catch and putting a custom logging message.

Title: websocketpp asio listen error

Body:
I have a multi-threaded websocketpp server. With no clients connected when I quit the program and relaunch, it works with no issues.

However when a client is connected and I quit/relaunch, the program throws this error

[2017-08-06 15:36:05] [info] asio listen error: system:98 ()
terminate called after throwing an instance of 'websocketpp::exception'
   what():  Underlying Transport Error
Aborted

I believe I have a proper disconnect sequence going and I have the following message (my own debug info) when I initiate the quit sequence

[2017-08-06 15:35:55] [control] Control frame received with opcode 8
on_close
[2017-08-06 15:35:55] [disconnect] Disconnect close local:[1000] remote:[1000]
Quitting :3
Waiting for thread

What does the asio error mean? I am hoping someone has seen this before so that I can begin troubleshooting. Thanks!

EDIT:
I am adapting the stock broadcast_server example where

typedef std::map<connection_hdl, connection_data, std::owner_less<connection_hdl> > con_list;
con_list m_connections;

Code to close connections.

lock_guard<mutex> guard(m_connection_lock);
std::cout << "Closing Server" << std::endl;
con_list::iterator it;
for (it = m_connections.begin(); it != m_connections.end(); ++it)
{
    m_server.close(it->first, websocketpp::close::status::normal, "", ec);
    if (ec)
    {
        std::cout << "> Error initiating client close: " << ec.message() << std::endl;
    }
    m_connections.erase(it->first);
}

Also in destructor for broadcast_server class I have a m_server.stop()

Body:
Whenever there's a websocketpp::exception, I first check anywhere I'm explicitly using the endpoint, in your case m_server.

For instance, it could be somewhere where you are calling m_server.send(...). Since you're multithreading, it's very possible that one of the threads may be trying to utilize a connection_hdl while it has already been closed by a different thread.

In that case, it's usually a websocketpp::exception invalid state. <s>I'm not sure for the Underlying Transport Error.</s>

You can use breakpoints to spot the culprit (or put a bunch of cout sequences in different methods, and see which sequence is broken before the exception is thrown), or use a try/catch:

try {
    m_server.send(hdl, ...);
    // or
    m_server.close(hdl, ...);
    // or really anything you're trying to do using `m_server`.
} catch (const websocketpp::exception &e) {//by safety, I just go with `const std::exception` so that it grabs any potential exceptions out there.
    std::cout << "Exception in method foo() because: " << e.what() /* log the cause of the exception */ << std::endl;
}

Otherwise, I have noticed that it will sometimes throw an exception when you're trying to close a connection_hdl, even if no other thread is seemingly accessing it. But if you put it in a try/catch, although it still throws the exception, since it doesn't terminate the program, it eventually closes the handler.

Also, maybe try m_server.pause_reading(it->first) before calling close() to freeze activity from that handler.

After second look, I think the exception you're getting is thrown where you listen with m_server.listen(...). Try surrounding it with a try/catch and putting a custom logging message.