答:
The Find method does not return the found text, but the first cell where the text was found, and when it is not found it returns Nothing. Furthermore, your Range has numbers (going by the title of your question), while your form might have a text input box (the question is not clear on that). Your condition is going to be false each time because of this.

Instead, convert the text input to number, and use the fact that the Find method returns Nothing when the text is not found:

Change this:

```<code>If MoneyTextBox.Value = range("H:H").Find(MoneyTextBox.Value) Then
</code>```

to:

```<code>If Not Range("H:H").Find(CLng(MoneyTextBox.Value)) Is Nothing Then
</code>```

Title: Show "duplicate Number" when number is not found in range

Body:
If MoneyTextBox.Value = range("H:H").Find(MoneyTextBox.Value) Then
    MsgBox "Duplicate number"
EndIf

Body:
The Find method does not return the found text, but the first cell where the text was found, and when it is not found it returns Nothing. Furthermore, your Range has numbers (going by the title of your question), while your form might have a text input box (the question is not clear on that). Your condition is going to be false each time because of this.

Instead, convert the text input to number, and use the fact that the Find method returns Nothing when the text is not found:

Change this:

If MoneyTextBox.Value = range("H:H").Find(MoneyTextBox.Value) Then

to:

If Not Range("H:H").Find(CLng(MoneyTextBox.Value)) Is Nothing Then


来源: stackexchange

问:
You have an error in your SQL syntax; when try to submit form

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '','1','7','123tw')' at line 2

I got the above error when submitting the form.

```<code> <?php
    session_start();
    $branch=$_SESSION['branch'];
    include('../dist/includes/dbcon.php');
        $name = $_POST['prod_name'];
        $price = $_POST['prod_price'];
        $desc = $_POST['prod_desc'];
        $supplier = $_POST['supplier'];
        $reorder = $_POST['reorder'];
        $category = $_POST['category'];
        //$quantity = $_POST['prod_qty'];
        $serialn = $_POST['serialn'];

        $query2=mysqli_query($con,"select * from product where prod_name='$name' and branch_id='$branch'")or die(mysqli_error($con));
            $count=mysqli_num_rows($query2);

            if ($count>0)
            {
                echo "<script type='text/javascript'>alert('Product already exist!');</script>";
                echo "<script>document.location='product.php'</script>";
            }
            else
            {

                $pic = $_FILES["image"]["name"];
                if ($pic=="")
                {
                    $pic="default.gif";
                }
                else
                {
                    $pic = $_FILES["image"]["name"];
                    $type = $_FILES["image"]["type"];
                    $size = $_FILES["image"]["size"];
                    $temp = $_FILES["image"]["tmp_name"];
                    $error = $_FILES["image"]["error"];

                    if ($error > 0)
                    {
                        die("Error uploading file! Code $error.");
                        }
                    else{
                        if($size > 100000000000) //conditions for the file
                            {
                            die("Format is not allowed or file size is too big!");
                            }
                    else
                          {
                        move_uploaded_file($temp, "../dist/uploads/".$pic);
                          }
                        }
                }

                mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
                VALUES('$name','$price','$desc','$pic','$category', $reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con));

                echo "<script type='text/javascript'>alert('Successfully added new product!');</script>";
                          echo "<script>document.location='product.php'</script>";
            }
    ?>
</code>```

答:
You have missed ' before $reorder try this code

```<code> mysqli_query($con,"INSERT INTO product(prod_name, prod_price, prod_desc ,prod_pic, cat_id, reorder, supplier_id, branch_id, serialn) VALUES ('$name', '$price', '$desc', '$pic', '$category', '$reorder', '$supplier', '$branch', '$serialn')")or die(mysqli_error($con))or die(mysqli_error($con));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '','1','7','123tw')' at line 2

I got the above error when submitting the form.

 <?php
    session_start();
    $branch=$_SESSION['branch'];
    include('../dist/includes/dbcon.php');
        $name = $_POST['prod_name'];
        $price = $_POST['prod_price'];
        $desc = $_POST['prod_desc'];
        $supplier = $_POST['supplier'];
        $reorder = $_POST['reorder'];
        $category = $_POST['category'];
        //$quantity = $_POST['prod_qty'];
        $serialn = $_POST['serialn'];

        $query2=mysqli_query($con,"select * from product where prod_name='$name' and branch_id='$branch'")or die(mysqli_error($con));
            $count=mysqli_num_rows($query2);

            if ($count>0)
            {
                echo "";
                echo "";
            }
            else
            {

                $pic = $_FILES["image"]["name"];
                if ($pic=="")
                {
                    $pic="default.gif";
                }
                else
                {
                    $pic = $_FILES["image"]["name"];
                    $type = $_FILES["image"]["type"];
                    $size = $_FILES["image"]["size"];
                    $temp = $_FILES["image"]["tmp_name"];
                    $error = $_FILES["image"]["error"];

                    if ($error > 0)
                    {
                        die("Error uploading file! Code $error.");
                        }
                    else{
                        if($size > 100000000000) //conditions for the file
                            {
                            die("Format is not allowed or file size is too big!");
                            }
                    else
                          {
                        move_uploaded_file($temp, "../dist/uploads/".$pic);
                          }
                        }
                }

                mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
                VALUES('$name','$price','$desc','$pic','$category', $reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con));

                echo "";
                          echo "";
            }
    ?>

Body:
You have missed ' before $reorder try this code

 mysqli_query($con,"INSERT INTO product(prod_name, prod_price, prod_desc ,prod_pic, cat_id, reorder, supplier_id, branch_id, serialn) VALUES ('$name', '$price', '$desc', '$pic', '$category', '$reorder', '$supplier', '$branch', '$serialn')")or die(mysqli_error($con))or die(mysqli_error($con));


问:
How can I tell react router v4 where to load the component?
This is the thing that confuses me about react router 4. I currently have the routes setup in the main parent component index.jsx. The navigation bar is in it's own component NavBar.jsx.

I want it so that when you click a link in NavBar.jsx, it loads the component into Body.jsx. Currently It loads a component across the entire screen replacing everything.

I believe with React Router 3 you were supposed to do something with this.props.children but if you guys and gals can shed some light on this for me, I'd greatly appreciate it. Thank you.

Here's the top most component code:

ReactDOM.render(
  <Router>

      <Route path="/" component={Index} />

  </Router>

, document.getElementById('app'));```

My components go from Index > Body > TabArea
The navbar is in Index > Banner > HotelTop

Tab Area is the location I want to render the component that HotelTop's navbar chooses.

答:
I figured it out. In the place you want your links to load, you have to put a switch and then routes there, but don't put a new router there.

something like...

  <switch>
    <Route exact path = "/" component={containertoloadpaths}/>
      <Route path = "/Path1" component={component1}
      <Route path = "/Path2" component={component2}
    </Route>
  </switch>

//You can put code like this anywhere in your app where you'd like your links to load, and they'll load there.```

Body:
This is the thing that confuses me about react router 4. I currently have the routes setup in the main parent component index.jsx. The navigation bar is in it's own component NavBar.jsx.

I want it so that when you click a link in NavBar.jsx, it loads the component into Body.jsx. Currently It loads a component across the entire screen replacing everything.

I believe with React Router 3 you were supposed to do something with this.props.children but if you guys and gals can shed some light on this for me, I'd greatly appreciate it. Thank you.

Here's the top most component code:

ReactDOM.render(
  <Router>

      <Route path="/" component={Index} />

  </Router>

, document.getElementById('app'));

My components go from Index > Body > TabArea
The navbar is in Index > Banner > HotelTop

Tab Area is the location I want to render the component that HotelTop's navbar chooses.

Body:
I figured it out. In the place you want your links to load, you have to put a switch and then routes there, but don't put a new router there.

something like...

<div>
  <switch>
    <Route exact path = "/" component={containertoloadpaths}/>
      <Route path = "/Path1" component={component1}
      <Route path = "/Path2" component={component2}
    </Route>
  </switch>
</div>

//You can put code like this anywhere in your app where you'd like your links to load, and they'll load there.


问:
Instance Tag Info using boto3 : Getting None object
My python code is as follow and need help with the same. Thanks

```<code>    import boto3
    import yaml

    def get_all_running_instances(unique_name):
        """
        Returns instance data for given instance id.
        :param unique_name:
        :return:
        """
        count = 1
        rname = unique_name.rsplit('-', 1)[0] + '-' + str(count)
        print rname
        ec2 = boto3.resource('ec2')
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'pending']}])
        for instance in instances:
          print(instance.id, instance.instance_type)
        for instance in instances:
          for tag in instance.tags:
                if rname in tag['Value'] and "Name" in tag['Key']:
                    count = count + 1
                    rname = rname.rsplit('-', 1)[0] + '-' + str(count)
        return count
    x = get_all_running_instances('test-1')
    print x
</code>```

Output is as follows and is not able to get the tag information associated with each of the instance.
I am running a Lambda on the tag information returned as part of this function.

```<code>    ('i-08987804493yyyyyy82', 't2.medium')
    ('i-0e96754xxxxxxxxx', 't2.small')
    Traceback (most recent call last):
      File "dummy.py", line 30, in <module>
        x = get_all_running_instances('test-1')
      File "dummy.py", line 23, in get_all_running_instances
        for tag in instance.tags:
    **TypeError**: 'NoneType' object is not iterable
</code>```

答:
You are assuming all instances have at least one tag. In your case, there are instances with no tags which causes your code to fail. Instead, you can check if tags are present before iterating on tags.

```<code>for instance in instances:
  if instance.tags:
    for tag in instance.tags:
</code>```

The above code will ignore the instances that have no tag defined. You can modify the code to suit your needs. To verify this, you can also print the tags when you are printing the instance-id and instance-type.

```<code>for instance in instances:
  print(instance.id, instance.instance_type, instance.tags)
</code>```

Body:
My python code is as follow and need help with the same. Thanks

    import boto3
    import yaml

    def get_all_running_instances(unique_name):
        """
        Returns instance data for given instance id.
        :param unique_name:
        :return:
        """
        count = 1
        rname = unique_name.rsplit('-', 1)[0] + '-' + str(count)
        print rname
        ec2 = boto3.resource('ec2')
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'pending']}])
        for instance in instances:
          print(instance.id, instance.instance_type)
        for instance in instances:
          for tag in instance.tags:
                if rname in tag['Value'] and "Name" in tag['Key']:
                    count = count + 1
                    rname = rname.rsplit('-', 1)[0] + '-' + str(count)
        return count
    x = get_all_running_instances('test-1')
    print x

Output is as follows and is not able to get the tag information associated with each of the instance.
I am running a Lambda on the tag information returned as part of this function.

    ('i-08987804493yyyyyy82', 't2.medium')
    ('i-0e96754xxxxxxxxx', 't2.small')
    Traceback (most recent call last):
      File "dummy.py", line 30, in <module>
        x = get_all_running_instances('test-1')
      File "dummy.py", line 23, in get_all_running_instances
        for tag in instance.tags:
    **TypeError**: 'NoneType' object is not iterable

Body:
You are assuming all instances have at least one tag. In your case, there are instances with no tags which causes your code to fail. Instead, you can check if tags are present before iterating on tags.

for instance in instances:
  if instance.tags:
    for tag in instance.tags:

The above code will ignore the instances that have no tag defined. You can modify the code to suit your needs. To verify this, you can also print the tags when you are printing the instance-id and instance-type.

for instance in instances:
  print(instance.id, instance.instance_type, instance.tags)


问:
How to open a new ViewController from every CollectionViewCell using a FlipAnimation and dismiss Swift 3
Have implemented collectionview it works fine but i want FlipAnimation while opening a new view controller from the cell and dismiss back to the cell. how to achieve the same.As i dont have any idea of Animation. Please Help.Thank you.
code

```<code>import UIKit

    class DashBoardVC: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
    {

    @IBOutlet weak var logoutbtn: UIButton!
    @IBOutlet weak var menubtn: UIButton!

    var names = ["Dashboard","Add Book","Delete Book","Search Book","On Demand","About Us"]

    var useimages = [UIImage(named:"dashboard_icon2"),UIImage(named:"book_blue_add"),UIImage(named:"book_blue_delete"),UIImage(named:"book_blue_view"),UIImage(named:"book_blue_new"),UIImage(named:"businesspeople2"),]

 override func viewDidLoad()
      {
             super.viewDidLoad()

        }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
         {
               return names.count
          }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
      {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellcollect", for: indexPath) as! mycollectioncell

        cell.collectLabel.text! = names[indexPath.row]
        cell.collectimage.image = useimages[indexPath.row]
        return cell
     }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
       {
        let padding : CGFloat =  15
        let collectionViewSize = collectionView.frame.size.width - padding
        return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)

         }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
        {

    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    switch(indexPath.row)
    {
    case 0:
    let desVC = storyboard.instantiateViewController(withIdentifier: "DashboardClick") as! DashboardClick
    self.navigationController?.pushViewController(desVC, animated: true)
        break
    case 1:
        let desVC = storyboard.instantiateViewController(withIdentifier: "AddBookVC") as! AddBookVC
        self.navigationController?.pushViewController(desVC, animated: true)
        break
    case 2:
        let desVC = storyboard.instantiateViewController(withIdentifier: "DeleteBookVC") as! DeleteBookVC
        self.navigationController?.pushViewController(desVC, animated: true)
        break

    case 3:
        let desVC = storyboard.instantiateViewController(withIdentifier: "SearchBookVC") as! SearchBookVC
        self.navigationController?.pushViewController(desVC, animated: true)
         break

    case 4:
        let desVC = storyboard.instantiateViewController(withIdentifier: "onDemandBookVC") as! onDemandBookVC
        self.navigationController?.pushViewController(desVC, animated: true)

        break
    default:
        break
    }

         }

override func viewWillAppear(_ animated: Bool)
 {
    self.navigationController?.navigationBar.isHidden = true
    self.navigationController?.toolbar.isHidden = true
  }

@IBAction func menutapped(_ sender: Any)
       {
    var appdelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

    appdelegate.centerContainer?.toggle(MMDrawerSide.left, animated: true, completion: nil)

           }
        }
</code>```

mycollectioncell.swift

```<code>import UIKit

class mycollectioncell: UICollectionViewCell {

@IBOutlet weak var collectLabel: UILabel!

@IBOutlet weak var collectimage: UIImageView!

}
</code>```

答:
here Student is NSObjectClass

```<code>var Arraydata:[Student] = []
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let arr = Arraydata[indexPath.row]
        if indexPath.row == arr
        {
          let story = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController")  as! SecondViewController

    UIView.beginAnimations("", context: nil)
    UIView.setAnimationDuration(1.0)
    UIView.setAnimationCurve(UIViewAnimationCurve.easeInOut)
    UIView.setAnimationTransition(UIViewAnimationTransition.flipFromRight, for: (self.navigationController?.view)!, cache: false)
    self.navigationController?.pushViewController(story, animated: true)
    UIView.commitAnimations()

        }
    }
</code>```

Body:
Have implemented collectionview it works fine but i want FlipAnimation while opening a new view controller from the cell and dismiss back to the cell. how to achieve the same.As i dont have any idea of Animation. Please Help.Thank you.
code

import UIKit

    class DashBoardVC: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
    {

    @IBOutlet weak var logoutbtn: UIButton!
    @IBOutlet weak var menubtn: UIButton!

    var names = ["Dashboard","Add Book","Delete Book","Search Book","On Demand","About Us"]

    var useimages = [UIImage(named:"dashboard_icon2"),UIImage(named:"book_blue_add"),UIImage(named:"book_blue_delete"),UIImage(named:"book_blue_view"),UIImage(named:"book_blue_new"),UIImage(named:"businesspeople2"),]

 override func viewDidLoad()
      {
             super.viewDidLoad()

        }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
         {
               return names.count
          }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
      {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellcollect", for: indexPath) as! mycollectioncell

        cell.collectLabel.text! = names[indexPath.row]
        cell.collectimage.image = useimages[indexPath.row]
        return cell
     }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
       {
        let padding : CGFloat =  15
        let collectionViewSize = collectionView.frame.size.width - padding
        return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)

         }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
        {

    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    switch(indexPath.row)
    {
    case 0:
    let desVC = storyboard.instantiateViewController(withIdentifier: "DashboardClick") as! DashboardClick
    self.navigationController?.pushViewController(desVC, animated: true)
        break
    case 1:
        let desVC = storyboard.instantiateViewController(withIdentifier: "AddBookVC") as! AddBookVC
        self.navigationController?.pushViewController(desVC, animated: true)
        break
    case 2:
        let desVC = storyboard.instantiateViewController(withIdentifier: "DeleteBookVC") as! DeleteBookVC
        self.navigationController?.pushViewController(desVC, animated: true)
        break

    case 3:
        let desVC = storyboard.instantiateViewController(withIdentifier: "SearchBookVC") as! SearchBookVC
        self.navigationController?.pushViewController(desVC, animated: true)
         break

    case 4:
        let desVC = storyboard.instantiateViewController(withIdentifier: "onDemandBookVC") as! onDemandBookVC
        self.navigationController?.pushViewController(desVC, animated: true)

        break
    default:
        break
    }

         }

override func viewWillAppear(_ animated: Bool)
 {
    self.navigationController?.navigationBar.isHidden = true
    self.navigationController?.toolbar.isHidden = true
  }

@IBAction func menutapped(_ sender: Any)
       {
    var appdelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

    appdelegate.centerContainer?.toggle(MMDrawerSide.left, animated: true, completion: nil)

           }
        }

mycollectioncell.swift

import UIKit

class mycollectioncell: UICollectionViewCell {

@IBOutlet weak var collectLabel: UILabel!

@IBOutlet weak var collectimage: UIImageView!

}

Body:
here Student is NSObjectClass

var Arraydata:[Student] = []
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let arr = Arraydata[indexPath.row]
        if indexPath.row == arr
        {
          let story = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController")  as! SecondViewController

    UIView.beginAnimations("", context: nil)
    UIView.setAnimationDuration(1.0)
    UIView.setAnimationCurve(UIViewAnimationCurve.easeInOut)
    UIView.setAnimationTransition(UIViewAnimationTransition.flipFromRight, for: (self.navigationController?.view)!, cache: false)
    self.navigationController?.pushViewController(story, animated: true)
    UIView.commitAnimations()

        }
    }


问:
Sass Color functions - include more than one
I have a HSL color that I need to, for example, adjust hue, saturation, and lightness all at once. And I've noticed if I do that one by one, as in

```<code>$color: hsl color code;

$new-color: adjust-hue($color, -1);
$new-color: lighten($color, 20%);
$new-color: desaturate($color, 10%);
</code>```

it doesn't actually apply them correctly. So my question is, how can I wrap this up in a function or a mixin (whatever is more appropriate in this situation) so it looks cleaner and behaves properly too? Thanks!

答:
First of all, in your current code, you're updating the variable $new-color on the $color variable at each step which is incorrect.

Now if you want to adjust hue, saturation, and lightness all at once, then adjust-color() (See documentation) is what you're looking for.

For example, following is equivalent to

```<code>$color: hsl(120,100%,50%);

$new-color: adjust-hue($color, -1);
$new-color: lighten($new-color, 20%);
$new-color: desaturate($new-color, 10%);
</code>```

this

```<code>$color: hsl(120,100%,50%);

$new-color: adjust-color($color, $hue: -1,$lightness: 20%, $saturation: -10%);
</code>```

Body:
I have a HSL color that I need to, for example, adjust hue, saturation, and lightness all at once. And I've noticed if I do that one by one, as in

$color: hsl color code;

$new-color: adjust-hue($color, -1);
$new-color: lighten($color, 20%);
$new-color: desaturate($color, 10%);

it doesn't actually apply them correctly. So my question is, how can I wrap this up in a function or a mixin (whatever is more appropriate in this situation) so it looks cleaner and behaves properly too? Thanks!

Body:
First of all, in your current code, you're updating the variable $new-color on the $color variable at each step which is incorrect.

Now if you want to adjust hue, saturation, and lightness all at once, then adjust-color() (See documentation) is what you're looking for.

For example, following is equivalent to

$color: hsl(120,100%,50%);

$new-color: adjust-hue($color, -1);
$new-color: lighten($new-color, 20%);
$new-color: desaturate($new-color, 10%);

this

$color: hsl(120,100%,50%);

$new-color: adjust-color($color, $hue: -1,$lightness: 20%, $saturation: -10%);


问:
What client tools are available to manage Amazon S3 and CloudFront?
I just started using the Amazon S3 and Amazon CloudFront. What proper client tools are out there that I can use to manage my account? Like uploading files etc. Yes I am a developer, but, I am pressed for time, I just want to deploy my apps.

I came across this one S3 Browser. It's almost what I am looking for.

EDIT ~ Is it possible to map a bucket as a windows Drive?

答: Cyberduck for Mac & Windows supports the full feature set of both S3 and Cloudfront distributions including custom origins. See http://trac.cyberduck.ch/wiki/help/en/howto/s3.</p>


问:
Excel: Different Cells with Duplicate Function
I have tried finding an answer to this question but I'm not sure how to even phrase it.

Say I have three cells A1, A2 and A3:

A1 has a data validation list contained within: X, Y, Z.

A3 is scripted to produce a VLOOKUP result depending on the letter selected.

I want A2 to mirror and provide an identical function to A1, but I also want both to be dependent on each other. For clarity, if I select 'X' on A1, A2 will also display 'X'. If I change 'X' to 'Y' on A2, A1 will then change to 'Y'. Either way, I want A3 to display the appropriate result whether or not the function is changed on A1 or A2.

Is this achievable? Or am I just messing with circular references?

答:
It is possible to connect two cells without VBA OR circular references, but it requires the use of form controls. Please reference this example for now.

Comboboxes

Comoboxes can be used as dropdown boxes (just like your data validation) but require two things: 1) an input range containing your list and 2) a linked cell. The linked cell returns an integer equal to the position of the selected value in your input range. Select X1 in your combobox and the the linked cell becomes 1, select Y1 and it becomes 2, etc.

To make your comboboxes, go to Developer in the Ribbon and select Insert > Combobox (form control). Put two boxes over cells A1 and B1, or wherever you want your lists to be. Right click each combobox and select "Format Control . . ." Choose your linked cell (you can put it under the combobox to easily hide it) and make an input range with your {X,Y,Z}. Make each combobox EXACTLY the same.

Now here's the important part: linked cells and their comboboxes are a two way street. Select Y1 in your combobox and the linked cell becomes 2; change your linked cell to 3 and the combobox becomes Z1. Therefore, when the first combobox changes the linked cell, the linked cell changes the second combobox. No circular reference, no VBA.

Formula for identical comboboxes

In cell C1 enter the formula

```<code>=VLOOKUP(INDEX($G$2:$G$4,$E$1),$J$2:$K$4,2,0)
</code>```

It's your standard VLOOKUP, but since your linked cell returns an integer we have to convert it back into a lookup value.

```<code>INDEX($G$2:$G$4,$E$1)
</code>```

INDEX uses the same list you used for you comboboxes and $E$E1 is the position in that list of the thing you selected. Therefore, it outputs what you selected in the combobox.

And voila! You're done.

But what if I want connected lists with separate values?

Please reference this example:

In this example, both connected comboboxes (same linked cell) have two separate lists: {X1,Y1,Z1} and {X2,Y2,Z2}. To accomplish this, simply have each combobox reference a different input range. The first box references $G2$G4 and the second $H2$H4. Again, when you change one combobox, the other will change: select X1 and the second combobox becomes X2, etc.

Formula for different comboboxes

Since the linked cell is the same for both comboboxes, your formula can't tell which list it should reference. You can use a simple data validation (or combobox!) list with {1,2} where 1 represents the first combobox and 2 the second. In this example its cell $A$4. Then you can use the formula:

```<code>=VLOOKUP(IF($A$4=1,INDEX($G$2:$G$4,$E$1),INDEX($H$2:$H$4,$E$1)),$J$2:$K$7,2,0)
</code>```

It's the same formula we used for identical comboboxes, but this time we're choosing which list to get our lookup value from based on which combobox is selected in cell $A$4. If you wanted your VLOOKUP to have different table arrays, a simple two VLOOKUP formula:

```<code>=IF($A$4=1, VLOOKUP(INDEX($G$2:$G$4,$E$1),MyRange1,2,0),VLOOKUP(INDEX($H$2:$H$4,$E$1),MyRange2,2,0)
</code>```

will suffice.

You can also use list boxes or ActiveX comboboxes instead of Form control comboboxes. The former will give you an actual list but it takes up space and you don't get that similar effect to data validation drop-down boxes. ActiveX controls are simply too complicated and resource heavy for what we're trying to do here.

I noticed too late that I used different ranges in your example, but simply move the comboboxes and change the formulas to wherever you'd like.

Body:
It is possible to connect two cells without VBA OR circular references, but it requires the use of form controls. Please reference this example for now.

Comboboxes

Comoboxes can be used as dropdown boxes (just like your data validation) but require two things: 1) an input range containing your list and 2) a linked cell. The linked cell returns an integer equal to the position of the selected value in your input range. Select X1 in your combobox and the the linked cell becomes 1, select Y1 and it becomes 2, etc.

To make your comboboxes, go to Developer in the Ribbon and select Insert > Combobox (form control). Put two boxes over cells A1 and B1, or wherever you want your lists to be. Right click each combobox and select "Format Control . . ." Choose your linked cell (you can put it under the combobox to easily hide it) and make an input range with your {X,Y,Z}. Make each combobox EXACTLY the same.

Now here's the important part: linked cells and their comboboxes are a two way street. Select Y1 in your combobox and the linked cell becomes 2; change your linked cell to 3 and the combobox becomes Z1. Therefore, when the first combobox changes the linked cell, the linked cell changes the second combobox. No circular reference, no VBA.

Formula for identical comboboxes

In cell C1 enter the formula

=VLOOKUP(INDEX($G$2:$G$4,$E$1),$J$2:$K$4,2,0)

It's your standard VLOOKUP, but since your linked cell returns an integer we have to convert it back into a lookup value.

INDEX($G$2:$G$4,$E$1)

INDEX uses the same list you used for you comboboxes and $E$E1 is the position in that list of the thing you selected. Therefore, it outputs what you selected in the combobox.

And voila! You're done.

But what if I want connected lists with separate values?

Please reference this example:

In this example, both connected comboboxes (same linked cell) have two separate lists: {X1,Y1,Z1} and {X2,Y2,Z2}. To accomplish this, simply have each combobox reference a different input range. The first box references $G2$G4 and the second $H2$H4. Again, when you change one combobox, the other will change: select X1 and the second combobox becomes X2, etc.

Formula for different comboboxes

Since the linked cell is the same for both comboboxes, your formula can't tell which list it should reference. You can use a simple data validation (or combobox!) list with {1,2} where 1 represents the first combobox and 2 the second. In this example its cell $A$4. Then you can use the formula:

=VLOOKUP(IF($A$4=1,INDEX($G$2:$G$4,$E$1),INDEX($H$2:$H$4,$E$1)),$J$2:$K$7,2,0)

It's the same formula we used for identical comboboxes, but this time we're choosing which list to get our lookup value from based on which combobox is selected in cell $A$4. If you wanted your VLOOKUP to have different table arrays, a simple two VLOOKUP formula:

=IF($A$4=1, VLOOKUP(INDEX($G$2:$G$4,$E$1),MyRange1,2,0),VLOOKUP(INDEX($H$2:$H$4,$E$1),MyRange2,2,0)

will suffice.

You can also use list boxes or ActiveX comboboxes instead of Form control comboboxes. The former will give you an actual list but it takes up space and you don't get that similar effect to data validation drop-down boxes. ActiveX controls are simply too complicated and resource heavy for what we're trying to do here.

I noticed too late that I used different ranges in your example, but simply move the comboboxes and change the formulas to wherever you'd like.


问:
Is `make(chan _, _)` atomic?
Is it thread-safe to modify the channel that a consumer is reading from?

Consider the following code:

```<code>func main(){
    channel     := make(chan int, 3)
    channel_ptr := &channel

    go supplier (channel_ptr)
    go consumer (channel_ptr)

    temp = *channel_ptr
    // Important bit
    *channel_ptr = make(chan int, 5)

    more := true
    for more{
        select {
            case msg := <-temp:
                *channel_ptr <- msg
            default:
                more = false
        }
    }
    // Block main indefinitely to keep the children alive
    <-make(chan bool)
}

func consumer(c *chan int){
    for true{
        fmt.Println(<-(*c))
    }
}

func supplier(c *chan int){
    for i :=0; i < 5; i ++{
        (*c)<-i
    }
}
</code>```

If channels and make work the way that I want them to, I should get the following properties:

The program always outputs 0 1 2 3 4

The program will never panic from trying to read from a non-initialized channel (IE, the part I labelled Important bit is atomic)

From several test runs, this seems to be true, but I can't find it anywhere in the documentation and I'm worried about subtle race conditions.

Update

Yeah, what I was doing doesn't work. This thread is probably buried at this point, but does anybody know how to dynamically resize a buffered channel?

答:
It's not thread safe.

If you run with -race flag to use race detector, you'll see the bug:

```<code>$ run -race t.go
==================
WARNING: DATA RACE
Write at 0x00c420086018 by main goroutine:
  main.main()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:14 +0x128

Previous read at 0x00c420086018 by goroutine 6:
  main.supplier()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:37 +0x51

Goroutine 6 (running) created at:
  main.main()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:9 +0xb4
0
==================
1
2
3
==================
WARNING: DATA RACE
Read at 0x00c420086018 by goroutine 6:
  main.supplier()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:37 +0x51

Previous write at 0x00c420086018 by main goroutine:
  main.main()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:14 +0x128

Goroutine 6 (running) created at:
  main.main()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:9 +0xb4
==================
4
</code>```

As a rule of thumb, you should never pass channel as a pointer. Channel already is a pointer internally.

Stepping back a bit: I don't understand what you're trying to achieve.

I guess there's a reason you're trying to pass a channel as a pointer. The pattern of using channels in Go is: you create it once and you pass it around as value. You don't pass a pointer to it and you never modify it after creation.

In your example the problem is that you have a shared piece of memory (memory address pointed to by channel_ptr) and you write to that memory in one thread while some other thread reads it. That's data race.

It's not specific to a channel, you would have the same issue if it was pointer to an int and two threads were modifying the value of an int.

Title: Is `make(chan _, _)` atomic?

Body:
Is it thread-safe to modify the channel that a consumer is reading from?

Consider the following code:

func main(){
    channel     := make(chan int, 3)
    channel_ptr := &channel

    go supplier (channel_ptr)
    go consumer (channel_ptr)

    temp = *channel_ptr
    // Important bit
    *channel_ptr = make(chan int, 5)

    more := true
    for more{
        select {
            case msg := <-temp:
                *channel_ptr <- msg
            default:
                more = false
        }
    }
    // Block main indefinitely to keep the children alive
    <-make(chan bool)
}

func consumer(c *chan int){
    for true{
        fmt.Println(<-(*c))
    }
}

func supplier(c *chan int){
    for i :=0; i < 5; i ++{
        (*c)<-i
    }
}

If channels and make work the way that I want them to, I should get the following properties:

The program always outputs 0 1 2 3 4

The program will never panic from trying to read from a non-initialized channel (IE, the part I labelled Important bit is atomic)

From several test runs, this seems to be true, but I can't find it anywhere in the documentation and I'm worried about subtle race conditions.

Update

Yeah, what I was doing doesn't work. This thread is probably buried at this point, but does anybody know how to dynamically resize a buffered channel?

Body:
It's not thread safe.

If you run with -race flag to use race detector, you'll see the bug:

$ run -race t.go
==================
WARNING: DATA RACE
Write at 0x00c420086018 by main goroutine:
  main.main()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:14 +0x128

Previous read at 0x00c420086018 by goroutine 6:
  main.supplier()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:37 +0x51

Goroutine 6 (running) created at:
  main.main()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:9 +0xb4
0
==================
1
2
3
==================
WARNING: DATA RACE
Read at 0x00c420086018 by goroutine 6:
  main.supplier()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:37 +0x51

Previous write at 0x00c420086018 by main goroutine:
  main.main()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:14 +0x128

Goroutine 6 (running) created at:
  main.main()
      /Users/kjk/src/go/src/github.com/kjk/go-cookbook/start-mysql-in-docker-go/t.go:9 +0xb4
==================
4

As a rule of thumb, you should never pass channel as a pointer. Channel already is a pointer internally.

Stepping back a bit: I don't understand what you're trying to achieve.

I guess there's a reason you're trying to pass a channel as a pointer. The pattern of using channels in Go is: you create it once and you pass it around as value. You don't pass a pointer to it and you never modify it after creation.

In your example the problem is that you have a shared piece of memory (memory address pointed to by channel_ptr) and you write to that memory in one thread while some other thread reads it. That's data race.

It's not specific to a channel, you would have the same issue if it was pointer to an int and two threads were modifying the value of an int.


问:
C: WAV file not being opened in "rb"
I'm having a difficult time trying to open a WAV file for reading. When I compile and run my code, I do not get any errors. I am adding the code that I am messing with (assuming necessary libraries have been called). The program is supposed to display the contents of the WAV file and although I enter a valid filename and extension, the statement "Invalid Filename. Try Again." is still being printed to the screen. The other method I attempted was enter the directory of the file instead of just the name, and when I do that, my program ends and nothing is displayed. Any guidance would be helpful and thank you in advance!</p>

```<code>main(){
FILE *fin;
printf("\nEnter filename of WAV file: \n");
char filename[256];
scanf("%s",&filename);
fin = fopen(filename,"rb"); // opens in rb

if(!fin) // if file doesn't exist
{
printf("Invalid filename. Try again.\n");
}
else // if fin opens succesfully
{
    printf("\nFile opened succesfully\n");

    char *header;
    header = (char *)malloc(44);
    if(header == NULL)
    {
        printf("Error in allocating memory.");
        return 0;
    }

    fread(header,1,44,fin);

    char *chunkid;
    unsigned int *chunksize;
    char *format;
    char *subchunk1id;
    unsigned int *subchunk1size;
    unsigned short int *audioformat;
    unsigned short int *numchannels;
    unsigned int *samplerate;
    unsigned int *byterate;
    unsigned short int *blockalign;
    unsigned short int *bitspersample;
    char *subchunk2id;
    unsigned int *subchunk2size;
    unsigned int *data;

    chunkid = header;
    chunksize = (unsigned int *)(header + 4);
    format = header + 8;
    subchunk1id = header + 12;
    subchunk1size = (unsigned int *)(header + 16);
    audioformat = (unsigned short int *)(header + 18);
    numchannels = (unsigned short int*)(header + 20);
    samplerate = (unsigned int*)(header + 24);
    byterate = (unsigned int*)(header + 28);
    blockalign = (unsigned short int*)(header + 30);
    bitspersample = (unsigned short int*)(header + 32);
    subchunk2id = header + 36;
    subchunk2size = (unsigned int*)(header + 40);
    data = (unsigned int*)(header + 44);

    printf("\n%c%c%c%c",*(header),*(header+1),*(header+2),*(header+3));
    printf("\n%d",*chunksize);
    printf("\n%c%c%c%c",*(header + 8),*(header + 9), *(header + 10), *(header + 11));
    printf("\n%c%c%c%c",*(header + 12),*(header + 13), *(header + 14), *(header + 15));
    printf("\n%d",*subchunk1size);
    printf("\n%d",*audioformat);
    printf("\n%d",*numchannels);
    printf("\n%d",*samplerate);
    printf("\n%d",*byterate);
    printf("\n%d",*blockalign);
    printf("\n%d",*bitspersample);
    printf("\n%c%c%c%c",*(header + 36),*(header + 37),*(header + 38), *(header + 39));
    printf("\n%d",*subchunk2size);
    printf("\n%d",*data);

    fclose(fin);

} // end of else
} // end of main
</code>```

答:
Using warnings while compiling the code would have revealed your mistake.

Proposal for improvement, describe the header as a struct like:

```<code>typedef struct
{
    char    riff_tag[4];
    int32_t riff_length;
    char    wave_tag[4];
    char    fmt_tag[4];
    int32_t fmt_length;
    int16_t audio_format;
    int16_t num_channels;
    int32_t sample_rate;
    int32_t byte_rate;
    int16_t block_align;
    int16_t bits_per_sample;
    char    data_tag[4];
    int32_t data_length;
}waveFileHeader, *waveFileHeaderptr ;
</code>```

and read it like:

```<code>waveFileHeaderptr header =malloc ( sizeof (waveFileHeader));
fread (header , sizeof (waveFileHeader), 1 , fin);
</code>```

will make the following code and handeling less messy

Title: C: WAV file not being opened in "rb"

Body:
I'm having a difficult time trying to open a WAV file for reading. When I compile and run my code, I do not get any errors. I am adding the code that I am messing with (assuming necessary libraries have been called). The program is supposed to display the contents of the WAV file and although I enter a valid filename and extension, the statement "Invalid Filename. Try Again." is still being printed to the screen. The other method I attempted was enter the directory of the file instead of just the name, and when I do that, my program ends and nothing is displayed. Any guidance would be helpful and thank you in advance!

main(){
FILE *fin;
printf("\nEnter filename of WAV file: \n");
char filename[256];
scanf("%s",&filename);
fin = fopen(filename,"rb"); // opens in rb

if(!fin) // if file doesn't exist
{
printf("Invalid filename. Try again.\n");
}
else // if fin opens succesfully
{
    printf("\nFile opened succesfully\n");

    char *header;
    header = (char *)malloc(44);
    if(header == NULL)
    {
        printf("Error in allocating memory.");
        return 0;
    }

    fread(header,1,44,fin);

    char *chunkid;
    unsigned int *chunksize;
    char *format;
    char *subchunk1id;
    unsigned int *subchunk1size;
    unsigned short int *audioformat;
    unsigned short int *numchannels;
    unsigned int *samplerate;
    unsigned int *byterate;
    unsigned short int *blockalign;
    unsigned short int *bitspersample;
    char *subchunk2id;
    unsigned int *subchunk2size;
    unsigned int *data;

    chunkid = header;
    chunksize = (unsigned int *)(header + 4);
    format = header + 8;
    subchunk1id = header + 12;
    subchunk1size = (unsigned int *)(header + 16);
    audioformat = (unsigned short int *)(header + 18);
    numchannels = (unsigned short int*)(header + 20);
    samplerate = (unsigned int*)(header + 24);
    byterate = (unsigned int*)(header + 28);
    blockalign = (unsigned short int*)(header + 30);
    bitspersample = (unsigned short int*)(header + 32);
    subchunk2id = header + 36;
    subchunk2size = (unsigned int*)(header + 40);
    data = (unsigned int*)(header + 44);

    printf("\n%c%c%c%c",*(header),*(header+1),*(header+2),*(header+3));
    printf("\n%d",*chunksize);
    printf("\n%c%c%c%c",*(header + 8),*(header + 9), *(header + 10), *(header + 11));
    printf("\n%c%c%c%c",*(header + 12),*(header + 13), *(header + 14), *(header + 15));
    printf("\n%d",*subchunk1size);
    printf("\n%d",*audioformat);
    printf("\n%d",*numchannels);
    printf("\n%d",*samplerate);
    printf("\n%d",*byterate);
    printf("\n%d",*blockalign);
    printf("\n%d",*bitspersample);
    printf("\n%c%c%c%c",*(header + 36),*(header + 37),*(header + 38), *(header + 39));
    printf("\n%d",*subchunk2size);
    printf("\n%d",*data);

    fclose(fin);

} // end of else
} // end of main

Body:
Using warnings while compiling the code would have revealed your mistake.

Proposal for improvement, describe the header as a struct like:

typedef struct
{
    char    riff_tag[4];
    int32_t riff_length;
    char    wave_tag[4];
    char    fmt_tag[4];
    int32_t fmt_length;
    int16_t audio_format;
    int16_t num_channels;
    int32_t sample_rate;
    int32_t byte_rate;
    int16_t block_align;
    int16_t bits_per_sample;
    char    data_tag[4];
    int32_t data_length;
}waveFileHeader, *waveFileHeaderptr ;

and read it like:

waveFileHeaderptr header =malloc ( sizeof (waveFileHeader));
fread (header , sizeof (waveFileHeader), 1 , fin);

will make the following code and handeling less messy


问:
Not implemented exception was unhandled by user code
Everytime I try to print the error shows up.
it says "Not implemented exception was unhandled by user code".
how to fix this sh!t?
here's my code

```<code>namespace RunwayMedlinc
{
public partial class patient : Form
{
    Print print;
    MySqlConnection con;
    String sql;
    MySqlCommand cmd;
    MySqlDataAdapter data, data2, data3;
    DataTable table = new DataTable();
    DataTable table2 = new DataTable();
    DataTable table3 = new DataTable();
    DataSet da = new DataSet();
    int age;

    public patient()
    {
        InitializeComponent();
    }

    public void view()
    {
    try
        {
            sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year.Text + "%' and admit like'%" + month.Text + "%'";
            cmd = new MySqlCommand(sql, con);
            data.SelectCommand = cmd;
            pview.DataSource = table;
            table.Clear();
            data.Fill(table);
            pview.DataSource = table;
        }
        catch (Exception exx)
        {
            MessageBox.Show(exx.Message, "Error");
        }
    }

    public void bew()
    {
        try
        {
            sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year2.Text + "%' and admit like'%" + month2.Text + "%'";
            cmd = new MySqlCommand(sql, con);
            data2.SelectCommand = cmd;
            pview2.DataSource = table2;
            table2.Clear();
            data2.Fill(table2);
        }
        catch (Exception exx)
        {
            MessageBox.Show(exx.Message, "Error");
        }
    }

    private void search_Enter(object sender, EventArgs e)
    {
        if (search.ForeColor == Color.Gray)
        {
            search.Clear();
            search.ForeColor = Color.Black;
        }
    }

    private void search_Leave(object sender, EventArgs e)
    {
        if (search.Text == "")
        {
            search.ForeColor = Color.Gray;
            search.Text = "SEARCH PATIENT...";
        }
    }

    private void search2_Enter(object sender, EventArgs e)
    {
        if (search2.ForeColor == Color.Gray)
        {
            search2.Clear();
            search2.ForeColor = Color.Black;
        }
    }

    private void search2_Leave(object sender, EventArgs e)
    {
        if (search2.Text == "")
        {
            search2.ForeColor = Color.Gray;
            search2.Text = "SEARCH PATIENT...";
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        time.Text = DateTime.Now.ToString("h:mm:ss tt");
        date.Text = DateTime.Now.ToString("MMMM d, yyyy");
    }

    private void patient_Load(object sender, EventArgs e)
    {
        con = new MySqlConnection();
        con.ConnectionString = "server=Localhost;" + "username=root;" + "password=;" + "database=runway";
        con.Open();
        sql = "select mrn from p";
        cmd = new MySqlCommand(sql, con);
        data = new MySqlDataAdapter();
        data2 = new MySqlDataAdapter();

        month.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        view();

        bew();
    }

    private void clear_Click(object sender, EventArgs e)
    {
        mrn.Clear();
        name.Clear();
        phy.Clear();
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;

        add.Enabled = true;
        mrn.ReadOnly = false;
        name.ReadOnly = false;
        phy.ReadOnly = false;
        m.Enabled = true;
        f.Enabled = true;
        bdate.Enabled = true;
        admit.Enabled = true;
    }

    private void phy_Enter(object sender, EventArgs e)
    {
        if (phy.ReadOnly == false)
        {
            phy.Clear();
        }
    }

    private void add_Click(object sender, EventArgs e)
    {
        if (mrn.Text == "" || name.Text == "" || (m.Checked == false && f.Checked == false))
        {
            MessageBox.Show("Please fill out all information.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        else
        {
                DateTime x = admit.Value;
                DateTime y = bdate.Value;
                if (x.Month < y.Month || (x.Month == y.Month && x.Day < y.Day))
                {
                    age = x.Year - y.Year - 1;
                }
                else
                {
                    age = x.Year - y.Year;
                }

                if (m.Checked == true)
                {
                    if (name.ReadOnly == false)
                    {
                        sql = "insert into pp(mrn, name, gender, bday)values (?a, ?b, ?c, ?d)";
                        cmd = new MySqlCommand(sql, con);

                        cmd.Parameters.AddWithValue("?a", mrn.Text);
                        cmd.Parameters.AddWithValue("?b", name.Text);
                        cmd.Parameters.AddWithValue("?c", m.Text);
                        cmd.Parameters.AddWithValue("?d", bdate.Text);
                        cmd.ExecuteNonQuery();
                    }
                }

                if (f.Checked == true)
                {
                    if (name.ReadOnly == false)
                    {
                        sql = "insert into pp(mrn, name, gender, bday)values (?a, ?b, ?c, ?d)";
                        cmd = new MySqlCommand(sql, con);

                        cmd.Parameters.AddWithValue("?a", mrn.Text);
                        cmd.Parameters.AddWithValue("?b", name.Text);
                        cmd.Parameters.AddWithValue("?c", f.Text);
                        cmd.Parameters.AddWithValue("?d", bdate.Text);
                        cmd.ExecuteNonQuery();
                    }
                }

                sql = "insert into p(mrn, admit, discharge, md, age)values (?a, ?e, ?f, ?g, ?z)";
                cmd = new MySqlCommand(sql, con);

                cmd.Parameters.AddWithValue("?a", mrn.Text);
                cmd.Parameters.AddWithValue("?e", admit.Text);
                cmd.Parameters.AddWithValue("?f", null);
                cmd.Parameters.AddWithValue("?g", phy.Text);
                cmd.Parameters.AddWithValue("?z", age);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Patient Successfully Added!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                mrn.Clear();
                name.Clear();
                phy.Text = "MANGASEP, CONCEPCION R.";
                m.Checked = false;
                f.Checked = false;
                bdate.Value = DateTime.Now;
                admit.Value = DateTime.Now;
                disch.Value = DateTime.Now;

                month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
                year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
                bew();

        }
    }

    private void search_TextChanged(object sender, EventArgs e)
    {
        if (search.ForeColor != Color.Gray)
        {
            try
            {
                sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year.Text + "%' and admit like'%" + month.Text + "%' and name like'%" + search.Text + "%'";
                cmd = new MySqlCommand(sql, con);
                data.SelectCommand = cmd;
                pview.DataSource = table;
                table.Clear();
                data.Fill(table);
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message, "Error");
            }
        }
    }

    private void search2_TextChanged(object sender, EventArgs e)
    {
        if (search2.ForeColor != Color.Gray)
        {
            try
            {
                sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year2.Text + "%' and admit like'%" + month2.Text + "%' and name like'%" + search2.Text + "%'";
                cmd = new MySqlCommand(sql, con);
                data2.SelectCommand = cmd;
                pview2.DataSource = table2;
                table2.Clear();
                data2.Fill(table2);
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message, "Error");
            }
        }
    }

    private void pview2_Click(object sender, EventArgs e)
    {
        mrn.Text = pview2.SelectedRows[0].Cells[0].Value.ToString();
        name.Text = pview2.SelectedRows[0].Cells[1].Value.ToString();
        if (pview2.SelectedRows[0].Cells[4].Value.ToString() == "MALE")
        {
            m.Checked = true;
        }
        else
        {
            f.Checked = true;
        }
        bdate.Text = pview2.SelectedRows[0].Cells[2].Value.ToString();
        admit.Text = pview2.SelectedRows[0].Cells[5].Value.ToString();
        phy.Text = pview2.SelectedRows[0].Cells[7].Value.ToString();

        add.Enabled = false;
        mrn.ReadOnly = true;
        name.ReadOnly = true;
        phy.ReadOnly = true;
        m.Enabled = false;
        f.Enabled = false;
        bdate.Enabled = false;
        admit.Enabled = false;
    }

    private void update_Click(object sender, EventArgs e)
    {
        sql = "Update p set discharge= '" + disch.Text + "' where mrn = '" + mrn.Text + "'";
        cmd = new MySqlCommand(sql, con);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Patient Successfuly Updated!");

        add.Enabled = true;
        mrn.Clear();
        mrn.ReadOnly = false;
        name.Clear();
        name.ReadOnly = false;
        phy.Text = "MANGASEP, CONCEPCION R.";
        phy.ReadOnly = false;
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
        bew();
    }

    private void mrn_TextChanged(object sender, EventArgs e)
    {
        sql = "Select name, gender, bday from pp where mrn = '" + mrn.Text + "'";
        cmd = new MySqlCommand(sql, con);
        data3 = new MySqlDataAdapter();
        data3.SelectCommand = cmd;
        table3 = new DataTable();
        data3.Fill(table3);

        if (table3.Rows.Count > 0)
        {
            name.Text = Convert.ToString(table3.Rows[0][0]);
            if (Convert.ToString(table3.Rows[0][1]) == "MALE")
            {
                m.Checked = true; ;
            }
            else
            {
                f.Checked = true;
            }
            bdate.Value = Convert.ToDateTime(table3.Rows[0][2]);
            name.ReadOnly = true;
            m.Enabled = false;
            f.Enabled = false;
            bdate.Enabled = false;

        }
        else
        {
            name.Clear();
            m.Checked = false;
            f.Checked = false;
            bdate.Value = DateTime.Now;
            name.ReadOnly = false;
            m.Enabled = true;
            f.Enabled = true;
            bdate.Enabled = true;
        }
    }

    private void year_SelectedIndexChanged(object sender, EventArgs e)
    {
        view();
    }

    private void month_SelectedIndexChanged(object sender, EventArgs e)
    {
        view();
    }

    private void mrn_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != '.'))
        {
            e.Handled = true;
        }

        if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
        {
            e.Handled = true;
        }
    }

    private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        month.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
        search.ForeColor = Color.Gray;
        search.Text = "SEARCH PATIENT...";
        search2.ForeColor = Color.Gray;
        search2.Text = "SEARCH PATIENT...";
        mrn.Clear();
        name.Clear();
        phy.Text = "MANGASEP, CONCEPCION R.";
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;
    }

    private void month2_SelectedIndexChanged(object sender, EventArgs e)
    {
        bew();
    }

    private void year2_SelectedIndexChanged(object sender, EventArgs e)
    {
        bew();
    }

    private bool SetupThePrinting()
     {
         PrintDialog MyPrintDialog = new PrintDialog();
         MyPrintDialog.AllowCurrentPage = false;
         MyPrintDialog.AllowPrintToFile = false;
         MyPrintDialog.AllowSelection = false;
         MyPrintDialog.AllowSomePages = false;
         MyPrintDialog.PrintToFile = false;
         MyPrintDialog.ShowHelp = false;
         MyPrintDialog.ShowNetwork = false;
         if (MyPrintDialog.ShowDialog() != DialogResult.OK)
         return false;
         dokumento.DocumentName = "List of Patients";
         dokumento.PrinterSettings = MyPrintDialog.PrinterSettings;
         dokumento.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
         dokumento.DefaultPageSettings.Landscape = false;
         dokumento.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(10, 10, 10, 10);
         dokumento.DefaultPageSettings.Landscape = MyPrintDialog.PrinterSettings.DefaultPageSettings.Landscape;
         print = new Print(pview, dokumento, true, true, Environment.NewLine + "" + Environment.NewLine + "" + "Runway Medlinc"  + Environment.NewLine + "" + Environment.NewLine + "List of Patients"
         + Environment.NewLine + "" + Environment.NewLine + month.Text + "  " + year.Text, new Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
         return true;
     }

    private void printer_Click(object sender, EventArgs e)
       {
           if (SetupThePrinting())
           {
               PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
               MyPrintPreviewDialog.Document = dokumento;
               MyPrintPreviewDialog.ShowDialog();
               dokumento.Print();
           }
       }

    private void dokumento_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
      {
          bool more = print.DrawDataGridView(e.Graphics);
          if (more == true)
          e.HasMorePages = true;
     }

}
}
</code>```

Everytime I try to print the error shows up.
it says "Not implemented exception was unhandled by user code".
how to fix this sh!t?
and the other class is here

```<code>namespace RunwayMedlinc
{
class Print
{
    private System.Windows.Forms.DataGridView pview;
    private System.Drawing.Printing.PrintDocument dokumento;
    private bool p;
    private bool p_2;
    private string p_3;
    private System.Drawing.Font font;
    private System.Drawing.Color color;
    private bool p_4;

    public Print(System.Windows.Forms.DataGridView pview, System.Drawing.Printing.PrintDocument dokumento, bool p, bool p_2, string p_3, System.Drawing.Font font, System.Drawing.Color color, bool p_4)
    {
        this.pview = pview;
        this.dokumento = dokumento;
        this.p = p;
        this.p_2 = p_2;
        this.p_3 = p_3;
        this.font = font;
        this.color = color;
        this.p_4 = p_4;
    }

    internal bool DrawDataGridView(System.Drawing.Graphics graphics)
    {
        throw new NotImplementedException();
    }
}
}
</code>```

答: You must implement DrawDataGridView method in Print class.

Body:
Everytime I try to print the error shows up.
it says "Not implemented exception was unhandled by user code".
how to fix this sh!t?
here's my code

namespace RunwayMedlinc
{
public partial class patient : Form
{
    Print print;
    MySqlConnection con;
    String sql;
    MySqlCommand cmd;
    MySqlDataAdapter data, data2, data3;
    DataTable table = new DataTable();
    DataTable table2 = new DataTable();
    DataTable table3 = new DataTable();
    DataSet da = new DataSet();
    int age;

    public patient()
    {
        InitializeComponent();
    }

    public void view()
    {
    try
        {
            sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year.Text + "%' and admit like'%" + month.Text + "%'";
            cmd = new MySqlCommand(sql, con);
            data.SelectCommand = cmd;
            pview.DataSource = table;
            table.Clear();
            data.Fill(table);
            pview.DataSource = table;
        }
        catch (Exception exx)
        {
            MessageBox.Show(exx.Message, "Error");
        }
    }

    public void bew()
    {
        try
        {
            sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year2.Text + "%' and admit like'%" + month2.Text + "%'";
            cmd = new MySqlCommand(sql, con);
            data2.SelectCommand = cmd;
            pview2.DataSource = table2;
            table2.Clear();
            data2.Fill(table2);
        }
        catch (Exception exx)
        {
            MessageBox.Show(exx.Message, "Error");
        }
    }

    private void search_Enter(object sender, EventArgs e)
    {
        if (search.ForeColor == Color.Gray)
        {
            search.Clear();
            search.ForeColor = Color.Black;
        }
    }

    private void search_Leave(object sender, EventArgs e)
    {
        if (search.Text == "")
        {
            search.ForeColor = Color.Gray;
            search.Text = "SEARCH PATIENT...";
        }
    }

    private void search2_Enter(object sender, EventArgs e)
    {
        if (search2.ForeColor == Color.Gray)
        {
            search2.Clear();
            search2.ForeColor = Color.Black;
        }
    }

    private void search2_Leave(object sender, EventArgs e)
    {
        if (search2.Text == "")
        {
            search2.ForeColor = Color.Gray;
            search2.Text = "SEARCH PATIENT...";
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        time.Text = DateTime.Now.ToString("h:mm:ss tt");
        date.Text = DateTime.Now.ToString("MMMM d, yyyy");
    }

    private void patient_Load(object sender, EventArgs e)
    {
        con = new MySqlConnection();
        con.ConnectionString = "server=Localhost;" + "username=root;" + "password=;" + "database=runway";
        con.Open();
        sql = "select mrn from p";
        cmd = new MySqlCommand(sql, con);
        data = new MySqlDataAdapter();
        data2 = new MySqlDataAdapter();

        month.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        view();

        bew();
    }

    private void clear_Click(object sender, EventArgs e)
    {
        mrn.Clear();
        name.Clear();
        phy.Clear();
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;

        add.Enabled = true;
        mrn.ReadOnly = false;
        name.ReadOnly = false;
        phy.ReadOnly = false;
        m.Enabled = true;
        f.Enabled = true;
        bdate.Enabled = true;
        admit.Enabled = true;
    }

    private void phy_Enter(object sender, EventArgs e)
    {
        if (phy.ReadOnly == false)
        {
            phy.Clear();
        }
    }

    private void add_Click(object sender, EventArgs e)
    {
        if (mrn.Text == "" || name.Text == "" || (m.Checked == false && f.Checked == false))
        {
            MessageBox.Show("Please fill out all information.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        else
        {
                DateTime x = admit.Value;
                DateTime y = bdate.Value;
                if (x.Month < y.Month || (x.Month == y.Month && x.Day < y.Day))
                {
                    age = x.Year - y.Year - 1;
                }
                else
                {
                    age = x.Year - y.Year;
                }

                if (m.Checked == true)
                {
                    if (name.ReadOnly == false)
                    {
                        sql = "insert into pp(mrn, name, gender, bday)values (?a, ?b, ?c, ?d)";
                        cmd = new MySqlCommand(sql, con);

                        cmd.Parameters.AddWithValue("?a", mrn.Text);
                        cmd.Parameters.AddWithValue("?b", name.Text);
                        cmd.Parameters.AddWithValue("?c", m.Text);
                        cmd.Parameters.AddWithValue("?d", bdate.Text);
                        cmd.ExecuteNonQuery();
                    }
                }

                if (f.Checked == true)
                {
                    if (name.ReadOnly == false)
                    {
                        sql = "insert into pp(mrn, name, gender, bday)values (?a, ?b, ?c, ?d)";
                        cmd = new MySqlCommand(sql, con);

                        cmd.Parameters.AddWithValue("?a", mrn.Text);
                        cmd.Parameters.AddWithValue("?b", name.Text);
                        cmd.Parameters.AddWithValue("?c", f.Text);
                        cmd.Parameters.AddWithValue("?d", bdate.Text);
                        cmd.ExecuteNonQuery();
                    }
                }

                sql = "insert into p(mrn, admit, discharge, md, age)values (?a, ?e, ?f, ?g, ?z)";
                cmd = new MySqlCommand(sql, con);

                cmd.Parameters.AddWithValue("?a", mrn.Text);
                cmd.Parameters.AddWithValue("?e", admit.Text);
                cmd.Parameters.AddWithValue("?f", null);
                cmd.Parameters.AddWithValue("?g", phy.Text);
                cmd.Parameters.AddWithValue("?z", age);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Patient Successfully Added!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                mrn.Clear();
                name.Clear();
                phy.Text = "MANGASEP, CONCEPCION R.";
                m.Checked = false;
                f.Checked = false;
                bdate.Value = DateTime.Now;
                admit.Value = DateTime.Now;
                disch.Value = DateTime.Now;

                month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
                year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
                bew();

        }
    }

    private void search_TextChanged(object sender, EventArgs e)
    {
        if (search.ForeColor != Color.Gray)
        {
            try
            {
                sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year.Text + "%' and admit like'%" + month.Text + "%' and name like'%" + search.Text + "%'";
                cmd = new MySqlCommand(sql, con);
                data.SelectCommand = cmd;
                pview.DataSource = table;
                table.Clear();
                data.Fill(table);
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message, "Error");
            }
        }
    }

    private void search2_TextChanged(object sender, EventArgs e)
    {
        if (search2.ForeColor != Color.Gray)
        {
            try
            {
                sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year2.Text + "%' and admit like'%" + month2.Text + "%' and name like'%" + search2.Text + "%'";
                cmd = new MySqlCommand(sql, con);
                data2.SelectCommand = cmd;
                pview2.DataSource = table2;
                table2.Clear();
                data2.Fill(table2);
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message, "Error");
            }
        }
    }

    private void pview2_Click(object sender, EventArgs e)
    {
        mrn.Text = pview2.SelectedRows[0].Cells[0].Value.ToString();
        name.Text = pview2.SelectedRows[0].Cells[1].Value.ToString();
        if (pview2.SelectedRows[0].Cells[4].Value.ToString() == "MALE")
        {
            m.Checked = true;
        }
        else
        {
            f.Checked = true;
        }
        bdate.Text = pview2.SelectedRows[0].Cells[2].Value.ToString();
        admit.Text = pview2.SelectedRows[0].Cells[5].Value.ToString();
        phy.Text = pview2.SelectedRows[0].Cells[7].Value.ToString();

        add.Enabled = false;
        mrn.ReadOnly = true;
        name.ReadOnly = true;
        phy.ReadOnly = true;
        m.Enabled = false;
        f.Enabled = false;
        bdate.Enabled = false;
        admit.Enabled = false;
    }

    private void update_Click(object sender, EventArgs e)
    {
        sql = "Update p set discharge= '" + disch.Text + "' where mrn = '" + mrn.Text + "'";
        cmd = new MySqlCommand(sql, con);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Patient Successfuly Updated!");

        add.Enabled = true;
        mrn.Clear();
        mrn.ReadOnly = false;
        name.Clear();
        name.ReadOnly = false;
        phy.Text = "MANGASEP, CONCEPCION R.";
        phy.ReadOnly = false;
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
        bew();
    }

    private void mrn_TextChanged(object sender, EventArgs e)
    {
        sql = "Select name, gender, bday from pp where mrn = '" + mrn.Text + "'";
        cmd = new MySqlCommand(sql, con);
        data3 = new MySqlDataAdapter();
        data3.SelectCommand = cmd;
        table3 = new DataTable();
        data3.Fill(table3);

        if (table3.Rows.Count > 0)
        {
            name.Text = Convert.ToString(table3.Rows[0][0]);
            if (Convert.ToString(table3.Rows[0][1]) == "MALE")
            {
                m.Checked = true; ;
            }
            else
            {
                f.Checked = true;
            }
            bdate.Value = Convert.ToDateTime(table3.Rows[0][2]);
            name.ReadOnly = true;
            m.Enabled = false;
            f.Enabled = false;
            bdate.Enabled = false;

        }
        else
        {
            name.Clear();
            m.Checked = false;
            f.Checked = false;
            bdate.Value = DateTime.Now;
            name.ReadOnly = false;
            m.Enabled = true;
            f.Enabled = true;
            bdate.Enabled = true;
        }
    }

    private void year_SelectedIndexChanged(object sender, EventArgs e)
    {
        view();
    }

    private void month_SelectedIndexChanged(object sender, EventArgs e)
    {
        view();
    }

    private void mrn_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != '.'))
        {
            e.Handled = true;
        }

        if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
        {
            e.Handled = true;
        }
    }

    private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        month.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
        search.ForeColor = Color.Gray;
        search.Text = "SEARCH PATIENT...";
        search2.ForeColor = Color.Gray;
        search2.Text = "SEARCH PATIENT...";
        mrn.Clear();
        name.Clear();
        phy.Text = "MANGASEP, CONCEPCION R.";
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;
    }

    private void month2_SelectedIndexChanged(object sender, EventArgs e)
    {
        bew();
    }

    private void year2_SelectedIndexChanged(object sender, EventArgs e)
    {
        bew();
    }

    private bool SetupThePrinting()
     {
         PrintDialog MyPrintDialog = new PrintDialog();
         MyPrintDialog.AllowCurrentPage = false;
         MyPrintDialog.AllowPrintToFile = false;
         MyPrintDialog.AllowSelection = false;
         MyPrintDialog.AllowSomePages = false;
         MyPrintDialog.PrintToFile = false;
         MyPrintDialog.ShowHelp = false;
         MyPrintDialog.ShowNetwork = false;
         if (MyPrintDialog.ShowDialog() != DialogResult.OK)
         return false;
         dokumento.DocumentName = "List of Patients";
         dokumento.PrinterSettings = MyPrintDialog.PrinterSettings;
         dokumento.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
         dokumento.DefaultPageSettings.Landscape = false;
         dokumento.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(10, 10, 10, 10);
         dokumento.DefaultPageSettings.Landscape = MyPrintDialog.PrinterSettings.DefaultPageSettings.Landscape;
         print = new Print(pview, dokumento, true, true, Environment.NewLine + "" + Environment.NewLine + "" + "Runway Medlinc"  + Environment.NewLine + "" + Environment.NewLine + "List of Patients"
         + Environment.NewLine + "" + Environment.NewLine + month.Text + "  " + year.Text, new Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
         return true;
     }

    private void printer_Click(object sender, EventArgs e)
       {
           if (SetupThePrinting())
           {
               PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
               MyPrintPreviewDialog.Document = dokumento;
               MyPrintPreviewDialog.ShowDialog();
               dokumento.Print();
           }
       }

    private void dokumento_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
      {
          bool more = print.DrawDataGridView(e.Graphics);
          if (more == true)
          e.HasMorePages = true;
     }

}
}

Everytime I try to print the error shows up.
it says "Not implemented exception was unhandled by user code".
how to fix this sh!t?
and the other class is here

namespace RunwayMedlinc
{
class Print
{
    private System.Windows.Forms.DataGridView pview;
    private System.Drawing.Printing.PrintDocument dokumento;
    private bool p;
    private bool p_2;
    private string p_3;
    private System.Drawing.Font font;
    private System.Drawing.Color color;
    private bool p_4;

    public Print(System.Windows.Forms.DataGridView pview, System.Drawing.Printing.PrintDocument dokumento, bool p, bool p_2, string p_3, System.Drawing.Font font, System.Drawing.Color color, bool p_4)
    {
        this.pview = pview;
        this.dokumento = dokumento;
        this.p = p;
        this.p_2 = p_2;
        this.p_3 = p_3;
        this.font = font;
        this.color = color;
        this.p_4 = p_4;
    }

    internal bool DrawDataGridView(System.Drawing.Graphics graphics)
    {
        throw new NotImplementedException();
    }
}
}


问:
edit text in android
hi
i want to restrict the special characters (!,@,#,$ etc.) from entering in to Edit Text field in android. how to do this please any body help..
thnx.</p>

答:
You need to look at the reference. EditTest inherits from TextView:
http://developer.android.com/reference/android/widget/TextView.html

There you can add an TextChangedListener:

addTextChangedListener(TextWatcher watcher)

Then you test for your special characters and remove them if they are found

ContentLicense: CC BY-SA 2.5

Title: edit text in android


问:
Add new attribute dynamically to the existing model object in Yii2 framework
In Yii2 framework is it possible to add a new attribute dynamically to an existing object, which is retrieved from Database?

Example

```<code>//Retrieve from $result
$result = Result::findone(1);
//Add dynamic attribute to the object say 'result'
$result->attributes = array('attempt' => 1);
</code>```

If it is not possible, please suggest an alternate best method to implement it.

Finally I would be converting the result to a json object. In my application, at the behaviour code block, I have used like this:

```<code>'formats' => [
               'application/json' => Response::FORMAT_JSON,
             ],
</code>```

答:
You can add define a public variable inside your model, that will store dynamic attributes as associative array. It'll look something like this:

```<code>class Result extends \yii\db\ActiveRecord implements Arrayable
{
    public $dynamic;

    // Implementation of Arrayable fields() method, for JSON
    public function fields()
    {
        return [
            'id' => 'id',
            'created_at' => 'created_at',
            // other attributes...
            'dynamic' => 'dynamic',
        ];
    }
    ...
</code>```

..in your action pass some dynamic values to your model, and return everything as JSON:

```<code>public function actionJson()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $model = Result::findOne(1);
    $model->dynamic = [
        'field1' => 'value1',
        'field2' => 2,
        'field3' => 3.33,
    ];

    return $model;
}
</code>```

In result you will get JSON like this:

```<code>{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}
</code>```

Body:
In Yii2 framework is it possible to add a new attribute dynamically to an existing object, which is retrieved from Database?

Example

//Retrieve from $result
$result = Result::findone(1);
//Add dynamic attribute to the object say 'result'
$result->attributes = array('attempt' => 1);

If it is not possible, please suggest an alternate best method to implement it.

Finally I would be converting the result to a json object. In my application, at the behaviour code block, I have used like this:

'formats' => [
               'application/json' => Response::FORMAT_JSON,
             ],

Body:
You can add define a public variable inside your model, that will store dynamic attributes as associative array. It'll look something like this:

class Result extends \yii\db\ActiveRecord implements Arrayable
{
    public $dynamic;

    // Implementation of Arrayable fields() method, for JSON
    public function fields()
    {
        return [
            'id' => 'id',
            'created_at' => 'created_at',
            // other attributes...
            'dynamic' => 'dynamic',
        ];
    }
    ...

..in your action pass some dynamic values to your model, and return everything as JSON:

public function actionJson()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $model = Result::findOne(1);
    $model->dynamic = [
        'field1' => 'value1',
        'field2' => 2,
        'field3' => 3.33,
    ];

    return $model;
}

In result you will get JSON like this:

{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}


问:
Time complexity of adjacency list representation?
I am going through this link for adjacency list representation.

http://www.geeksforgeeks.org/graph-and-its-representations/

I have a simple doubt in some part of a code as follows :

```<code>// A utility function to print the adjacenncy list representation of graph
void printGraph(struct Graph* graph)
{
    int v;
    for (v = 0; v < graph->V; ++v)
    {
        struct AdjListNode* pCrawl = graph->array[v].head;
        printf("\n Adjacency list of vertex %d\n head ", v);
        while (pCrawl)
        {
            printf("-> %d", pCrawl->dest);
            pCrawl = pCrawl->next;
        }
        printf("\n");
    }
}
</code>```

Since, here for every V while loop is executed say d times where d is the degree of each vertex.

So, I think time complexity is like

```<code>d0 + d1 + d2 + d3 ....... +dV where di is the degree of each vertex.
</code>```

All this sums up O(E), but the link says that time complexity is O(|V|+|E|)

Not sure what is the problem with the understanding. Some help needed here

答:
The important thing here is that for the time complexity to be valid, we need to cover every possible situation:

The outer loop is executed O(|V|) regardless of the graph structure.

Even if we had no edges at all, for every iteration of the outer loop, we would have to do a constant number of operations (O(1))

The inner loop is executed once for every edge, thus O(deg(v)) times, where deg(v) is the degree of the current node.

Thus the runtime of a single iteration of the outer loop is O(1 + deg(v)). Note that we cannot leave out the 1, because deg(v) might be 0 but we still need to do some work in that iteration

Summing it all up, we get a runtime of O(|V| * 1 + deg(v1) + deg(v2) + ...) = O(|V| + |E|).

As mentioned before, |E| could be rather small such that we still need
to account for the work done exclusively in the outer loop. Thus, we cannot simply remove the |V| term.

Body:
I am going through this link for adjacency list representation.

http://www.geeksforgeeks.org/graph-and-its-representations/

I have a simple doubt in some part of a code as follows :

// A utility function to print the adjacenncy list representation of graph
void printGraph(struct Graph* graph)
{
    int v;
    for (v = 0; v < graph->V; ++v)
    {
        struct AdjListNode* pCrawl = graph->array[v].head;
        printf("\n Adjacency list of vertex %d\n head ", v);
        while (pCrawl)
        {
            printf("-> %d", pCrawl->dest);
            pCrawl = pCrawl->next;
        }
        printf("\n");
    }
}

Since, here for every V while loop is executed say d times where d is the degree of each vertex.

So, I think time complexity is like

d0 + d1 + d2 + d3 ....... +dV where di is the degree of each vertex.

All this sums up O(E), but the link says that time complexity is O(|V|+|E|)

Not sure what is the problem with the understanding. Some help needed here


问:
eclipse - Always view object when debugging
I have an object in a Set that has it's guts updated by reference. Is there a way I can use the object hash ID (MyObject@93efa2ed) or Eclipse ID (id=356) to always watch in in my Expressions view even when it's out-of-scope?

I am using Eclipse Neon.

答:
Add a toString() method in you MyObject class.
  You can do it through Eclipse using:
  right click(in MyObject) -> Source -> Generate toString().
  Now you will be able to see the contents rather than hash id of MyObject.


答:
```<code>internal bool DrawDataGridView(System.Drawing.Graphics graphics)
{
    throw new NotImplementedException();
}
</code>```

The throw line is causing the issue. You need to remove that line and add an implementation there.

Title: Not implemented exception was unhandled by user code

Body:
internal bool DrawDataGridView(System.Drawing.Graphics graphics)
{
    throw new NotImplementedException();
}

The throw line is causing the issue. You need to remove that line and add an implementation there.


问:
Emoji Picker Ios Swift
I saw an app recently that incorporated an emoji picker as a way to react to certain things. I wanted to implement a similar concept into my app, anyone know how I can create something like this photo. I was thinking to use a collectionview and have each cell be its own emoji. Any thoughts or better methods?

答:
To put emojis into a collectionView, do such:

```<code>var emojiList: [[String]] = []
let sectionTitle: [String] = ["Emoticons", "Dingbats", "Transport and map symbols", "Enclosed Characters"]

override func layoutSubviews() {
    super.layoutSubviews()
    fetchEmojis()
}

func fetchEmojis(){

    let emojiRanges = [
        0x1F601...0x1F64F,
        0x2702...0x27B0,
        0x1F680...0x1F6C0,
        0x1F170...0x1F251
    ]

    for range in emojiRanges {
        var array: [String] = []
        for i in range {
            if let unicodeScalar = UnicodeScalar(i){
                array.append(String(describing: unicodeScalar))
            }
        }

        emojiList.append(array)
    }
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! DragCell
    cell.imageView.image = emojiList[indexPath.section][indexPath.item].image()
    return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return emojiList[section].count
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return emojiList.count
}
</code>```

With this extension:

```<code>extension String {

    func image() -> UIImage? {
        let size = CGSize(width: 100, height: 100)
        UIGraphicsBeginImageContextWithOptions(size, false, 0);
        UIColor.clear.set()

        let stringBounds = (self as NSString).size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 75)])
        let originX = (size.width - stringBounds.width)/2
        let originY = (size.height - stringBounds.height)/2
        print(stringBounds)
        let rect = CGRect(origin: CGPoint(x: originX, y: originY), size: size)
        UIRectFill(rect)

        (self as NSString).draw(in: rect, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 75)])

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

}
</code>```

Keep in mind that the unicode emoji ranges might not include all the emoji and you might want to look up and modify the ranges for your app

Title: Emoji Picker Ios Swift

Body:
To put emojis into a collectionView, do such:

var emojiList: [[String]] = []
let sectionTitle: [String] = ["Emoticons", "Dingbats", "Transport and map symbols", "Enclosed Characters"]

override func layoutSubviews() {
    super.layoutSubviews()
    fetchEmojis()
}

func fetchEmojis(){

    let emojiRanges = [
        0x1F601...0x1F64F,
        0x2702...0x27B0,
        0x1F680...0x1F6C0,
        0x1F170...0x1F251
    ]

    for range in emojiRanges {
        var array: [String] = []
        for i in range {
            if let unicodeScalar = UnicodeScalar(i){
                array.append(String(describing: unicodeScalar))
            }
        }

        emojiList.append(array)
    }
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! DragCell
    cell.imageView.image = emojiList[indexPath.section][indexPath.item].image()
    return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return emojiList[section].count
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return emojiList.count
}

With this extension:

extension String {

    func image() -> UIImage? {
        let size = CGSize(width: 100, height: 100)
        UIGraphicsBeginImageContextWithOptions(size, false, 0);
        UIColor.clear.set()

        let stringBounds = (self as NSString).size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 75)])
        let originX = (size.width - stringBounds.width)/2
        let originY = (size.height - stringBounds.height)/2
        print(stringBounds)
        let rect = CGRect(origin: CGPoint(x: originX, y: originY), size: size)
        UIRectFill(rect)

        (self as NSString).draw(in: rect, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 75)])

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

}

Keep in mind that the unicode emoji ranges might not include all the emoji and you might want to look up and modify the ranges for your app

ContentLicense: CC BY-SA 4.0


问:
Load div (fade in) step by step
I make a html page. I want load step by step in page with jQuery but I don't know make it.

My HTML code:

```<code><div class="main-template">
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
</div>
</code>```

Fade-in burst in sequence!

答:
Try this

$('.main-child').each(function(i) {$(this).fadeOut(0).delay(1000*i).fadeIn(1850);});

Here Is JsFiddle

Title: Load div (fade in) step by step

Body:
I make a html page. I want load step by step in page with jQuery but I don't know make it.

My HTML code:

Fade-in burst in sequence!


问:
Python Tkinter window.mainloop()
I have copied the following code to experiment with animations using Tkinter:

```<code>from Tkinter import *
window = Tk()
canvas = Canvas(window, width = 400, height = 300)
canvas.pack()
x0 = 10
y0 = 50
x1 = 60
y1 = 100
i = 0
deltax = 2
deltay = 3
which = canvas.create_oval(x0,y0,x1,y1,fill="red", tag='redBall')
while True:
    canvas.move('redBall', deltax, deltay)
    canvas.after(20)
    canvas.update()
    if x1 >= 400:
        deltax = -2
    if x0 < 0:
        deltax = 2
    if y1 > 300:
        deltay = -3
    if y0 < 0:
        deltay = 3
    x0 += deltax
    x1 += deltax
    y0 += deltay
    y1 += deltay
window.mainloop()
</code>```

This works fine, but what I have noticed is that it seems to work the same with and without the line window.mainloop(). Furthermore, this line seemingly would never be called, because the prevailing while loop never breaks. However, I have seen this example code many times, so it seems that window.mainloop() does perform something important. What is that thing??

答:
window.mainloop() does not allow python interpreter to execute codes after that line until the the application is closed. For example you can add some print statements after the window.mainloop() you will find that python prints them after you close you app.

```<code>from Tkinter import *
root=Tk()
#your code here
root.mainloop()
#now print
print 'Mainloop over'
</code>```

In this way the program loops within the mainloop allowing buttons and other widgets to perform multiple times, else program would not execute after first execution.

Title: Python Tkinter window.mainloop()

Body:
I have copied the following code to experiment with animations using Tkinter:

from Tkinter import *
window = Tk()
canvas = Canvas(window, width = 400, height = 300)
canvas.pack()
x0 = 10
y0 = 50
x1 = 60
y1 = 100
i = 0
deltax = 2
deltay = 3
which = canvas.create_oval(x0,y0,x1,y1,fill="red", tag='redBall')
while True:
    canvas.move('redBall', deltax, deltay)
    canvas.after(20)
    canvas.update()
    if x1 >= 400:
        deltax = -2
    if x0 < 0:
        deltax = 2
    if y1 > 300:
        deltay = -3
    if y0 < 0:
        deltay = 3
    x0 += deltax
    x1 += deltax
    y0 += deltay
    y1 += deltay
window.mainloop()

This works fine, but what I have noticed is that it seems to work the same with and without the line window.mainloop(). Furthermore, this line seemingly would never be called, because the prevailing while loop never breaks. However, I have seen this example code many times, so it seems that window.mainloop() does perform something important. What is that thing??

Body:
window.mainloop() does not allow python interpreter to execute codes after that line until the the application is closed. For example you can add some print statements after the window.mainloop() you will find that python prints them after you close you app.

from Tkinter import *
root=Tk()
#your code here
root.mainloop()
#now print
print 'Mainloop over'

In this way the program loops within the mainloop allowing buttons and other widgets to perform multiple times, else program would not execute after first execution.