问:
Getting text to align in a radio button template
I am attempting to make a radio button template which will look like the following:
enter image description here

And here is the template I have added:

```<code><Style
        x:Key="MainWindowTemplateConfigurationWindowRadioButtonStyle"
        TargetType="RadioButton"
        BasedOn="{StaticResource MainWindowRadioButtonImageStyle}">
        <Setter
            Property="Margin"
            Value="3,3" />
        <Setter
            Property="Template">
            <Setter.Value>
                <ControlTemplate
                    TargetType="{x:Type RadioButton}">
                    <Border BorderThickness="2" BorderBrush="{StaticResource BRInactiveItemBackgroundBrush}" >
                        <StackPanel x:Name="Panel" Background="{StaticResource ControlsLightBorderBrush}" VerticalAlignment="Stretch"
                                    >
                            <TextBlock x:Name="ButtonText" TextAlignment="Center" FontSize="25" Padding="7,7" VerticalAlignment="Center"
                                       />
                        </StackPanel>
                    </Border>
                    <ControlTemplate.Triggers>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition
                                    Binding="{Binding Tag, RelativeSource={RelativeSource Self}}"
                                    Value="{x:Static views:DisplayModes.SystemConfiguration}"/>
                                <Condition
                                    Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}"
                                    Value="True" />
                            </MultiDataTrigger.Conditions>
                            <Setter
                                Property="Text"
                                TargetName="ButtonText"
                                Value="{StaticResource SystemConfigurationRadioButton}" />
                            <Setter
                                Property="Background"
                                TargetName="Panel"
                                Value="{StaticResource BRInactiveItemBackgroundBrush}" />
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition
                                    Binding="{Binding Tag, RelativeSource={RelativeSource Self}}"
                                    Value="{x:Static views:DisplayModes.SystemConfiguration}"/>
                                <Condition
                                    Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}"
                                    Value="False" />
                            </MultiDataTrigger.Conditions>
                            <Setter
                                Property="Text"
                                TargetName="ButtonText"
                                Value="{StaticResource SystemConfigurationRadioButton}" />
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition
                                    Binding="{Binding Tag, RelativeSource={RelativeSource Self}}"
                                    Value="{x:Static views:DisplayModes.PlateSetup}"/>
                                <Condition
                                    Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}"
                                    Value="True" />
                            </MultiDataTrigger.Conditions>
                            <Setter
                                Property="Text"
                                TargetName="ButtonText"
                                Value="{StaticResource PlateSetup}" />
                            <Setter
                                Property="Background"
                                TargetName="Panel"
                                Value="{StaticResource BRInactiveItemBackgroundBrush}" />
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition
                                    Binding="{Binding Tag, RelativeSource={RelativeSource Self}}"
                                    Value="{x:Static views:DisplayModes.PlateSetup}"/>
                                <Condition
                                    Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}"
                                    Value="False" />
                            </MultiDataTrigger.Conditions>
                            <Setter
                                Property="Text"
                                TargetName="ButtonText"
                                Value="{StaticResource PlateSetup}" />
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition
                                    Binding="{Binding Tag, RelativeSource={RelativeSource Self}}"
                                    Value="{x:Static views:DisplayModes.ThermalCyclingProtocol}"/>
                                <Condition
                                    Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}"
                                    Value="True" />
                            </MultiDataTrigger.Conditions>
                            <Setter
                                Property="Text"
                                TargetName="ButtonText"
                                Value="{StaticResource ThermalProtocol}" />
                            <Setter
                                Property="Background"
                                TargetName="Panel"
                                Value="{StaticResource BRInactiveItemBackgroundBrush}" />
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition
                                    Binding="{Binding Tag, RelativeSource={RelativeSource Self}}"
                                    Value="{x:Static views:DisplayModes.ThermalCyclingProtocol}"/>
                                <Condition
                                    Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}"
                                    Value="False" />
                            </MultiDataTrigger.Conditions>
                            <Setter
                                Property="Text"
                                TargetName="ButtonText"
                                Value="{StaticResource ThermalProtocol}" />
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition
                                    Binding="{Binding Tag, RelativeSource={RelativeSource Self}}"
                                    Value="{x:Static views:DisplayModes.Reports}"/>
                                <Condition
                                    Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}"
                                    Value="True" />
                            </MultiDataTrigger.Conditions>
                            <Setter
                                Property="Text"
                                TargetName="ButtonText"
                                Value="{StaticResource ReportsRadioButton}" />
                            <Setter
                                Property="Background"
                                TargetName="Panel"
                                Value="{StaticResource BRInactiveItemBackgroundBrush}" />
                        </MultiDataTrigger>
                        <MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition
                                    Binding="{Binding Tag, RelativeSource={RelativeSource Self}}"
                                    Value="{x:Static views:DisplayModes.Reports}"/>
                                <Condition
                                    Binding="{Binding IsChecked, RelativeSource={RelativeSource Self}}"
                                    Value="False" />
                            </MultiDataTrigger.Conditions>
                            <Setter
                                Property="Text"
                                TargetName="ButtonText"
                                Value="{StaticResource ReportsRadioButton}" />
                        </MultiDataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

However, the result I am getting is looking like this:
enter image description here

I have tried playing with all the properties between the StackPanel and the TextBlock to align the text in the center of the radio button, but when I do get that, I have a result of the text being centrally aligned, but then the content doesn't fit to fill the space of the radio button.  I can't attach any more images, since I don't have enough reputation, apologies...

which i essentially get by changing the StackPanel's VerticalAlignment to Center from Stretch, but then it doesn't fill the whole region correctly.  I am forcing the height of each RadioButton where I consume this style to be the same height of the tallest button (the one saying Thermal Cyling Protocol), and it doesn't seem like I can figure out how to make both the text be centered and fill in the extra height at the same time...

Any help would be appreciated.
Here is how I am laying out the Radio Button if it helps:

```<code><Grid Margin="5,5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid Grid.Column="0" >
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid Grid.Row="0" >
                    <Grid.RowDefinitions>
                        <RowDefinition SharedSizeGroup="A"/>
                        <RowDefinition SharedSizeGroup="A"/>
                        <RowDefinition SharedSizeGroup="A"/>
                        <RowDefinition SharedSizeGroup="A"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <RadioButton Grid.Row="0" Style="{StaticResource MainWindowTemplateConfigurationWindowRadioButtonStyle}"
                                 HorizontalAlignment="Stretch"
                                 Height="{Binding ActualHeight, ElementName=ThermalCyclingProtocolButton}"
                                 Tag="{x:Static views:DisplayModes.SystemConfiguration}">
                    </RadioButton>
                    <RadioButton Grid.Row="1" Style="{StaticResource MainWindowTemplateConfigurationWindowRadioButtonStyle}"
                                 HorizontalAlignment="Stretch"
                                 Height="{Binding ActualHeight, ElementName=ThermalCyclingProtocolButton}"
                                 Tag="{x:Static views:DisplayModes.PlateSetup}">
                    </RadioButton>
                    <RadioButton Grid.Row="2" Style="{StaticResource MainWindowTemplateConfigurationWindowRadioButtonStyle}"
                                 HorizontalAlignment="Stretch" x:Name="ThermalCyclingProtocolButton"
                                 Tag="{x:Static views:DisplayModes.ThermalCyclingProtocol}">
                    </RadioButton>
                    <RadioButton Grid.Row="3" Style="{StaticResource MainWindowTemplateConfigurationWindowRadioButtonStyle}"
                                 HorizontalAlignment="Stretch"
                                 Height="{Binding ActualHeight, ElementName=ThermalCyclingProtocolButton}"
                                 Tag="{x:Static views:DisplayModes.Reports}">
                    </RadioButton>
                </Grid>
            </Grid>
        </Grid>
    </Grid>
</code>```

答: Changed the panel in the template from being a StackPanel to being a Grid.  This has now achieved the effect for which I was looking.</p>

Body:
I am attempting to make a radio button template which will look like the following:
enter image description here

And here is the template I have added:

However, the result I am getting is looking like this:
enter image description here

I have tried playing with all the properties between the StackPanel and the TextBlock to align the text in the center of the radio button, but when I do get that, I have a result of the text being centrally aligned, but then the content doesn't fit to fill the space of the radio button.  I can't attach any more images, since I don't have enough reputation, apologies...

which i essentially get by changing the StackPanel's VerticalAlignment to Center from Stretch, but then it doesn't fill the whole region correctly.  I am forcing the height of each RadioButton where I consume this style to be the same height of the tallest button (the one saying Thermal Cyling Protocol), and it doesn't seem like I can figure out how to make both the text be centered and fill in the extra height at the same time...

Any help would be appreciated.
Here is how I am laying out the Radio Button if it helps:

<Grid Margin="5,5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid Grid.Column="0" >
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid Grid.Row="0" >
                    <Grid.RowDefinitions>
                        <RowDefinition SharedSizeGroup="A"/>
                        <RowDefinition SharedSizeGroup="A"/>
                        <RowDefinition SharedSizeGroup="A"/>
                        <RowDefinition SharedSizeGroup="A"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <RadioButton Grid.Row="0" Style="{StaticResource MainWindowTemplateConfigurationWindowRadioButtonStyle}"
                                 HorizontalAlignment="Stretch"
                                 Height="{Binding ActualHeight, ElementName=ThermalCyclingProtocolButton}"
                                 Tag="{x:Static views:DisplayModes.SystemConfiguration}">
                    </RadioButton>
                    <RadioButton Grid.Row="1" Style="{StaticResource MainWindowTemplateConfigurationWindowRadioButtonStyle}"
                                 HorizontalAlignment="Stretch"
                                 Height="{Binding ActualHeight, ElementName=ThermalCyclingProtocolButton}"
                                 Tag="{x:Static views:DisplayModes.PlateSetup}">
                    </RadioButton>
                    <RadioButton Grid.Row="2" Style="{StaticResource MainWindowTemplateConfigurationWindowRadioButtonStyle}"
                                 HorizontalAlignment="Stretch" x:Name="ThermalCyclingProtocolButton"
                                 Tag="{x:Static views:DisplayModes.ThermalCyclingProtocol}">
                    </RadioButton>
                    <RadioButton Grid.Row="3" Style="{StaticResource MainWindowTemplateConfigurationWindowRadioButtonStyle}"
                                 HorizontalAlignment="Stretch"
                                 Height="{Binding ActualHeight, ElementName=ThermalCyclingProtocolButton}"
                                 Tag="{x:Static views:DisplayModes.Reports}">
                    </RadioButton>
                </Grid>
            </Grid>
        </Grid>
    </Grid>


来源: stackexchange

问:
wondering if there is an efficient way to shorten this code
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

```<code>private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}
</code>```

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

答:
Create a class to represent a book list:

```<code>public class BookList
{
  public string ImageName { get; set; }
  public List<string> Items { get;set; }
}
</code>```

Then create a dictionary to hold these items:

```<code>Dictionary<string, BookList> bookLists = new Dictionary<string, BookList>
  {
    {
       "Programming",
       new BookList { ImageName = "programming.png", Items = new List<string> { ... } }
    }
    ...
  };
</code>```

Then modify your if statements to:

```<code>if (bookLists.ContainsKey(books))
{
  bookListBox.Items.Clear();
  selectedPictureBox.Image = Image.FromFile(bookLists[books].ImageName);
  foreach (var b in bookLists[books].Items)
  {
     bookListBox.Items.Add(b);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

Body:
Create a class to represent a book list:

public class BookList
{
  public string ImageName { get; set; }
  public List<string> Items { get;set; }
}

Then create a dictionary to hold these items:

Dictionary<string, BookList> bookLists = new Dictionary<string, BookList>
  {
    {
       "Programming",
       new BookList { ImageName = "programming.png", Items = new List<string> { ... } }
    }
    ...
  };

Then modify your if statements to:

if (bookLists.ContainsKey(books))
{
  bookListBox.Items.Clear();
  selectedPictureBox.Image = Image.FromFile(bookLists[books].ImageName);
  foreach (var b in bookLists[books].Items)
  {
     bookListBox.Items.Add(b);
  }
}


问:
How to Async Mongoose Controller
Trying to configure a SignUp() controller that can update multiple (separate) user accounts when a referral code is provided by the user.

Basic Flow:

Verify email doesn't already exist in system

Find the driver w/ userID matching the rider's refCode (FindOneAndUpdate)

If Found: Add the userID of each user to the other users [clients] list

Only need to do a refCode match if isRider

If any of those fail... Return the specific error to the client/user

This does not work. But essentially, this is what I'm trying to accomplish...

```<code>// POST `/signup` (Create a new local user)
export function signUp(req, res, next) {
  const newUser = new User({
    email: req.body.email,
    password: req.body.password,
    profile: {
      userID: req.body.userID,
      refCode: req.body.refCode,
      isRider: req.body.isRider
    }
  });

  User.findOne({ email: req.body.email }, (findErr, foundUser) => {
    if (foundUser) {
      return res.status(409).send('This e-mail address already exists');
    }
    // riders must link to a driver
    if (req.body.isRider) {
      // find driver + add rider ID to clients
      return User.findOneAndUpdate({ 'profile.userID': req.body.refCode }, { $push: { clients: newUser.profile.userID }}).exec()
        .then((err, foundDriver) => {
          if (err) {
            return res.status(409).send('Error searching for driver');
          } else if (!foundDriver) {
            return res.status(409).send(`We can't find your driver (${req.body.refCode})!`);
          }
          // add driver ID to rider's clients
          newUser.clients = [req.body.refCode];

          return newUser.save((saveErr) => {
            if (saveErr) return next(saveErr);
            return req.logIn(newUser, (loginErr) => {
              if (loginErr) return res.sendStatus(401);
              return res.json(newUser.profile);
            });
          });
        });
    }

    return newUser.save((saveErr) => {
      if (saveErr) return next(saveErr);
      return req.logIn(newUser, (loginErr) => {
        if (loginErr) return res.sendStatus(401);
        return res.json(newUser.profile);
      });
    });
  });
}
</code>```

Tried to configure it as a pure promise but no luck. Most of the examples out there all seem different to me... Also could not figure out how to handle/throw specific errors using the mongoose docs.

Greatly appreciated if anyone can lend a hand, Thx!

UPDATE:
Ippi's answer helped a ton - Thx!

This does the trick. Remember to return null from .then() after the req.login stuff to avoid warnings - Any tips on how to improve this are appreciated - Thx!

```<code>  const createUser = (foundUser) => {
    if (foundUser) { throw new Error('This e-mail address already exist.'); }
    if (!req.body.isRider) { return newUser.save(); }
    return User.findOneAndUpdate({ 'profile.userID': req.body.refCode.toLowerCase() }, { $push: { clients: newUser.profile.userID }}).exec()
      .then((driver) => {
        if (!driver) { throw new Error('We can\'t find your driver.'); }
        newUser.clients = [req.body.refCode];
        return newUser.save();
      })
      .catch(() => { throw new Error('There was a database error.'); });
  };

  User.findOne({ email: req.body.email }).exec()
    .then(createUser)
    .then((user) => {
      if (user.profile) {
        req.logIn(user, (loginErr) => {
          if (loginErr) return res.sendStatus(401);
          return res.status(200).send({ profile: user.profile, clients: user.clients });
        });
      } else { res.status(409); }
      return null;
    })
    .catch((err) => { return res.status(409).send(err.message); });
</code>```

答:
This is how I would do it. I couldn't be bothered to try with express or the login (you need to replace console.log with res.status().json()) and I might have done some other blunder in the logic with the driver. But other than that I tested it with local mongo and it probably works and if nothing else it's a little bit more concise.

```<code>let updateUser = user => {
  if (user){ throw new Error("USER_EXIST"); }
  if (!req.body.isRider) { return newUser.save() }
  return User.findOneAndUpdate({ 'profile.userID': req.body.refCode },{ $push: { clients: newUser.profile.userID }}).exec()
    .then(driver => {
      if (!driver) { throw new Error("NO_DRIVER");}
      newUser.clients.push(req.body.refCode);
      return newUser.save();
    });
}

User.findOne({ email: req.body.email }).exec()
  .then(updateUser)
  .then(req.logIn) // newUser.save() response is passed in as is (I have not tested this line.)
  .then( ()=>{ return console.log('profile', newUser.profile);  })
  .catch( Error,  err => {
    if (err.message == "USER_EXISTS") return console.log ("This e-mail address already exist." );
    if (err.message == "NO_DRIVER") return console.log ("We can't find your driver." );
      throw err;
  });
</code>```

Something worth remembering:

Callback calls or res.send should always go in the last then / catch. Calling res.send in middle of chains leads to trouble.

Title: How to Async Mongoose Controller

Body:
Trying to configure a SignUp() controller that can update multiple (separate) user accounts when a referral code is provided by the user.

Basic Flow:

Verify email doesn't already exist in system

Find the driver w/ userID matching the rider's refCode (FindOneAndUpdate)

If Found: Add the userID of each user to the other users [clients] list

Only need to do a refCode match if isRider

If any of those fail... Return the specific error to the client/user

This does not work. But essentially, this is what I'm trying to accomplish...

// POST `/signup` (Create a new local user)
export function signUp(req, res, next) {
  const newUser = new User({
    email: req.body.email,
    password: req.body.password,
    profile: {
      userID: req.body.userID,
      refCode: req.body.refCode,
      isRider: req.body.isRider
    }
  });

  User.findOne({ email: req.body.email }, (findErr, foundUser) => {
    if (foundUser) {
      return res.status(409).send('This e-mail address already exists');
    }
    // riders must link to a driver
    if (req.body.isRider) {
      // find driver + add rider ID to clients
      return User.findOneAndUpdate({ 'profile.userID': req.body.refCode }, { $push: { clients: newUser.profile.userID }}).exec()
        .then((err, foundDriver) => {
          if (err) {
            return res.status(409).send('Error searching for driver');
          } else if (!foundDriver) {
            return res.status(409).send(`We can't find your driver (${req.body.refCode})!`);
          }
          // add driver ID to rider's clients
          newUser.clients = [req.body.refCode];

          return newUser.save((saveErr) => {
            if (saveErr) return next(saveErr);
            return req.logIn(newUser, (loginErr) => {
              if (loginErr) return res.sendStatus(401);
              return res.json(newUser.profile);
            });
          });
        });
    }

    return newUser.save((saveErr) => {
      if (saveErr) return next(saveErr);
      return req.logIn(newUser, (loginErr) => {
        if (loginErr) return res.sendStatus(401);
        return res.json(newUser.profile);
      });
    });
  });
}

Tried to configure it as a pure promise but no luck. Most of the examples out there all seem different to me... Also could not figure out how to handle/throw specific errors using the mongoose docs.

Greatly appreciated if anyone can lend a hand, Thx!

UPDATE:
Ippi's answer helped a ton - Thx!

This does the trick. Remember to return null from .then() after the req.login stuff to avoid warnings - Any tips on how to improve this are appreciated - Thx!

  const createUser = (foundUser) => {
    if (foundUser) { throw new Error('This e-mail address already exist.'); }
    if (!req.body.isRider) { return newUser.save(); }
    return User.findOneAndUpdate({ 'profile.userID': req.body.refCode.toLowerCase() }, { $push: { clients: newUser.profile.userID }}).exec()
      .then((driver) => {
        if (!driver) { throw new Error('We can\'t find your driver.'); }
        newUser.clients = [req.body.refCode];
        return newUser.save();
      })
      .catch(() => { throw new Error('There was a database error.'); });
  };

  User.findOne({ email: req.body.email }).exec()
    .then(createUser)
    .then((user) => {
      if (user.profile) {
        req.logIn(user, (loginErr) => {
          if (loginErr) return res.sendStatus(401);
          return res.status(200).send({ profile: user.profile, clients: user.clients });
        });
      } else { res.status(409); }
      return null;
    })
    .catch((err) => { return res.status(409).send(err.message); });

Body:
This is how I would do it. I couldn't be bothered to try with express or the login (you need to replace console.log with res.status().json()) and I might have done some other blunder in the logic with the driver. But other than that I tested it with local mongo and it probably works and if nothing else it's a little bit more concise.

let updateUser = user => {
  if (user){ throw new Error("USER_EXIST"); }
  if (!req.body.isRider) { return newUser.save() }
  return User.findOneAndUpdate({ 'profile.userID': req.body.refCode },{ $push: { clients: newUser.profile.userID }}).exec()
    .then(driver => {
      if (!driver) { throw new Error("NO_DRIVER");}
      newUser.clients.push(req.body.refCode);
      return newUser.save();
    });
}

User.findOne({ email: req.body.email }).exec()
  .then(updateUser)
  .then(req.logIn) // newUser.save() response is passed in as is (I have not tested this line.)
  .then( ()=>{ return console.log('profile', newUser.profile);  })
  .catch( Error,  err => {
    if (err.message == "USER_EXISTS") return console.log ("This e-mail address already exist." );
    if (err.message == "NO_DRIVER") return console.log ("We can't find your driver." );
      throw err;
  });

Something worth remembering:

Callback calls or res.send should always go in the last then / catch. Calling res.send in middle of chains leads to trouble.


问:
Getting values of textfields on page
Lets just say that I have some (many many many) text fields on a page... and i enter a new value in one of them, then click a button... How can I update the database with just that new value? Or, if it would be easier... How can I update all of those textfields to the database?

Thanks :)

答:
To update everything:

You can organize your inputs like this (1,2,3,4 - are record id's in database):

```<code><input type="text" name="info[1]" value="blabla">
<input type="text" name="info[2]" value="blabla">
<input type="text" name="info[3]" value="blabla">
<input type="text" name="info[4]" value="blabla">
<!-- ... -->
</code>```

Then, in your PHP script:

```<code><?php
foreach($_POST['info'] as $id=>$data){
    mysql_query("UPDATE table SET data = '".mysql_escape_string($data)."' WHERE id = ".intval($id));
}
?>
</code>```

This way there will be one UPDATE statement for every record

To update only those that changed:

You can use javascript's onChange() event to see what fields were changed and submit only those. Just be carefull, if a user has javascript disabled, he well never be able to change any record.

ContentLicense: CC BY-SA 2.5

Title: Getting values of textfields on page

Body:
To update everything:

You can organize your inputs like this (1,2,3,4 - are record id's in database):

<input type="text" name="info[1]" value="blabla">
<input type="text" name="info[2]" value="blabla">
<input type="text" name="info[3]" value="blabla">
<input type="text" name="info[4]" value="blabla">
<!-- ... -->

Then, in your PHP script:

<?php
foreach($_POST['info'] as $id=>$data){
    mysql_query("UPDATE table SET data = '".mysql_escape_string($data)."' WHERE id = ".intval($id));
}
?>

This way there will be one UPDATE statement for every record

To update only those that changed:

You can use javascript's onChange() event to see what fields were changed and submit only those. Just be carefull, if a user has javascript disabled, he well never be able to change any record.


问:
CodeIgniter / Ajax . Posting parameters through ajax to CodeIgniter controller
I am trying to post some variables to CodeIgniter controller function through ajax but ts resulting in an error message .

This is my javascript function

```<code>$(document).ready(function()
 {

    $('.add_cart').click(function(){
      var quantity = $('#qty').val();
      var product_id = $(this).data("productid");
      var product_name = $(this).data("productname");
      var product_price = $(this).data("price");

      if(quantity != '' && quantity > 0)
          {
           $.ajax({
            url:"<?php echo base_url(); ?>products/add_product_to_cart",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
            success:function(data)
            {
                alert('success');
            }
           });
          }
          else
          {
           alert("Please Enter quantity");
          }

        });
      });
</code>```

Here is my controller function.

```<code>    public function add_product_to_cart()
{

    echo $_POST["product_id"];

}
</code>```

But when i track the whole process through firebug .Its giving the error that undefined variable product_id or does not print any thing when i try to echo it as given below.

Here is the screen shot.

Can somebody help me about how to do this right or is there any special file that you need to include for ajax functions?

答:
```<code>   var var_data = {product_id:product_id,
                   product_name:product_name,
                   product_price:product_price,
                   quantity:quantity}
   $.ajax({
        url:"<?php echo base_url(); ?>products/add_product_to_cart",
        type:"POST",
        dataType : 'json',
        async : false,
        data:var_data,
        success:function(data)
        {
            alert('success');
        }
       });
</code>```

in controller function get the post array from var_data

like

```<code>   $post_data = $this->input->post('var_data',true);
   print_r($post_data);
</code>```

try it like this may be help , change method to type

Body:
I am trying to post some variables to CodeIgniter controller function through ajax but ts resulting in an error message .

This is my javascript function

$(document).ready(function()
 {

    $('.add_cart').click(function(){
      var quantity = $('#qty').val();
      var product_id = $(this).data("productid");
      var product_name = $(this).data("productname");
      var product_price = $(this).data("price");

      if(quantity != '' && quantity > 0)
          {
           $.ajax({
            url:"<?php echo base_url(); ?>products/add_product_to_cart",
            method:"POST",
            data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
            success:function(data)
            {
                alert('success');
            }
           });
          }
          else
          {
           alert("Please Enter quantity");
          }

        });
      });

Here is my controller function.

    public function add_product_to_cart()
{

    echo $_POST["product_id"];

}

But when i track the whole process through firebug .Its giving the error that undefined variable product_id or does not print any thing when i try to echo it as given below.

Here is the screen shot.

Can somebody help me about how to do this right or is there any special file that you need to include for ajax functions?

Body:
   var var_data = {product_id:product_id,
                   product_name:product_name,
                   product_price:product_price,
                   quantity:quantity}
   $.ajax({
        url:"<?php echo base_url(); ?>products/add_product_to_cart",
        type:"POST",
        dataType : 'json',
        async : false,
        data:var_data,
        success:function(data)
        {
            alert('success');
        }
       });

in controller function get the post array from var_data

like

   $post_data = $this->input->post('var_data',true);
   print_r($post_data);

try it like this may be help , change method to type


问:
Select query in sqlite in android with two value in where clause
i want to write  query in sqlite for android in which i want to get a value based upon two values of that row.How can i do that?
i have the following query to get value based on one value:</p>

```<code>cursor = db.query(TABLE_NAME,new String[] {NAME}, ROLL_NO + " like" + "'%"
                + roll + "%'", null, null, null, null);
</code>```

答:
Its Simple try this actid,cusid is string and FF_CUSTOMER_ID,FF_ACTIVITY_ID is column name

Cursor cursor = db.rawQuery("select * from " + TABLE_PROJECT_ACTIVITY_CHECKLIST +" where " + FF_ACTIVITY_ID + " = ? AND " + FF_CUSTOMER_ID + " = ? " , new String[] { actid,cusid});

Body:
i want to write  query in sqlite for android in which i want to get a value based upon two values of that row.How can i do that?
i have the following query to get value based on one value:

cursor = db.query(TABLE_NAME,new String[] {NAME}, ROLL_NO + " like" + "'%"
                + roll + "%'", null, null, null, null);


问:
How to wrap multi actionCreators into one props?
I'm getting the following error:

Uncaught TypeError: this.props.dispatch is not a function

Here's my component:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as jobTitleSkillsActions from '../../actions/jobTitleSkillsActions';
import SkillList from './SkillList';
import * as userPositionActions from '../../actions/userPositionActions';

class SkillPage extends React.Component {

  componentDidMount() {
    this.props.dispatch(userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;    this.props.dispatch(jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

.....

const mapStateToProps = state => {
  return {
    job_title_skills: state.job_title_skills,
    user_positions: state.user_positions
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: {
      userPositionActions: bindActionCreators(userPositionActions, dispatch),
      jobTitleSkillsActions: bindActionCreators(jobTitleSkillsActions, dispatch),
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SkillPage);
</code>```

What am I doing wrong here?

答:
As you have provided mapDispatchToProps to connect function, dispatch is not passed as prop to your component.

Your componentDidMount code should be like this:

```<code>componentDidMount() {
  const actions = this.props.actions
  actions.userPositionActions.loadUserPositions()
  var job_title_id = this.props.user_positions[0].job_title_id;
  actions.jobTitleSkillsActions.loadJobTitleSkills(job_title_id)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting the following error:

Uncaught TypeError: this.props.dispatch is not a function

Here's my component:

import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as jobTitleSkillsActions from '../../actions/jobTitleSkillsActions';
import SkillList from './SkillList';
import * as userPositionActions from '../../actions/userPositionActions';

class SkillPage extends React.Component {

  componentDidMount() {
    this.props.dispatch(userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;    this.props.dispatch(jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

.....

const mapStateToProps = state => {
  return {
    job_title_skills: state.job_title_skills,
    user_positions: state.user_positions
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: {
      userPositionActions: bindActionCreators(userPositionActions, dispatch),
      jobTitleSkillsActions: bindActionCreators(jobTitleSkillsActions, dispatch),
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SkillPage);

What am I doing wrong here?

Body:
As you have provided mapDispatchToProps to connect function, dispatch is not passed as prop to your component.

Your componentDidMount code should be like this:

componentDidMount() {
  const actions = this.props.actions
  actions.userPositionActions.loadUserPositions()
  var job_title_id = this.props.user_positions[0].job_title_id;
  actions.jobTitleSkillsActions.loadJobTitleSkills(job_title_id)
}


问:
ffmpeg: Streamcopy requested for output stream 0:0, which is fed from a complex filtergraph. Filtering and streamcopy cannot be used together
I'm on Fedora25 running the following command expecting live streaming to youtube and at the same time saving of the final combined stream (screencast + webcam + logo + audio) into local mp4 file.

```<code>ffmpeg \
-f x11grab -video_size 3840x2160 -framerate 30 -i :1.0 \
-f v4l2 -video_size 320x240 -framerate 30 -i /dev/video1 \
-f alsa -ac 2 -i pulse -i logo.png -filter_complex \
"[0:v]scale=1920:-1,setpts=PTS-STARTPTS[bg]; \
 [1:v]scale=160:-1,setpts=PTS-STARTPTS[fg]; \
 [bg][fg]overlay=W-w-10:10[bg2]; \
 [bg2][3:v]overlay=W-w-10:H-h-10,format=yuv420p[out]" \
-map "[out]" -map 2:a -c:v libx264 -preset veryfast \
-maxrate 9000k -bufsize 12000k -c:a aac -b:a 160k -ar 44100 -b:a 128k \
-force_key_frames "expr:gte(t,n_forced*2)" \
-c copy -f flv rtmp://a.rtmp.youtube.com/live2/TOKEN
-c copy -f mp4 out.mp4
</code>```

getting the following output

```<code>ffmpeg version 3.1.7 Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 6.3.1 (GCC) 20161221 (Red Hat 6.3.1-1)
  configuration: --prefix=/usr --bindir=/usr/bin --datadir=/usr/share/ffmpeg --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --optflags='-O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --extra-ldflags='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld' --enable-bzlib --disable-crystalhd --enable-fontconfig --enable-frei0r --enable-gcrypt --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libcdio --enable-indev=jack --enable-libfreetype --enable-libfribidi --enable-libgsm --enable-libmp3lame --enable-nvenc --extra-cflags=-I/usr/include/nvenc --enable-openal --enable-opencl --enable-opengl --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libvorbis --enable-libv4l2 --enable-libvpx --enable-libx264 --enable-libx265 --enable-libxvid --enable-x11grab --enable-avfilter --enable-avresample --enable-postproc --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-stripping --shlibdir=/usr/lib64 --enable-libmfx --enable-runtime-cpudetect
  libavutil      55. 28.100 / 55. 28.100
  libavcodec     57. 48.101 / 57. 48.101
  libavformat    57. 41.100 / 57. 41.100
  libavdevice    57.  0.101 / 57.  0.101
  libavfilter     6. 47.100 /  6. 47.100
  libavresample   3.  0.  0 /  3.  0.  0
  libswscale      4.  1.100 /  4.  1.100
  libswresample   2.  1.100 /  2.  1.100
  libpostproc    54.  0.100 / 54.  0.100
[x11grab @ 0x562f6e929c20] Stream #0: not enough frames to estimate rate; consider increasing probesize
Input #0, x11grab, from ':1.0':
  Duration: N/A, start: 1496800335.695598, bitrate: N/A
    Stream #0:0: Video: rawvideo (BGR[0] / 0x524742), bgr0, 3840x2160, 30 fps, 1000k tbr, 1000k tbn, 1000k tbc
Input #1, video4linux2,v4l2, from '/dev/video1':
  Duration: N/A, start: 17665.258327, bitrate: 36864 kb/s
    Stream #1:0: Video: rawvideo (YUY2 / 0x32595559), yuyv422, 320x240, 36864 kb/s, 30 fps, 30 tbr, 1000k tbn, 1000k tbc
Guessed Channel Layout for Input Stream #2.0 : stereo
Input #2, alsa, from 'pulse':
  Duration: N/A, start: 1496800336.972575, bitrate: 1536 kb/s
    Stream #2:0: Audio: pcm_s16le, 48000 Hz, 2 channels, s16, 1536 kb/s
Input #3, png_pipe, from 'logo.png':
  Duration: N/A, bitrate: N/A
    Stream #3:0: Video: png, rgba(pc), 190x105 [SAR 2835:2835 DAR 38:21], 25 tbr, 25 tbn, 25 tbc
Streamcopy requested for output stream 0:0, which is fed from a complex filtergraph. Filtering and streamcopy cannot be used together.
➜  tmp
</code>```

答: Since you are filtering or encoding the input streams, you can't do a stream copy on the input. Remove -c copy altogether.

Body:
I'm on Fedora25 running the following command expecting live streaming to youtube and at the same time saving of the final combined stream (screencast + webcam + logo + audio) into local mp4 file.

ffmpeg \
-f x11grab -video_size 3840x2160 -framerate 30 -i :1.0 \
-f v4l2 -video_size 320x240 -framerate 30 -i /dev/video1 \
-f alsa -ac 2 -i pulse -i logo.png -filter_complex \
"[0:v]scale=1920:-1,setpts=PTS-STARTPTS[bg]; \
 [1:v]scale=160:-1,setpts=PTS-STARTPTS[fg]; \
 [bg][fg]overlay=W-w-10:10[bg2]; \
 [bg2][3:v]overlay=W-w-10:H-h-10,format=yuv420p[out]" \
-map "[out]" -map 2:a -c:v libx264 -preset veryfast \
-maxrate 9000k -bufsize 12000k -c:a aac -b:a 160k -ar 44100 -b:a 128k \
-force_key_frames "expr:gte(t,n_forced*2)" \
-c copy -f flv rtmp://a.rtmp.youtube.com/live2/TOKEN
-c copy -f mp4 out.mp4

getting the following output

ffmpeg version 3.1.7 Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 6.3.1 (GCC) 20161221 (Red Hat 6.3.1-1)
  configuration: --prefix=/usr --bindir=/usr/bin --datadir=/usr/share/ffmpeg --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --optflags='-O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --extra-ldflags='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld' --enable-bzlib --disable-crystalhd --enable-fontconfig --enable-frei0r --enable-gcrypt --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libcdio --enable-indev=jack --enable-libfreetype --enable-libfribidi --enable-libgsm --enable-libmp3lame --enable-nvenc --extra-cflags=-I/usr/include/nvenc --enable-openal --enable-opencl --enable-opengl --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libvorbis --enable-libv4l2 --enable-libvpx --enable-libx264 --enable-libx265 --enable-libxvid --enable-x11grab --enable-avfilter --enable-avresample --enable-postproc --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-stripping --shlibdir=/usr/lib64 --enable-libmfx --enable-runtime-cpudetect
  libavutil      55. 28.100 / 55. 28.100
  libavcodec     57. 48.101 / 57. 48.101
  libavformat    57. 41.100 / 57. 41.100
  libavdevice    57.  0.101 / 57.  0.101
  libavfilter     6. 47.100 /  6. 47.100
  libavresample   3.  0.  0 /  3.  0.  0
  libswscale      4.  1.100 /  4.  1.100
  libswresample   2.  1.100 /  2.  1.100
  libpostproc    54.  0.100 / 54.  0.100
[x11grab @ 0x562f6e929c20] Stream #0: not enough frames to estimate rate; consider increasing probesize
Input #0, x11grab, from ':1.0':
  Duration: N/A, start: 1496800335.695598, bitrate: N/A
    Stream #0:0: Video: rawvideo (BGR[0] / 0x524742), bgr0, 3840x2160, 30 fps, 1000k tbr, 1000k tbn, 1000k tbc
Input #1, video4linux2,v4l2, from '/dev/video1':
  Duration: N/A, start: 17665.258327, bitrate: 36864 kb/s
    Stream #1:0: Video: rawvideo (YUY2 / 0x32595559), yuyv422, 320x240, 36864 kb/s, 30 fps, 30 tbr, 1000k tbn, 1000k tbc
Guessed Channel Layout for Input Stream #2.0 : stereo
Input #2, alsa, from 'pulse':
  Duration: N/A, start: 1496800336.972575, bitrate: 1536 kb/s
    Stream #2:0: Audio: pcm_s16le, 48000 Hz, 2 channels, s16, 1536 kb/s
Input #3, png_pipe, from 'logo.png':
  Duration: N/A, bitrate: N/A
    Stream #3:0: Video: png, rgba(pc), 190x105 [SAR 2835:2835 DAR 38:21], 25 tbr, 25 tbn, 25 tbc
Streamcopy requested for output stream 0:0, which is fed from a complex filtergraph. Filtering and streamcopy cannot be used together.
➜  tmp


问:
Swift - Assign Function to ToolBar Button Item
I have used a tool bar on the storyboard and i have some custom buttons on it.
How can I assign these buttons to the functions created in the Viewcontroller?

答:
You can create IBAction for the barbutton item in storyboard like this

OR

Create a function like this and connect with bar button item


问:
how to display output of spark java application in UI
I have a Spark Java application for log mining. Currently I am reading the output from spark output files and displaying it in Excel Sheet. But I want a better UI. Can somebody help me to code a better UI for easier and better way to analyze the results of spark output. It will be helpful if I add graphs and table views.</p>

答:
One option is exposing Spark data via JDBC/ODBC as described in:

https://spark.apache.org/docs/latest/sql-programming-guide.html#distributed-sql-engine

So you can write an Application for a platform of your choice.


问:
JDBC: complains about invalid sign but seems fine
I have to use JDBC to write to a database (hibernate/ibatis is not an option) and my database is Oracle 11g.

I create the following query: insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL, 'Jack', 19,TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS'));

However my statetement.execeuteUpdate(above sql). generates an invalid sign exception.
But when I perform the query in squirrel it gets commited just fine.
Does anyone know why this is happening?

```<code>Edit:
user table:
id: number : not null
username varchar2(30) not null
age number(10) not null
creation_ts timestamp not null

Error:
ORA-00911: invalid character

Java snippet:
try
        {
            DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
            String url = "privatized";
            Connection conn = DriverManager.getConnection(url, "username", "password");

            Statement st = conn.createStatement();

            Format formatter = new SimpleDateFormat(dateTimeFormatString);
            String formattedDate = formatter.format(Calendar.getInstance(TimeZone.getDefault()).getTime());

            StringBuilder insertQuery = new StringBuilder("insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL,");
                insertQuery.append(username);
                insertQuery.append(",");
            insertQuery.append(age);
            insertQuery.append(",TO_TIMESTAMP('");
            insertQuery.append(formattedDate);
            insertQuery.append("', 'DD/MM/RR HH24/MI/SS'));");
            System.err.println(insertQuery.toString());
            st.executeUpdate(insertQuery.toString());

            conn.close();
        } catch (SQLException ex){
            System.err.println(ex.getMessage());
            System.err.println(ex.getCause().toString());
            ex.printStackTrace();
            System.out.println("=========================================");
        } catch(Exception ex) {
            System.err.println(ex.getMessage());
        }
</code>```

答:
Are you sure the value of the username variable is 'Jack' and not Jack? (the ORA-00911 error doesn't look like a typical date format error).

Also you should learn about PreparedStatement. They are more efficient, easier to read and debug and not susceptible to SQL injection.

My java is a bit rusty, but this would look something like this with a PreparedStatement:

```<code>String query = "insert into user(user_id, username, age, creation_ts) values "
              + "(seq_userid.NEXTVAL, ?, ?, ?)";

Statement st = conn.prepareStatement(query);

st.setString(1, username);
st.setInt(2, age);
st.setTimestamp(3, new java.sql.Timestamp(
                          Calendar.getInstance(
                             TimeZone.getDefault()).getTimeMillis()));

st.executeUpdate(insertQuery.toString());
</code>```

This way you don't need to convert a date to a string to get it converted back by the DB. Also you may find the statement easier to read and you will never have to worry about user's naming their account with a ' (single-quote) :)

Body:
I have to use JDBC to write to a database (hibernate/ibatis is not an option) and my database is Oracle 11g.

I create the following query: insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL, 'Jack', 19,TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS'));

However my statetement.execeuteUpdate(above sql). generates an invalid sign exception.
But when I perform the query in squirrel it gets commited just fine.
Does anyone know why this is happening?

Edit:
user table:
id: number : not null
username varchar2(30) not null
age number(10) not null
creation_ts timestamp not null

Error:
ORA-00911: invalid character

Java snippet:
try
        {
            DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
            String url = "privatized";
            Connection conn = DriverManager.getConnection(url, "username", "password");

            Statement st = conn.createStatement();

            Format formatter = new SimpleDateFormat(dateTimeFormatString);
            String formattedDate = formatter.format(Calendar.getInstance(TimeZone.getDefault()).getTime());

            StringBuilder insertQuery = new StringBuilder("insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL,");
                insertQuery.append(username);
                insertQuery.append(",");
            insertQuery.append(age);
            insertQuery.append(",TO_TIMESTAMP('");
            insertQuery.append(formattedDate);
            insertQuery.append("', 'DD/MM/RR HH24/MI/SS'));");
            System.err.println(insertQuery.toString());
            st.executeUpdate(insertQuery.toString());

            conn.close();
        } catch (SQLException ex){
            System.err.println(ex.getMessage());
            System.err.println(ex.getCause().toString());
            ex.printStackTrace();
            System.out.println("=========================================");
        } catch(Exception ex) {
            System.err.println(ex.getMessage());
        }

Body:
Are you sure the value of the username variable is 'Jack' and not Jack? (the ORA-00911 error doesn't look like a typical date format error).

Also you should learn about PreparedStatement. They are more efficient, easier to read and debug and not susceptible to SQL injection.

My java is a bit rusty, but this would look something like this with a PreparedStatement:

String query = "insert into user(user_id, username, age, creation_ts) values "
              + "(seq_userid.NEXTVAL, ?, ?, ?)";

Statement st = conn.prepareStatement(query);

st.setString(1, username);
st.setInt(2, age);
st.setTimestamp(3, new java.sql.Timestamp(
                          Calendar.getInstance(
                             TimeZone.getDefault()).getTimeMillis()));

st.executeUpdate(insertQuery.toString());

This way you don't need to convert a date to a string to get it converted back by the DB. Also you may find the statement easier to read and you will never have to worry about user's naming their account with a ' (single-quote) :)


问:
Dressing a mannequin with different items in android
I am trying to implement similar screen. Unable to add different items at proper place. I want to add shoes at the proper place.

Layout

```<code><?xml version="1.0" encoding="utf-8"?><RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:padding="0dp">

<ImageView
    android:id="@+id/imgBody"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:scaleType="fitXY"
    android:src="@drawable/dress" />

<ImageView
    android:id="@+id/imgFeet"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/imgBody"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="0dp"
    android:src="@drawable/ic_shoe1"
    android:visibility="gone" />

<ImageView
    android:id="@+id/imgFace"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="55dp"
    android:layout_marginTop="0dp"
    android:src="@drawable/ic_head"
    android:visibility="gone" />
</code>```

```<code><android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white"/>
</code>```

答:
Try to user Table layout for split a screen in two part. like below :
  Here i have use android:layout_weight="0.5" for screen size.

```<code>   <TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#EBEBEB"
    android:stretchColumns="2"
    android:weightSum="2">

    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="0.5"
            android:background="#FFFFFF"
            android:orientation="vertical">

            <!--Write your xml Right side xml code here-->

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="0.5"
            android:background="#FFFFFF">

            <!--Write your xml Left side xml code here-->

        </RelativeLayout>
    </TableRow>
</TableLayout>
</code>```

Body:
I am trying to implement similar screen. Unable to add different items at proper place. I want to add shoes at the proper place.

Layout

<?xml version="1.0" encoding="utf-8"?><RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:padding="0dp">

<ImageView
    android:id="@+id/imgBody"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:scaleType="fitXY"
    android:src="@drawable/dress" />

<ImageView
    android:id="@+id/imgFeet"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/imgBody"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="0dp"
    android:src="@drawable/ic_shoe1"
    android:visibility="gone" />

<ImageView
    android:id="@+id/imgFace"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="55dp"
    android:layout_marginTop="0dp"
    android:src="@drawable/ic_head"
    android:visibility="gone" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white"/>

Body:
Try to user Table layout for split a screen in two part. like below :
  Here i have use android:layout_weight="0.5" for screen size.

   <TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#EBEBEB"
    android:stretchColumns="2"
    android:weightSum="2">

    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="0.5"
            android:background="#FFFFFF"
            android:orientation="vertical">

            <!--Write your xml Right side xml code here-->

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="0.5"
            android:background="#FFFFFF">

            <!--Write your xml Left side xml code here-->

        </RelativeLayout>
    </TableRow>
</TableLayout>


问:
Get most common column for each column value
I want the most common letter for each number. I've tried a variety of things; not sure what's the right way.

```<code>import pandas as pd
from pandas import DataFrame, Series

original = DataFrame({
    'letter': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'},
    'number': {0: '01', 1: '01', 2: '02', 3: '02', 4: '02'}
})

expected = DataFrame({'most_common_letter': {'01': 'A', '02': 'B'}})
</code>```

Ideally I'm looking to maximize readability.

答:
Use groupby + apply + value_counts + select first index values, because values are sorted.

Last convert Series to_frame and remove index name by rename_axis:

```<code>df = original.groupby('number')['letter'] \
             .apply(lambda x: x.value_counts().index[0])
             .to_frame('most_common_letter')
             .rename_axis(None)
print (df)
   most_common_letter
01                  A
02                  B
</code>```

Similar solution:

```<code>from collections import Counter

df = original.groupby('number')['letter'] \
             .apply(lambda x: Counter(x).most_common(1)[0][0]) \
             .to_frame('most_common_letter') \
             .rename_axis(None)
print (df)
   most_common_letter
01                  A
02                  B
</code>```

Or use Series.mode:

```<code>df = original.groupby('number')['letter'] \
             .apply(lambda x: x.mode()[0][0])
             .to_frame('most_common_letter')
             .rename_axis(None)
print (df)
   most_common_letter
01                  A
02                  B
</code>```

Body:
I want the most common letter for each number. I've tried a variety of things; not sure what's the right way.

import pandas as pd
from pandas import DataFrame, Series

original = DataFrame({
    'letter': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'},
    'number': {0: '01', 1: '01', 2: '02', 3: '02', 4: '02'}
})

expected = DataFrame({'most_common_letter': {'01': 'A', '02': 'B'}})

Ideally I'm looking to maximize readability.

Body:
Use groupby + apply + value_counts + select first index values, because values are sorted.

Last convert Series to_frame and remove index name by rename_axis:

df = original.groupby('number')['letter'] \
             .apply(lambda x: x.value_counts().index[0])
             .to_frame('most_common_letter')
             .rename_axis(None)
print (df)
   most_common_letter
01                  A
02                  B

Similar solution:

from collections import Counter

df = original.groupby('number')['letter'] \
             .apply(lambda x: Counter(x).most_common(1)[0][0]) \
             .to_frame('most_common_letter') \
             .rename_axis(None)
print (df)
   most_common_letter
01                  A
02                  B

Or use Series.mode:

df = original.groupby('number')['letter'] \
             .apply(lambda x: x.mode()[0][0])
             .to_frame('most_common_letter')
             .rename_axis(None)
print (df)
   most_common_letter
01                  A
02                  B


问:
Update multiple column and row using temp table
I'm trying to update multiple column value on condition, but it's updating only single column. I'm not able to figure out why it's not updating all columns.

This is my SP.

```<code>CREATE PROCEDURE [dbo].[MIC_UpdateIdeaInline]
(
@UpdatedBy int,
@UpdatedOn Datetime,
@UpdateRecords [UpdateIdeaInline] READONLY
)
as
BEGIN
UPDATE MI
        SET MI.IsPortalShare= CASE WHEN ColoumnName = 'IsPortalShare' THEN CAST(ur.ColValue as BIT) ELSE IsPortalShare END
        ,MI.Validity= CASE WHEN ColoumnName = 'Validity' THEN CAST(ur.ColValue as BIT) ELSE Validity END
        ,MI.DeadLine= CASE WHEN ColoumnName = 'DeadLine' THEN CAST(ur.ColValue as datetime) ELSE DeadLine END
        ,MI.UpdatedBy=@UpdatedBy, MI.UpdatedOn=@UpdatedOn
from [MIC_Idea] MI
Join @UpdateRecords ur ON MI.Id=ur.IdeaId
SELECT 1
END
</code>```

These are my parameter while calling SP.

```<code>declare @p3 dbo.UpdateIdeaInline
insert into @p3 values(N'15',N'Validity',N'1')
insert into @p3 values(N'15',N'DeadLine',N'15-Jun-2017')
insert into @p3 values(N'14',N'Validity',N'0')
insert into @p3 values(N'14',N'DeadLine',N'15-Jun-2017')

exec MIC_UpdateIdeaInline @UpdatedBy=1,@UpdatedOn='2017-06-06 21:45:19.863',@UpdateRecords=@p3
go
</code>```

UpdateIdeaInline is table type. It's first column contain

Id

ColumnName

ColumnValue

As You can see I want to update Column (validity and DeadLine) for same ids 14 and 15. But it's only updating validity column.

答:
That's because your update is in single atomic transaction. Update statement updates the table twice, because ID is duplicated in UpdateRecords table. So on the second update it cannot read the value updated by the first update.

Example:
You have values 10 and 15.

Now you issue a single UPDATE joining with UpdateRecord table which has two identical IDs, but each ID for different column.

E.g. UpdateRecord has
'Col1', 30
'Col2', 40

After first update:

10-->30  (pending)

15-->15  (pending)

After second update:

10-->10  (pending)

15-->40  (pending)

After transaction is committed:

10-->10

15-->40

Body:
I'm trying to update multiple column value on condition, but it's updating only single column. I'm not able to figure out why it's not updating all columns.

This is my SP.

CREATE PROCEDURE [dbo].[MIC_UpdateIdeaInline]
(
@UpdatedBy int,
@UpdatedOn Datetime,
@UpdateRecords [UpdateIdeaInline] READONLY
)
as
BEGIN
UPDATE MI
        SET MI.IsPortalShare= CASE WHEN ColoumnName = 'IsPortalShare' THEN CAST(ur.ColValue as BIT) ELSE IsPortalShare END
        ,MI.Validity= CASE WHEN ColoumnName = 'Validity' THEN CAST(ur.ColValue as BIT) ELSE Validity END
        ,MI.DeadLine= CASE WHEN ColoumnName = 'DeadLine' THEN CAST(ur.ColValue as datetime) ELSE DeadLine END
        ,MI.UpdatedBy=@UpdatedBy, MI.UpdatedOn=@UpdatedOn
from [MIC_Idea] MI
Join @UpdateRecords ur ON MI.Id=ur.IdeaId
SELECT 1
END

These are my parameter while calling SP.

declare @p3 dbo.UpdateIdeaInline
insert into @p3 values(N'15',N'Validity',N'1')
insert into @p3 values(N'15',N'DeadLine',N'15-Jun-2017')
insert into @p3 values(N'14',N'Validity',N'0')
insert into @p3 values(N'14',N'DeadLine',N'15-Jun-2017')

exec MIC_UpdateIdeaInline @UpdatedBy=1,@UpdatedOn='2017-06-06 21:45:19.863',@UpdateRecords=@p3
go

UpdateIdeaInline is table type. It's first column contain

Id

ColumnName

ColumnValue

As You can see I want to update Column (validity and DeadLine) for same ids 14 and 15. But it's only updating validity column.


答:
I would suggest to keep all the data in a configuration object and then iterate through that data when performing checks and assignments.

I would create a separate class to hold data for each book: name, picture file name and check box items string array.

Then I would create a list of that object and assign all the data manually on form initialization.

After that, in SelectedIndexChanged event handler, I would iterate (for loop) on each item and check if the book name matched. If it did, then I would use data from that object and then break; the loop.

Title: wondering if there is an efficient way to shorten this code

Body:
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.


问:
Display checkbox data
With Laravel Framework

I saved this checkbox to Mysql in one column

```<code><input type="checkbox" name="Sun" id="Sun" value="true"> Sun
<input type="checkbox" name="Mon" id="Mon" value="true"> Mon
<input type="checkbox" name="Thu" id="Thu" value="true"> Thu
<input type="checkbox" name="Wed" id="Wed" value="true"> Wed
<input type="checkbox" name="Thur" id="Thur" value="true"> Thur
<input type="checkbox" name="Fri" id="Fri" value="true"> Fri
<input type="checkbox" name="Sat" id="Sat" value="true"> Sat`
</code>```

And I display it in a table.It's displayed like1,0,1,0,0,0,1

Here's pic of that output

But I want to display if the value is equal to 1 like

Sun,Thu,Sat

How can I display like that?

答:
When we are working with checkboxes then we can use string value instead of true/false values. Like

```<code><input type="checkbox" name="Sun" id="Sun" value="Sun"> Sun
<input type="checkbox" name="Mon" id="Mon" value="Mon"> Mon
<input type="checkbox" name="Thu" id="Thu" value="Thu"> Thu
<input type="checkbox" name="Wed" id="Wed" value="Wed"> Wed
<input type="checkbox" name="Thur" id="Thur" value="Thur"> Thur
<input type="checkbox" name="Fri" id="Fri" value="Fri"> Fri
<input type="checkbox" name="Sat" id="Sat" value="Sat"> Sat`
</code>```

And when you will submit the form, then you can see which checkboxes you checked will show you value and other will not show you value.

Check below example and it is working fine.

```<code><?php

    if(isset($_POST) && !empty($_POST))
    {
        echo "```";
        print_r($_POST);
        echo "```";
        exit;
    }
?>

<form method="post">
    <input type="checkbox" name="Sun" id="Sun" value="Sun"> Sun
    <input type="checkbox" name="Mon" id="Mon" value="Mon"> Mon
    <input type="checkbox" name="Thu" id="Thu" value="Thu"> Thu
    <input type="checkbox" name="Wed" id="Wed" value="Wed"> Wed
    <input type="checkbox" name="Thur" id="Thur" value="Thur"> Thur
    <input type="checkbox" name="Fri" id="Fri" value="Fri"> Fri
    <input type="checkbox" name="Sat" id="Sat" value="Sat"> Sat
    <input type="submit" value="submit">

</form>
</code>```

Try this, I think this will help you.

Title: Display checkbox data

Body:
With Laravel Framework

I saved this checkbox to Mysql in one column

<input type="checkbox" name="Sun" id="Sun" value="true"> Sun
<input type="checkbox" name="Mon" id="Mon" value="true"> Mon
<input type="checkbox" name="Thu" id="Thu" value="true"> Thu
<input type="checkbox" name="Wed" id="Wed" value="true"> Wed
<input type="checkbox" name="Thur" id="Thur" value="true"> Thur
<input type="checkbox" name="Fri" id="Fri" value="true"> Fri
<input type="checkbox" name="Sat" id="Sat" value="true"> Sat`

And I display it in a table.It's displayed like1,0,1,0,0,0,1

Here's pic of that output

But I want to display if the value is equal to 1 like

Sun,Thu,Sat

How can I display like that?

Body:
When we are working with checkboxes then we can use string value instead of true/false values. Like

<input type="checkbox" name="Sun" id="Sun" value="Sun"> Sun
<input type="checkbox" name="Mon" id="Mon" value="Mon"> Mon
<input type="checkbox" name="Thu" id="Thu" value="Thu"> Thu
<input type="checkbox" name="Wed" id="Wed" value="Wed"> Wed
<input type="checkbox" name="Thur" id="Thur" value="Thur"> Thur
<input type="checkbox" name="Fri" id="Fri" value="Fri"> Fri
<input type="checkbox" name="Sat" id="Sat" value="Sat"> Sat`

And when you will submit the form, then you can see which checkboxes you checked will show you value and other will not show you value.

Check below example and it is working fine.

<?php

    if(isset($_POST) && !empty($_POST))
    {
        echo "<pre>";
        print_r($_POST);
        echo "</pre>";
        exit;
    }
?>

<form method="post">
    <input type="checkbox" name="Sun" id="Sun" value="Sun"> Sun
    <input type="checkbox" name="Mon" id="Mon" value="Mon"> Mon
    <input type="checkbox" name="Thu" id="Thu" value="Thu"> Thu
    <input type="checkbox" name="Wed" id="Wed" value="Wed"> Wed
    <input type="checkbox" name="Thur" id="Thur" value="Thur"> Thur
    <input type="checkbox" name="Fri" id="Fri" value="Fri"> Fri
    <input type="checkbox" name="Sat" id="Sat" value="Sat"> Sat
    <input type="submit" value="submit">

</form>

Try this, I think this will help you.


问:
Read every note from a MIDI file (note, velocity, length) using DryWetMidi
I'm making a C# program that should read every note from a MIDI file and get the length and the velocity of the note, but I don't know how to do that...

I'm using the DryWetMidi library, but is there some other library?

答:
Starting with the DryWetMidi 1.1.0, all you need to get notes of a MIDI file is this code:

```<code>IEnumerable<Note> notes = midiFile.GetNotes();
</code>```

The Note class contains all properties you need: NoteNumber, NoteName, Octave, Length, Time, Velocity, and OffVelocity.

To get Time as <hours,minutes,seconds> or <bars,beats>, you can use TimeAs extension method:

```<code>TempoMap tempoMap = midiFile.GetTempoMap();
MetricTimeSpan metricTime = note.TimeAs<MetricTimeSpan>(tempoMap);
BarBeatTicksTimeSpan musicalTime = note.TimeAs<BarBeatTicksTimeSpan>(tempoMap);
</code>```

For Length, you can use LengthAs extension method:

```<code>TempoMap tempoMap = midiFile.GetTempoMap();
MetricTimeSpan metricLength = note.LengthAs<MetricTimeSpan>(tempoMap);
BarBeatTimeSpan metricLength = note.LengthAs<BarBeatTimeSpan>(tempoMap);
</code>```

You can read more in the Time and length article of the library documentation.

Body:
Starting with the DryWetMidi 1.1.0, all you need to get notes of a MIDI file is this code:

IEnumerable<Note> notes = midiFile.GetNotes();

The Note class contains all properties you need: NoteNumber, NoteName, Octave, Length, Time, Velocity, and OffVelocity.

To get Time as <hours,minutes,seconds> or <bars,beats>, you can use TimeAs extension method:

TempoMap tempoMap = midiFile.GetTempoMap();
MetricTimeSpan metricTime = note.TimeAs<MetricTimeSpan>(tempoMap);
BarBeatTicksTimeSpan musicalTime = note.TimeAs<BarBeatTicksTimeSpan>(tempoMap);

For Length, you can use LengthAs extension method:

TempoMap tempoMap = midiFile.GetTempoMap();
MetricTimeSpan metricLength = note.LengthAs<MetricTimeSpan>(tempoMap);
BarBeatTimeSpan metricLength = note.LengthAs<BarBeatTimeSpan>(tempoMap);

You can read more in the Time and length article of the library documentation.


问:
Using iOS8 and later devices with Xcode
Using iOS8 and later devices with Xcode?

答:
Well you have two options:

1)Straightforward, download Xcode 9 and you are good to go.

2) You need to put DeveloperDiskImage of iOS 11 in

/Applications/Xcode8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

Put iOS 11 DiskImage

and you can find this diskImage in Xcode9 at same path in case you want to continue with XCode8

Path of iOS 11 Disk Image:

~/Applications/Xcode9.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0

```<code>NOTE: Xcode 9.0 requires a Mac running macOS Sierra 10.12.4 or later.
</code>```

Title: Using iOS8 and later devices with Xcode

Body:
Well you have two options:

1)Straightforward, download Xcode 9 and you are good to go.

2) You need to put DeveloperDiskImage of iOS 11 in

/Applications/Xcode8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

Put iOS 11 DiskImage

and you can find this diskImage in Xcode9 at same path in case you want to continue with XCode8

Path of iOS 11 Disk Image:

~/Applications/Xcode9.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0

NOTE: Xcode 9.0 requires a Mac running macOS Sierra 10.12.4 or later.


问:
Jquery form only working the first time you submit it, and not the second
I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the

```<code>$(document).ready(function(){
</code>```

But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing.
The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js

```<code>$(document).ready(function(){
$('#AddCaller').click(function(e){

    //stop the form from being submitted
    e.preventDefault();

    /* declare the variables, var error is the variable that we use on the end
    to determine if there was an error or not */
    var error = false;
    var Firstname = $('#Firstname').val();
    ...OTHER FORM FIELDS HERE

    /* in the next section we do the checking by using VARIABLE.length
    where VARIABLE is the variable we are checking (like name, email),
    length is a javascript function to get the number of characters.
    And as you can see if the num of characters is 0 we set the error
    variable to true and show the name_error div with the fadeIn effect.
    if it's not 0 then we fadeOut the div( that's if the div is shown and
    the error is fixed it fadesOut. */

    if(Firstname.length == 0){
        var error = true;
        $('#Firstname_error').fadeIn(500);
    }else{
        $('#Firstname_error').fadeOut(500);
    }
    if(Lastname.length == 0){
        var error = true;
        $('#Lastname_error').fadeIn(500);
    }else{
        $('#Lastname_error').fadeOut(500);
    }
    ...MORE CONDITIONAL STATEMENTS HERE

    //now when the validation is done we check if the error variable is false (no errors)
    if(error == false){
        //disable the submit button to avoid spamming
        //and change the button text to Sending...
        $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

        /* using the jquery's post(ajax) function and a lifesaver
        function serialize() which gets all the data from the form
        we submit it to send_email.php */
        $.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
            //and after the ajax request ends we check the text returned
            if(result == 'added'){

                 //$('#cf_submit_p').remove();
                //and show the success div with fadeIn
                $('#Add_success').fadeIn(500);
                 $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
                 document.getElementById('Firstname').value = "";
                 document.getElementById('Lastname').value = "";
                 document.getElementById('PhoneNumber').value = "";
                 document.getElementById('DefaultETA').value = "";
                 document.getElementById('Apparatus').value = "";
                 document.getElementById('DefaultLocation').value = "";

                 setTimeout(" $('#Add_success').fadeOut(500);",5000);

            }else if(result == 'alreadythere'){
                                    //checks database to see if the user is already there
                $('#Alreadythere').fadeIn(500);
                $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
            }
            else{
                //show the failed div
                $('#Add_fail').fadeIn(500);
                //reenable the submit button by removing attribute disabled and change the text back to Send The Message
                $('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');

            }
        });
    }
});
});
</code>```

Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.

Thanks for the help!

EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.

EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.

```<code><form action='addcallers.php' method='post' id='AddCaller_form'>

 <h2>Add Callers</h2>
 <p>
 First Name:
 <div id='Firstname_error' class='error'> Please Enter a First Name</div>
 <div><input type='text' name='Firstname' id='Firstname'></div>
 </p>

 <p>
 Last Name:
 <div id='Lastname_error' class='error'> Please Enter a Last Name</div>
 <div><input type='text' name='Lastname' id='Lastname'></div>
 </p>
 ...MORE FORM FIELDS HERE

 <div style="display:none;">
 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly >

 </div>
 </p>

 <p>

 <div id='Add_success' class='success'> The user has been added</div>
 <div id='Alreadythere' class='error'> That user is already in the database</div>
 <div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
 <p id='cf_submit_p'>
 <input type='submit' id='AddCaller' value='Send The Message'>
 </p>
 </form>

 </div>
</code>```

EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.

EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it

EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?

答:
Do not remove the attribute of disabled, set it to false.

This line

```<code>$('#AddCaller').removeAttr('disabled').attr(...
</code>```

should be

```<code>$('#AddCaller').attr('disabled', false).attr(...
</code>```

Body:
I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the

$(document).ready(function(){

But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing.
The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js

$(document).ready(function(){
$('#AddCaller').click(function(e){

    //stop the form from being submitted
    e.preventDefault();

    /* declare the variables, var error is the variable that we use on the end
    to determine if there was an error or not */
    var error = false;
    var Firstname = $('#Firstname').val();
    ...OTHER FORM FIELDS HERE

    /* in the next section we do the checking by using VARIABLE.length
    where VARIABLE is the variable we are checking (like name, email),
    length is a javascript function to get the number of characters.
    And as you can see if the num of characters is 0 we set the error
    variable to true and show the name_error div with the fadeIn effect.
    if it's not 0 then we fadeOut the div( that's if the div is shown and
    the error is fixed it fadesOut. */

    if(Firstname.length == 0){
        var error = true;
        $('#Firstname_error').fadeIn(500);
    }else{
        $('#Firstname_error').fadeOut(500);
    }
    if(Lastname.length == 0){
        var error = true;
        $('#Lastname_error').fadeIn(500);
    }else{
        $('#Lastname_error').fadeOut(500);
    }
    ...MORE CONDITIONAL STATEMENTS HERE

    //now when the validation is done we check if the error variable is false (no errors)
    if(error == false){
        //disable the submit button to avoid spamming
        //and change the button text to Sending...
        $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

        /* using the jquery's post(ajax) function and a lifesaver
        function serialize() which gets all the data from the form
        we submit it to send_email.php */
        $.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
            //and after the ajax request ends we check the text returned
            if(result == 'added'){

                 //$('#cf_submit_p').remove();
                //and show the success div with fadeIn
                $('#Add_success').fadeIn(500);
                 $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
                 document.getElementById('Firstname').value = "";
                 document.getElementById('Lastname').value = "";
                 document.getElementById('PhoneNumber').value = "";
                 document.getElementById('DefaultETA').value = "";
                 document.getElementById('Apparatus').value = "";
                 document.getElementById('DefaultLocation').value = "";

                 setTimeout(" $('#Add_success').fadeOut(500);",5000);

            }else if(result == 'alreadythere'){
                                    //checks database to see if the user is already there
                $('#Alreadythere').fadeIn(500);
                $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
            }
            else{
                //show the failed div
                $('#Add_fail').fadeIn(500);
                //reenable the submit button by removing attribute disabled and change the text back to Send The Message
                $('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');

            }
        });
    }
});
});

Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.

Thanks for the help!

EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.

EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.

<form action='addcallers.php' method='post' id='AddCaller_form'>

Add Callers

 First Name:

 Please Enter a First Name

<input type='text' name='Firstname' id='Firstname'>

 Last Name:

 Please Enter a Last Name

<input type='text' name='Lastname' id='Lastname'>

 ...MORE FORM FIELDS HERE

 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly >

 The user has been added

 That user is already in the database

 Sorry, don't know what happened. Try later.

 <input type='submit' id='AddCaller' value='Send The Message'>

 </form>

EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.

EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it

EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?

Body:
Do not remove the attribute of disabled, set it to false.

This line

$('#AddCaller').removeAttr('disabled').attr(...

should be

$('#AddCaller').attr('disabled', false).attr(...


问:
How to refactor this C# code
I have these functions

```<code>    public async Task<List<Machine>> GetMachines()
    {
        await Initialize();
        await SyncMachines();
        return await machineTable.ToListAsync();
    }

    public async Task InsertMachines(List<Machine> machines)
    {
        await Initialize();
        await Task.WhenAll(machines.Select(m => machineTable.InsertAsync(m)));
        await SyncMachines();
    }
</code>```

I am writing a parent class to put these functions in, such that the functions getMachines() and InsertMachines() become getObject and InsertObject where the List<Machine> can be a list of any objects, so they can return and accept any type of list

How do I declare functions like this?

答:
According to your description, I created my azure sync table class as follows, you could refer to it:

```<code>public class AzureCloudSyncTable<TModel> where TModel : class
{
    public static MobileServiceClient MobileService = new MobileServiceClient(
        "https://{your-mobile-app-name}.azurewebsites.net"
    );
    private IMobileServiceSyncTable<TModel> syncTable = MobileService.GetSyncTable<TModel>();

    #region Offline sync
    private async Task InitLocalStoreAsync()
    {
        if (!MobileService.SyncContext.IsInitialized)
        {
            var store = new MobileServiceSQLiteStore("localstore.db");
            store.DefineTable<TModel>();
            await MobileService.SyncContext.InitializeAsync(store);
        }
        await SyncAsync();
    }

    private async Task SyncAsync()
    {
        await PushAsync();
        await syncTable.PullAsync(typeof(TModel).Name, syncTable.CreateQuery());
    }

    private async Task PushAsync()
    {
        try
        {
            await MobileService.SyncContext.PushAsync();
        }
        catch (MobileServicePushFailedException ex)
        {
            if (ex.PushResult != null)
            {
                foreach (var error in ex.PushResult.Errors)
                {
                    await ResolveConflictAsync(error);
                }
            }
        }
    }

    private async Task ResolveConflictAsync(MobileServiceTableOperationError error)
    {
        //var serverItem = error.Result.ToObject<TModel>();
        //var localItem = error.Item.ToObject<TModel>();

        //// Note that you need to implement the public override Equals(TModel item)
        //// method in the Model for this to work
        //if (serverItem.Equals(localItem))
        //{
        //    // Items are the same, so ignore the conflict
        //    await error.CancelAndDiscardItemAsync();
        //    return;
        //}

        //// Client Always Wins
        //localItem.Version = serverItem.Version;
        //await error.UpdateOperationAsync(JObject.FromObject(localItem));

        // Server Always Wins
        //await error.CancelAndDiscardItemAsync();
    }
    #endregion

    #region public methods
    public async Task<List<TModel>> GetAll()
    {
        await InitLocalStoreAsync();
        await SyncAsync();
        return await syncTable.ToListAsync();
    }

    public async Task Insert(List<TModel> items)
    {
        await InitLocalStoreAsync();
        await Task.WhenAll(items.Select(item => syncTable.InsertAsync(item)));
        await PushAsync();
    }
    #endregion
}
</code>```

Additionally, for more details about Handling Conflict Resolution, you could refer to adrian hall's book here.

Title: How to refactor this C# code

Body:
I have these functions

    public async Task<List<Machine>> GetMachines()
    {
        await Initialize();
        await SyncMachines();
        return await machineTable.ToListAsync();
    }

    public async Task InsertMachines(List<Machine> machines)
    {
        await Initialize();
        await Task.WhenAll(machines.Select(m => machineTable.InsertAsync(m)));
        await SyncMachines();
    }

I am writing a parent class to put these functions in, such that the functions getMachines() and InsertMachines() become getObject and InsertObject where the List<Machine> can be a list of any objects, so they can return and accept any type of list

How do I declare functions like this?

Body:
According to your description, I created my azure sync table class as follows, you could refer to it:

public class AzureCloudSyncTable<TModel> where TModel : class
{
    public static MobileServiceClient MobileService = new MobileServiceClient(
        "https://{your-mobile-app-name}.azurewebsites.net"
    );
    private IMobileServiceSyncTable<TModel> syncTable = MobileService.GetSyncTable<TModel>();

    #region Offline sync
    private async Task InitLocalStoreAsync()
    {
        if (!MobileService.SyncContext.IsInitialized)
        {
            var store = new MobileServiceSQLiteStore("localstore.db");
            store.DefineTable<TModel>();
            await MobileService.SyncContext.InitializeAsync(store);
        }
        await SyncAsync();
    }

    private async Task SyncAsync()
    {
        await PushAsync();
        await syncTable.PullAsync(typeof(TModel).Name, syncTable.CreateQuery());
    }

    private async Task PushAsync()
    {
        try
        {
            await MobileService.SyncContext.PushAsync();
        }
        catch (MobileServicePushFailedException ex)
        {
            if (ex.PushResult != null)
            {
                foreach (var error in ex.PushResult.Errors)
                {
                    await ResolveConflictAsync(error);
                }
            }
        }
    }

    private async Task ResolveConflictAsync(MobileServiceTableOperationError error)
    {
        //var serverItem = error.Result.ToObject<TModel>();
        //var localItem = error.Item.ToObject<TModel>();

        //// Note that you need to implement the public override Equals(TModel item)
        //// method in the Model for this to work
        //if (serverItem.Equals(localItem))
        //{
        //    // Items are the same, so ignore the conflict
        //    await error.CancelAndDiscardItemAsync();
        //    return;
        //}

        //// Client Always Wins
        //localItem.Version = serverItem.Version;
        //await error.UpdateOperationAsync(JObject.FromObject(localItem));

        // Server Always Wins
        //await error.CancelAndDiscardItemAsync();
    }
    #endregion

    #region public methods
    public async Task<List<TModel>> GetAll()
    {
        await InitLocalStoreAsync();
        await SyncAsync();
        return await syncTable.ToListAsync();
    }

    public async Task Insert(List<TModel> items)
    {
        await InitLocalStoreAsync();
        await Task.WhenAll(items.Select(item => syncTable.InsertAsync(item)));
        await PushAsync();
    }
    #endregion
}

Additionally, for more details about Handling Conflict Resolution, you could refer to adrian hall's book here.