问:
Refreshing a react router page that has a dynamic url/params
I have several components displayed with react router that have dynamic url paths. An example path I have is

<Route path="/newproject/:id" onEnter={checkSesh} component= {ProjectDetails} />

When entering this component, I have a componentWillMount function that extract the id part of the url so that I can get the info for the correct project and render it on the ProjectDetails component.

```<code>  componentWillMount() {
    var id = this.props.router.params.id
    this.props.teamDetails(id);
  }
</code>```

this.props.teamDetails(id) this calls a redux action creator that will make an axios request to an express route that will get the project info from the database.

```<code>export function teamDetails(id) {
    return function(dispatch) {
    axios.get('/getteaminfo/' + id)
      .then(res => {
        dispatch({ type: "SET_TEAM_DETAILS", payload: {
                teamInfo: res.data.teamInfo,
                admin: res.data.admin,
                adminID: res.data.teamInfo.teamAdmin,
                teamMembers: res.data.teamInfo.teamMembers
            }
        })

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

everything works fine upon visiting the page after already being logged in etc. But when I refresh the page /newproject/:id, i get an error Uncaught SyntaxError: Unexpected token <. An example url in my browser looks like http://localhost:3000/newproject/58df1ae6aabc4916206fdaae. When I refresh this page, I get that error. The error is complaining about my <!DOCTYPE html> tag at the very top of my index.html for some reason. This index.html is where all of React is being rendered.

答:
When page is refreshed store state is not preserved. Make sure the state is not important to load the page, or at least initialized properly every time.

For e.g. login information if saved in store and not on browser with localStorage or cookies etc.. then on refresh, the error will come when trying to access /getteaminfo/ route through axios. The response will have error html and it can't be parsed by js.

Please check your web console on for more information. You can use chrome extension like https://github.com/zalmoxisus/redux-devtools-extension which will show your store and etc..

Make sure to check what /getteaminfo/ gives with id is not passed.

Also, make sure on your server side, did you route requests to react-router path through something like this?

e.g. express js,

```<code>app.get('*', function response(req, res) {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
</code>```

be sure to sendFile with the real location of index.html

Body:
I have several components displayed with react router that have dynamic url paths. An example path I have is

<Route path="/newproject/:id" onEnter={checkSesh} component= {ProjectDetails} />

When entering this component, I have a componentWillMount function that extract the id part of the url so that I can get the info for the correct project and render it on the ProjectDetails component.

  componentWillMount() {
    var id = this.props.router.params.id
    this.props.teamDetails(id);
  }

this.props.teamDetails(id) this calls a redux action creator that will make an axios request to an express route that will get the project info from the database.

export function teamDetails(id) {
    return function(dispatch) {
    axios.get('/getteaminfo/' + id)
      .then(res => {
        dispatch({ type: "SET_TEAM_DETAILS", payload: {
                teamInfo: res.data.teamInfo,
                admin: res.data.admin,
                adminID: res.data.teamInfo.teamAdmin,
                teamMembers: res.data.teamInfo.teamMembers
            }
        })

      });
    }
}

everything works fine upon visiting the page after already being logged in etc. But when I refresh the page /newproject/:id, i get an error Uncaught SyntaxError: Unexpected token <. An example url in my browser looks like http://localhost:3000/newproject/58df1ae6aabc4916206fdaae. When I refresh this page, I get that error. The error is complaining about my <!DOCTYPE html> tag at the very top of my index.html for some reason. This index.html is where all of React is being rendered.

Body:
When page is refreshed store state is not preserved. Make sure the state is not important to load the page, or at least initialized properly every time.

For e.g. login information if saved in store and not on browser with localStorage or cookies etc.. then on refresh, the error will come when trying to access /getteaminfo/ route through axios. The response will have error html and it can't be parsed by js.

Please check your web console on for more information. You can use chrome extension like https://github.com/zalmoxisus/redux-devtools-extension which will show your store and etc..

Make sure to check what /getteaminfo/ gives with id is not passed.

Also, make sure on your server side, did you route requests to react-router path through something like this?

e.g. express js,

app.get('*', function response(req, res) {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

be sure to sendFile with the real location of index.html


来源: stackexchange

问:
Spark reading in fixed width file
I'm new to Spark (less than 1 month!)  and am working with a flat file raw data input that is fixed width.  I am using sqlContext to read in the file using com.databricks.spark.csv and then using .withColumn to substring the rows based on the set widths.

```<code>    rawData.withColumn("ID"), trim(rawData['c0'].substr(1,8)))
</code>```

The issue I am encountering is that the last field is of variable width.  It has a fixed start point but variable number of 'sets' of data that are like 20 chars wide.  So for example

```<code>Row 1  A 1243 B 42225 C 23213
Row 2  A 12425
Row 3  A 111 B 2222 C 3 D 4 E55555
</code>```

I need to eventually read in those variable fields, just pull out the first character of each group in the variable width column, and then transpose so that the output looks like:

```<code>Row 1 A
Row 1 B
Row 1 C
Row 2 A
...
Row 3 D
Row 3 E
</code>```

I've read in the fixed width columns I need but I am stuck at the variable width field.

答:
zipWithIndex and explode can help to transpose the data into rows of each element</p>

```<code>sc.textFile ("csv.data").map(_.split("\\s+")).zipWithIndex.toDF("dataArray","rowId").select ($"rowId",explode($"dataArray")).show(false)

+-----+------+
|rowId|col   |
+-----+------+
|0    |A     |
|0    |1243  |
|0    |B     |
|0    |42225 |
|0    |C     |
|0    |23213 |
|1    |A     |
|1    |12425 |
|2    |A     |
|2    |111   |
</code>```

ContentLicense: CC BY-SA 3.0

Title: Spark reading in fixed width file

Body:
I'm new to Spark (less than 1 month!)  and am working with a flat file raw data input that is fixed width.  I am using sqlContext to read in the file using com.databricks.spark.csv and then using .withColumn to substring the rows based on the set widths.

    rawData.withColumn("ID"), trim(rawData['c0'].substr(1,8)))

The issue I am encountering is that the last field is of variable width.  It has a fixed start point but variable number of 'sets' of data that are like 20 chars wide.  So for example

Row 1  A 1243 B 42225 C 23213
Row 2  A 12425
Row 3  A 111 B 2222 C 3 D 4 E55555

I need to eventually read in those variable fields, just pull out the first character of each group in the variable width column, and then transpose so that the output looks like:

Row 1 A
Row 1 B
Row 1 C
Row 2 A
...
Row 3 D
Row 3 E

I've read in the fixed width columns I need but I am stuck at the variable width field.

Body:
zipWithIndex and explode can help to transpose the data into rows of each element

sc.textFile ("csv.data").map(_.split("\\s+")).zipWithIndex.toDF("dataArray","rowId").select ($"rowId",explode($"dataArray")).show(false)

+-----+------+
|rowId|col   |
+-----+------+
|0    |A     |
|0    |1243  |
|0    |B     |
|0    |42225 |
|0    |C     |
|0    |23213 |
|1    |A     |
|1    |12425 |
|2    |A     |
|2    |111   |


问:
How to make a JButton unclickable after clicking on it?
Here's my code :

```<code>for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();

            panel_1.add(button);
     }
 }

    button.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            //If Button is clicked, make the button unclickable
            if(button == (JButton)e.getSource())
            {
                button.setEnabled(false);

            }
        }

    });
</code>```

I want to make any JButton I click from this 10 x 10 grid button layout unclickable; however, this method only makes no other that the right button unclickable, What's wrong? I have put the ActionListener outside the for-Loop that is responsible for making the buttons. I don't know what's going on.

Here's what it looks like :

Edit: bsd code works. Add ActionListener before adding the buttons or something along those lines.

答:
Since you want to disable all buttons in your panel. The button action listener should be inside the for loop.</p>

```<code>button = new JButton();
button.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        //If Button is clicked, make the button unclickable
        if(button == (JButton)e.getSource())
        {
            button.setEnabled(false);

        }
    }

});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's my code :

for(int row = 0; row < 10; row++)
{
    for(int col = 0; col < 10; col++)
    {
            button = new JButton();

            panel_1.add(button);
     }
 }

    button.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            //If Button is clicked, make the button unclickable
            if(button == (JButton)e.getSource())
            {
                button.setEnabled(false);

            }
        }

    });

I want to make any JButton I click from this 10 x 10 grid button layout unclickable; however, this method only makes no other that the right button unclickable, What's wrong? I have put the ActionListener outside the for-Loop that is responsible for making the buttons. I don't know what's going on.

Here's what it looks like :

Edit: bsd code works. Add ActionListener before adding the buttons or something along those lines.

Body:
Since you want to disable all buttons in your panel. The button action listener should be inside the for loop.

button = new JButton();
button.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        //If Button is clicked, make the button unclickable
        if(button == (JButton)e.getSource())
        {
            button.setEnabled(false);

        }
    }

});


问:
Set table view into editing mode
I have a UITableView in a UIViewController and have added an edit button from code rather than IB. This comes with UITableViewControllers but not UIVCs. How can I get this button to put the table view into editing mode in swift? Thanks in advance for any help.

```<code>class WordsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate  {
  override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.rightBarButtonItem = self.editButtonItem()
  }

  func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
  }
}
</code>```

答:
Swift 3.0 version of njuri post:</p>

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    PackageNameLabel.text = detailPackageName
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PackageDetailsTableViewController.editButtonPressed))

}

func editButtonPressed(){
    tableView.setEditing(!tableView.isEditing, animated: true)
    if tableView.isEditing == true{
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PackageDetailsTableViewController.editButtonPressed))
    }else{
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PackageDetailsTableViewController.editButtonPressed))
    }
}
</code>```

Title: Set table view into editing mode

Body:
I have a UITableView in a UIViewController and have added an edit button from code rather than IB. This comes with UITableViewControllers but not UIVCs. How can I get this button to put the table view into editing mode in swift? Thanks in advance for any help.

class WordsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate  {
  override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.rightBarButtonItem = self.editButtonItem()
  }

  func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
  }
}

Body:
Swift 3.0 version of njuri post:

override func viewDidLoad() {
    super.viewDidLoad()

    PackageNameLabel.text = detailPackageName
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PackageDetailsTableViewController.editButtonPressed))

}

func editButtonPressed(){
    tableView.setEditing(!tableView.isEditing, animated: true)
    if tableView.isEditing == true{
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PackageDetailsTableViewController.editButtonPressed))
    }else{
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PackageDetailsTableViewController.editButtonPressed))
    }
}


问:
Is there a more efficient method to call the Hacker News API?
I am trying to find karma (points) of each Hacker News user using the official API. I am new to programming.

The following is the code snippet I have written to get karma of one specific user. There are close to 300k user accounts on HN.

```<code>var request = require("request");

request(
    "https://hacker-news.firebaseio.com/v0/user/pg.json",

    function (error, response, body) {
        if (!error && response.statusCode === 200) {
        console.log(JSON.parse(body).karma);
    }
});
</code>```

I ran this code, but it is not fast. Is there a better way to do this?

答:
There is a faster way. Use the following API endpoint:

```<code>https://hacker-news.firebaseio.com/v0/user/${username}/karma.json
</code>```

For comparison, here are the elapsed times for the respective calls:

```<code>/v0/user/pg.json: 9.560ms
/v0/user/pg/karma.json: 3.061ms
</code>```

Body:
I am trying to find karma (points) of each Hacker News user using the official API. I am new to programming.

The following is the code snippet I have written to get karma of one specific user. There are close to 300k user accounts on HN.

var request = require("request");

request(
    "https://hacker-news.firebaseio.com/v0/user/pg.json",

    function (error, response, body) {
        if (!error && response.statusCode === 200) {
        console.log(JSON.parse(body).karma);
    }
});

I ran this code, but it is not fast. Is there a better way to do this?

Body:
There is a faster way. Use the following API endpoint:

https://hacker-news.firebaseio.com/v0/user/${username}/karma.json

For comparison, here are the elapsed times for the respective calls:

/v0/user/pg.json: 9.560ms
/v0/user/pg/karma.json: 3.061ms


问:
qsort won't sort dynamically allocated array of structs
I have a struct

```<code>struct info {
    char firstName[100];
    char lastName[100];
    char companyName[100];
    char email[100];
    unsigned long phoneNumber;
};
</code>```

which is stored in the file compareElements.h

I read in a set of values into a dynamically allocated array of structs called bptr.

my comparePtr points to this function.

```<code>#include <string.h>
#include "compareElements.h"
int compareNameAscending (const void *a, const void *b) {

    struct info *part1 = (struct info *) a;
    struct info *part2 = (struct info *) b;

    if(part1 -> lastName[0] != '\0' && part2 -> lastName[0] != '\0') {
        return (strcmp(part1 -> lastName , part2 -> lastName));
    }
    if (part1 -> lastName[0] == '\0' && part2 -> lastName[0] != '\0') {
        return (strcmp(part1 -> companyName , part2 -> lastName));
    }

    if (part1 -> lastName[0] != '\0' && part2 -> lastName[0] == '\0') {
        return (strcmp(part1 -> lastName, part2 -> companyName));
    }

    if (part1 -> lastName[0] == '\0' && part2 -> lastName[0] == '\0') {
        return (strcmp(part1 -> companyName, part2 -> companyName));
    }

}
</code>```

In the main function I have

```<code>comparePtr = &compareNameAscending
</code>```

The problem is that not all structs need to have a lastName and companyName only one of the two. So I want to sort by last name, and if they don't have a last name I'll sort by company name. The problem is that my qsort call doesn't ever actually change the order of the struct it just spits out the original.
This is the qsort call.

```<code>qsort(bptr, i, sizeof(struct info), comparePtr);
</code>```

答:
I suppose you have problem in initialization of your code,
not how to use it, here simplified version of your code that works fine:</p>

```<code>#include <string.h>
#include <stdlib.h>
#include <stdio.h>

struct info {
    char lastName[100];
    char companyName[100];
};

int compareNameAscending (const void *a, const void *b) {

    const struct info *part1 = a;
    const struct info *part2 = b;

    const char *s1 = strcmp(part1->lastName, "") == 0 ?
        part1->companyName : part1->lastName;
    const char *s2 = strcmp(part2->lastName, "") == 0 ?
        part2->companyName : part2->lastName;

    return strcmp(s1, s2);
}

int main() {
    struct info bptr[2];
    strcpy(bptr[0].lastName, "");
    strcpy(bptr[0].companyName, "Foo");
    strcpy(bptr[1].lastName, "Boo");
    strcpy(bptr[1].companyName, "");
    qsort(bptr, sizeof(bptr) / sizeof(bptr[0]), sizeof(struct info), compareNameAscending);

    size_t i;
    for (i = 0; i < sizeof(bptr) / sizeof(bptr[0]); ++i) {
        printf("company %s, name %s\n", bptr[i].companyName, bptr[i].lastName);
    }
}
</code>```

Body:
I have a struct

struct info {
    char firstName[100];
    char lastName[100];
    char companyName[100];
    char email[100];
    unsigned long phoneNumber;
};

which is stored in the file compareElements.h

I read in a set of values into a dynamically allocated array of structs called bptr.

my comparePtr points to this function.

#include <string.h>
#include "compareElements.h"
int compareNameAscending (const void *a, const void *b) {

    struct info *part1 = (struct info *) a;
    struct info *part2 = (struct info *) b;

    if(part1 -> lastName[0] != '\0' && part2 -> lastName[0] != '\0') {
        return (strcmp(part1 -> lastName , part2 -> lastName));
    }
    if (part1 -> lastName[0] == '\0' && part2 -> lastName[0] != '\0') {
        return (strcmp(part1 -> companyName , part2 -> lastName));
    }

    if (part1 -> lastName[0] != '\0' && part2 -> lastName[0] == '\0') {
        return (strcmp(part1 -> lastName, part2 -> companyName));
    }

    if (part1 -> lastName[0] == '\0' && part2 -> lastName[0] == '\0') {
        return (strcmp(part1 -> companyName, part2 -> companyName));
    }

}

In the main function I have

comparePtr = &compareNameAscending

The problem is that not all structs need to have a lastName and companyName only one of the two. So I want to sort by last name, and if they don't have a last name I'll sort by company name. The problem is that my qsort call doesn't ever actually change the order of the struct it just spits out the original.
This is the qsort call.

qsort(bptr, i, sizeof(struct info), comparePtr);

Body:
I suppose you have problem in initialization of your code,
not how to use it, here simplified version of your code that works fine:

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

struct info {
    char lastName[100];
    char companyName[100];
};

int compareNameAscending (const void *a, const void *b) {

    const struct info *part1 = a;
    const struct info *part2 = b;

    const char *s1 = strcmp(part1->lastName, "") == 0 ?
        part1->companyName : part1->lastName;
    const char *s2 = strcmp(part2->lastName, "") == 0 ?
        part2->companyName : part2->lastName;

    return strcmp(s1, s2);
}

int main() {
    struct info bptr[2];
    strcpy(bptr[0].lastName, "");
    strcpy(bptr[0].companyName, "Foo");
    strcpy(bptr[1].lastName, "Boo");
    strcpy(bptr[1].companyName, "");
    qsort(bptr, sizeof(bptr) / sizeof(bptr[0]), sizeof(struct info), compareNameAscending);

    size_t i;
    for (i = 0; i < sizeof(bptr) / sizeof(bptr[0]); ++i) {
        printf("company %s, name %s\n", bptr[i].companyName, bptr[i].lastName);
    }
}


问:
mongodb v3.2 can't run in mac
I have a mac running El Capitan 10.11 with node.js v6.9.1.
I am trying to install mongodb 3.2 with homebrew.  It seems to install but when I run mongod I get this error:

```<code>Found an invalid index { v: 2, key: { version: 1 }, name:
"incompatible_with_version_32",ns: "admin.system.version" } on the
admin.system.version collection: this version of mongod cannot
build new indexes of version number 2
</code>```

I thought it might be because I had another version of mongodb before, so I uninstalled all packages previously downloaded and verified with 'brew list'.

答:
this version of mongod cannot build new indexes of version number 2

It looks like you previously installed MongoDB 3.4 and created some data files using new features which are not backward compatible with MongoDB 3.2. MongoDB 3.4 introduced v:2 indexes which support language-specific collation.

I thought it might be because I had another version of mongodb before, so I uninstalled all packages previously downloaded and verified with 'brew list'.

Uninstalling a Homebrew package generally does not remove files that weren't specified in the package formula (or directories that were specified but now have additional files). This intentionally leaves your MongoDB dbPath intact so package updates do not affect your data.

Any idea what Im doing wrong here?

There are several approaches you can take to resolve this issue:

Install a MongoDB 3.4 server instead of 3.2.

Follow the documented steps to downgrade MongoDB 3.4 to 3.2. This will require using MongoDB 3.4 to remove incompatible features from your data files.

If the previous data in your dbPath is not important (e.g. development/test data that can be recreated), move all files in your dbPath to a new location so your 3.2 server starts with an empty data directory. The default dbPath for Homebrew (assuming you are starting/stopping MongoDB as a service) will be /usr/local/var/mongodb.

Title: mongodb v3.2 can't run in mac

Body:
I have a mac running El Capitan 10.11 with node.js v6.9.1.
I am trying to install mongodb 3.2 with homebrew.  It seems to install but when I run mongod I get this error:

Found an invalid index { v: 2, key: { version: 1 }, name:
"incompatible_with_version_32",ns: "admin.system.version" } on the
admin.system.version collection: this version of mongod cannot
build new indexes of version number 2

I thought it might be because I had another version of mongodb before, so I uninstalled all packages previously downloaded and verified with 'brew list'.


问:
MongoDB How to copy index definitions from one collection to another?
I know there's a way to do db.collection.getIndexes() Which will list all the indexes defined for a collection. Is there a way to copy and create those index definitions to another collection?

There's a lot of them and I don't want to do them one by one.

regarding the duplicated question comment: I do not wish to copy a collection. I wish to export indexes in a format that I can apply to another collection.

答:
For example I have one existing user collection with indexes _id_, name_1, email_1 and website_1

Then I have another collection called usertest, I want to copy indexes from user collection to usertest collection. The following commands works for this scenario:

Copy both index key and index options

```<code>var indexes = db.user.getIndexes();

indexes.forEach(function(index){
    delete index.v;
    delete index.ns;
    var key = index.key;
    delete index.key
    var options = [];
    for (var option in index) {
        options.push(index[option]);
    }
   db.usertest.createIndex(key, options);
});
</code>```

Copy index key only (batch processing)

```<code>var indexKeys = db.user.getIndexKeys();
db.usertest.createIndexes(indexKeys);
</code>```

Hope this will be helpful. Here's the doc: createIndexes

Body:
For example I have one existing user collection with indexes _id_, name_1, email_1 and website_1

Then I have another collection called usertest, I want to copy indexes from user collection to usertest collection. The following commands works for this scenario:

Copy both index key and index options

var indexes = db.user.getIndexes();

indexes.forEach(function(index){
    delete index.v;
    delete index.ns;
    var key = index.key;
    delete index.key
    var options = [];
    for (var option in index) {
        options.push(index[option]);
    }
   db.usertest.createIndex(key, options);
});

Copy index key only (batch processing)

var indexKeys = db.user.getIndexKeys();
db.usertest.createIndexes(indexKeys);

Hope this will be helpful. Here's the doc: createIndexes


问:
How to use paintComponent in Java to paint multiple things, but rotate one?
I'm making a program in Java for my CS class. My teacher has little experience with graphics programing in Java so I've turned to you. I'm currently using the paintComponent method of my main panel to draw two things, one, a rectangle (my cannon, possibly replaced with a image later), and two, a .png file of a cannon ball. I use the Graphics g (which I convert to Graphics2D) to paint the cannon and Ball on to the screen. I then rotate, but, the cannon and ball rotate, not just the cannon. Any tips, suggestions, or helpful tutorials are greatly appreciated.

Here is my code (the commented out links are where I got certain code, ignore them):

```<code>    package Cannon;

import java.awt.geom.Point2D;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class NewMain{

public static void main(String[] args) {
FraMainWindow frame = new FraMainWindow();
}
}

class FraMainWindow extends JFrame {
DrawCannon pnlCannon = new DrawCannon();
ButtonPannel pnlButtons = new ButtonPannel();
public FraMainWindow() {
this.setDefaultCloseOperation(JFrame.EXI…
this.setTitle("Super Mario Cannon Bro's");
this.setSize(900, 550);
this.setLayout(new BorderLayout());
this.add(pnlCannon, BorderLayout.CENTER);
this.add(pnlButtons, BorderLayout.SOUTH);
MouseMovement mouseMove = new MouseMovement();
MouseAction mouseClick = new MouseAction();
pnlCannon.addMouseMotionListener(mouseMo…
pnlCannon.addMouseListener(mouseClick);
FireButton actnFire = new FireButton();
pnlButtons.btnFire.addActionListener(act…
this.setVisible(true);
}

public class DrawCannon extends JPanel{
Rectangle.Float rectCannon = new Rectangle.Float(30, 450, 50, 10);
Image imgBall=new ImageIcon("ball.png").getImage();
double dAngle = 0;
boolean isFired = false;
public void addCannonBall(){
isFired=true;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_… RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_… RenderingHints.VALUE_RENDER_QUALITY);//A… Aliasing from http://www.java2s.com/Code/Java/2D-Graph…
g2d.rotate(0 - dAngle, rectCannon.getX(), rectCannon.getY() + 5);
g2d.fill(rectCannon);
if(isFired){
g2d.drawImage(imgBall, 0, 0, null);
}
//Dimension size = getSize();
}
}

public class ButtonPannel extends JPanel {
JButton btnFire = new JButton("Fire!");
ButtonPannel() {
this.add(btnFire);
}
}

public class FireButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
pnlCannon.addCannonBall();
System.out.println("Fire ZE MISSILES");
}
}
public class MouseMovement implements MouseMotionListener {

public void mouseDragged(MouseEvent e) {
double dBase, dHeight, dAngle;
dBase = e.getX() - pnlCannon.rectCannon.getX();
dHeight = pnlCannon.rectCannon.getY() - 5 - e.getY() + 10;
dAngle = Math.atan2(dHeight, dBase);
pnlCannon.dAngle = dAngle;
pnlCannon.repaint();
}//http://download.oracle.com/javase/tutori…

public void mouseMoved(MouseEvent e) {
}
}

public class MouseAction implements MouseListener {

public void mousePressed(MouseEvent e) {
double dBase, dHeight, dAngle;
dBase = e.getX() - pnlCannon.rectCannon.getX();
dHeight = pnlCannon.rectCannon.getY() - 5 - e.getY() + 10;
dAngle = Math.atan2(dHeight, dBase);
pnlCannon.dAngle = dAngle;
pnlCannon.repaint();
}

public void mouseReleased(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {
} // From http://www.rgagnon
</code>```

答:
You have to unrotate after drawing the cannon and before drawing the ball :)

You could try to save the transform before you do a rotate and then set it back again. This example is from setTransform in the Java Docs:

```<code>// Get the current transform
 AffineTransform saveAT = g2.getTransform();
 // Perform transformation
 g2d.transform(...);
 // Render
 g2d.draw(...);
 // Restore original transform
 g2d.setTransform(saveAT);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm making a program in Java for my CS class. My teacher has little experience with graphics programing in Java so I've turned to you. I'm currently using the paintComponent method of my main panel to draw two things, one, a rectangle (my cannon, possibly replaced with a image later), and two, a .png file of a cannon ball. I use the Graphics g (which I convert to Graphics2D) to paint the cannon and Ball on to the screen. I then rotate, but, the cannon and ball rotate, not just the cannon. Any tips, suggestions, or helpful tutorials are greatly appreciated.

Here is my code (the commented out links are where I got certain code, ignore them):

    package Cannon;

import java.awt.geom.Point2D;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class NewMain{

public static void main(String[] args) {
FraMainWindow frame = new FraMainWindow();
}
}

class FraMainWindow extends JFrame {
DrawCannon pnlCannon = new DrawCannon();
ButtonPannel pnlButtons = new ButtonPannel();
public FraMainWindow() {
this.setDefaultCloseOperation(JFrame.EXI…
this.setTitle("Super Mario Cannon Bro's");
this.setSize(900, 550);
this.setLayout(new BorderLayout());
this.add(pnlCannon, BorderLayout.CENTER);
this.add(pnlButtons, BorderLayout.SOUTH);
MouseMovement mouseMove = new MouseMovement();
MouseAction mouseClick = new MouseAction();
pnlCannon.addMouseMotionListener(mouseMo…
pnlCannon.addMouseListener(mouseClick);
FireButton actnFire = new FireButton();
pnlButtons.btnFire.addActionListener(act…
this.setVisible(true);
}

public class DrawCannon extends JPanel{
Rectangle.Float rectCannon = new Rectangle.Float(30, 450, 50, 10);
Image imgBall=new ImageIcon("ball.png").getImage();
double dAngle = 0;
boolean isFired = false;
public void addCannonBall(){
isFired=true;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_… RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_… RenderingHints.VALUE_RENDER_QUALITY);//A… Aliasing from http://www.java2s.com/Code/Java/2D-Graph…
g2d.rotate(0 - dAngle, rectCannon.getX(), rectCannon.getY() + 5);
g2d.fill(rectCannon);
if(isFired){
g2d.drawImage(imgBall, 0, 0, null);
}
//Dimension size = getSize();
}
}

public class ButtonPannel extends JPanel {
JButton btnFire = new JButton("Fire!");
ButtonPannel() {
this.add(btnFire);
}
}

public class FireButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
pnlCannon.addCannonBall();
System.out.println("Fire ZE MISSILES");
}
}
public class MouseMovement implements MouseMotionListener {

public void mouseDragged(MouseEvent e) {
double dBase, dHeight, dAngle;
dBase = e.getX() - pnlCannon.rectCannon.getX();
dHeight = pnlCannon.rectCannon.getY() - 5 - e.getY() + 10;
dAngle = Math.atan2(dHeight, dBase);
pnlCannon.dAngle = dAngle;
pnlCannon.repaint();
}//http://download.oracle.com/javase/tutori…

public void mouseMoved(MouseEvent e) {
}
}

public class MouseAction implements MouseListener {

public void mousePressed(MouseEvent e) {
double dBase, dHeight, dAngle;
dBase = e.getX() - pnlCannon.rectCannon.getX();
dHeight = pnlCannon.rectCannon.getY() - 5 - e.getY() + 10;
dAngle = Math.atan2(dHeight, dBase);
pnlCannon.dAngle = dAngle;
pnlCannon.repaint();
}

public void mouseReleased(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {
} // From http://www.rgagnon

Body:
You have to unrotate after drawing the cannon and before drawing the ball :)

You could try to save the transform before you do a rotate and then set it back again. This example is from setTransform in the Java Docs:

// Get the current transform
 AffineTransform saveAT = g2.getTransform();
 // Perform transformation
 g2d.transform(...);
 // Render
 g2d.draw(...);
 // Restore original transform
 g2d.setTransform(saveAT);


问:
DataBase is locked in Django project
I'm developing a chatbot chatting page that uses a DB.sqlit3 as a knowledge base for reply to users questions .Also, a have a admin chatting page for the admin to add new question and reply to DB.sqlit3 by chatting.So, for that i have 2 python script (one for the chatbot chatting and one for the admin chatting) each with its own html and JS.

The chatbot chatting page works fine but sometime when i run the admin chatting page after and try to insert new data ( questions and replay) to DB.sqlit3 i get :

```<code>The database is locked
</code>```

Thank you,

PS:
i'm using Django 10 , python3 , sqlite3, web faction server

答: Sqlite is not for production. It uses a single global database level lock. Only one thread or process can access it at a time. This is not what you want in production, and definitely not for a chat server. Look into a key value store like Redis for the chat and use a better DB for everything else.</p>

Title: DataBase is locked in Django project

Body:
I'm developing a chatbot chatting page that uses a DB.sqlit3 as a knowledge base for reply to users questions .Also, a have a admin chatting page for the admin to add new question and reply to DB.sqlit3 by chatting.So, for that i have 2 python script (one for the chatbot chatting and one for the admin chatting) each with its own html and JS.

The chatbot chatting page works fine but sometime when i run the admin chatting page after and try to insert new data ( questions and replay) to DB.sqlit3 i get :

The database is locked

Thank you,

PS:
i'm using Django 10 , python3 , sqlite3, web faction server


问:
Change column values based on factors of other columns
For example, if I have a data frame like this:

```<code>df <- data.frame(profit=c(10,10,10), year=c(2010,2011,2012))

profit     year
10         2010
10         2011
10         2012
</code>```

I want to change the value of profit according to the year. For year 2010, I multiple the profit by 3, for year 2011, multiple the profit by 4, for year 2012, multiple by 5, which should result like this:

```<code>profit     year
30         2010
40         2011
50         2012
</code>```

How should I approach this? I tried:

```<code>inflationtransform <- function(k,v) {
    switch(k,
        2010,v<-v*3,
        2011,v<-v*4,
        2012,v<-v*5,
    )
}

df$profit <- sapply(df$year,df$profit,inflationtransform)
</code>```

But it doesn't work. Can someone tell me what to do?

答:
For this particular example, since your factors and years are both ordered and incremented by 1, you could just subtract 2007 from the year column and multiply it by profit.

```<code>transform(df, profit = profit * (year - 2007))
#   profit year
# 1     30 2010
# 2     40 2011
# 3     50 2012
</code>```

Otherwise, you could use a lookup vector.  This will cover all cases.

```<code>lookup <- c("2010" = 3, "2011" = 4, "2012" = 5)
transform(df, profit = profit * lookup[as.character(year)])
#   profit year
# 1     30 2010
# 2     40 2011
# 3     50 2012
</code>```

I wouldn't use switch() unless you really need to. It's not vectorized, and that's where R is most efficient.  However, since you ask for it in the comments, here's one way.  I find it easier to use a for() loop with switch().

```<code>for(i in seq_len(nrow(df))) {
    df$profit[i] <- with(df, switch(as.character(year[i]),
        "2010" = 3 * profit[i],
        "2011" = 4 * profit[i],
        "2012" = 5 * profit[i]
    ))
}
</code>```

Body:
For example, if I have a data frame like this:

df <- data.frame(profit=c(10,10,10), year=c(2010,2011,2012))

profit     year
10         2010
10         2011
10         2012

I want to change the value of profit according to the year. For year 2010, I multiple the profit by 3, for year 2011, multiple the profit by 4, for year 2012, multiple by 5, which should result like this:

profit     year
30         2010
40         2011
50         2012

How should I approach this? I tried:

inflationtransform <- function(k,v) {
    switch(k,
        2010,v<-v*3,
        2011,v<-v*4,
        2012,v<-v*5,
    )
}

df$profit <- sapply(df$year,df$profit,inflationtransform)

But it doesn't work. Can someone tell me what to do?

Body:
For this particular example, since your factors and years are both ordered and incremented by 1, you could just subtract 2007 from the year column and multiply it by profit.

transform(df, profit = profit * (year - 2007))
#   profit year
# 1     30 2010
# 2     40 2011
# 3     50 2012

Otherwise, you could use a lookup vector.  This will cover all cases.

lookup <- c("2010" = 3, "2011" = 4, "2012" = 5)
transform(df, profit = profit * lookup[as.character(year)])
#   profit year
# 1     30 2010
# 2     40 2011
# 3     50 2012

I wouldn't use switch() unless you really need to. It's not vectorized, and that's where R is most efficient.  However, since you ask for it in the comments, here's one way.  I find it easier to use a for() loop with switch().

for(i in seq_len(nrow(df))) {
    df$profit[i] <- with(df, switch(as.character(year[i]),
        "2010" = 3 * profit[i],
        "2011" = 4 * profit[i],
        "2012" = 5 * profit[i]
    ))
}


问:
Tersely determining how many times a pair exists in a longer list
I am in the middle of writing a large piece of code and I want to shorten a length or expression.
Let's say we have a list, something like:

```<code>farm = ["cow","cow","cow", "hen","hen","hen", "fox","fox","fox", "hen","hen", "hen"]
lookup = ["cow","hen"]
</code>```

I am supposed to check whether there are three consecutive elements of lookfor in farm list.

One way is to do:

```<code>for i in range (0,len(farm) - 2):
  if ((farm[i] == farm[i+1] == farm[i+2] == lookup[0])
     or (farm[i] == farm[i+1] == farm[i+2] == lookup[1])):
    # do something
</code>```

Now if the number of elements in lookup is small, it can be written in the above way. However, if it is too long the code looks cumbersome and is harder to maintain. Is there a more concise way of writing the code, perhaps in list comprehension format - so that I do not have to manually write to look for all the elements of lookup?

答:
Untested, but something "like this" ;-) should work.  any() is a natural way to process an arbitrary number of ors, and all() for arbitrary number of ands.

```<code>if any(farm[i] == farm[i+1] == farm[i+2] == target for i in range(len(farm) - 2)
       for target in lookup):
    # do something
</code>```

If you need i

This variant will give you the matching i value, and is very much like your original code:

```<code>for i in range (0,len(farm) - 2):
   if any(farm[i] == farm[i+1] == farm[i+2] == target for target in lookup):
       print(i)
</code>```

Body:
I am in the middle of writing a large piece of code and I want to shorten a length or expression.
Let's say we have a list, something like:

farm = ["cow","cow","cow", "hen","hen","hen", "fox","fox","fox", "hen","hen", "hen"]
lookup = ["cow","hen"]

I am supposed to check whether there are three consecutive elements of lookfor in farm list.

One way is to do:

for i in range (0,len(farm) - 2):
  if ((farm[i] == farm[i+1] == farm[i+2] == lookup[0])
     or (farm[i] == farm[i+1] == farm[i+2] == lookup[1])):
    # do something

Now if the number of elements in lookup is small, it can be written in the above way. However, if it is too long the code looks cumbersome and is harder to maintain. Is there a more concise way of writing the code, perhaps in list comprehension format - so that I do not have to manually write to look for all the elements of lookup?

Body:
Untested, but something "like this" ;-) should work.  any() is a natural way to process an arbitrary number of ors, and all() for arbitrary number of ands.

if any(farm[i] == farm[i+1] == farm[i+2] == target for i in range(len(farm) - 2)
       for target in lookup):
    # do something

If you need i

This variant will give you the matching i value, and is very much like your original code:

for i in range (0,len(farm) - 2):
   if any(farm[i] == farm[i+1] == farm[i+2] == target for target in lookup):
       print(i)


问:
Rotate a 2D NxN matrix in Concentric Circles
Given a 2D NxN matrix, visualize it as concentric circles. You have to find the rotated matrix where each element in the circle is rotated by 1 position layer by layer in an alternate clockwise and anticlockwise direction. All rotations should be in-place.

```<code>2 3 4 5
1 6 7 8
4 2 1 9
5 3 2 4
</code>```

should get transformed to

```<code>1 2 3 4
4 7 1 5
5 6 2 8
3 2 4 9
</code>```

I thought about the solution

1> For clockwise circle rotation, read elements in the order

```<code>i -> 0 to n-1 and j = 0
j -> 0 to n-1 and i = n-1
i -> n-1 to 0 and j = n-1
j -> n-1 to 0 and i = 0
</code>```

2> For anti-clockwise circle rotation, read elements in the order

```<code>j -> 0 to n-1 and i = 0
i -> 0 to n-1 and j = n-1
j -> n-1 to 0 and i = n-1
i -> n-1 to 0 and j = 0
</code>```

Code

```<code>for(int cnt = 0; cnt < n/2; cnt++)
    {
        if(cnt%2 == 0) // Clockwise
        {
            i = cnt; j = cnt;
            // while loops for each case
        }
        else // anti-clockwise
        {
            i = cnt; j = cnt;
            // while loops for each case
        }
}
</code>```

Is there any better approach to solve this problem in O(n2) or better ?

答:
```<code>import java.util.Scanner;

public class RotateMatrix
{
    static int rows = 0;
    static int cols = 0;

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        rows = scan.nextInt();
        cols = scan.nextInt();
        int rots = scan.nextInt();
        int[][] matrix = new int[rows][cols];
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                matrix[i][j] = scan.nextInt();
            }
        }
        for (int i = 0; i < rots; i++)
            rotate(matrix, 0, rows - 1, 0, cols - 1);

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
        scan.close();
    }

    public static int[][] rotate(int[][] arr, int rowStart, int rowEnd, int colStart, int colEnd)
    {

        if (rowStart == rowEnd && colStart == colEnd)
        {
            return arr;
        }
        if (rowStart > rowEnd || colStart > colEnd)
        {
            return arr;
        }

        int temp = arr[rowStart][colStart];
        for (int j = colStart; j < colEnd; j++)
        {
            arr[colStart][j] = arr[colStart][j + 1];
        }
        for (int i = rowStart; i < rowEnd; i++)
        {
            arr[i][colEnd] = arr[i + 1][colEnd];
        }
        for (int i = colEnd; i > colStart; i--)
        {
            arr[rowEnd][i] = arr[rowEnd][i - 1];
        }
        for (int i = rowEnd; i > rowStart; i--)
        {
            arr[i][colStart] = arr[i - 1][colStart];
        }

        if (rows == 1)
        {
            arr[colEnd][rowStart] = temp;
        }
        else
            arr[rowStart + 1][colStart] = temp;

        System.out.println("-----------------------------------------\n");
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println("-----------------------------------------\n");
        rotate(arr, rowStart + 1, rowEnd - 1, colStart + 1, colEnd - 1);
        return arr;
    }
}
</code>```

Body:
Given a 2D NxN matrix, visualize it as concentric circles. You have to find the rotated matrix where each element in the circle is rotated by 1 position layer by layer in an alternate clockwise and anticlockwise direction. All rotations should be in-place.

2 3 4 5
1 6 7 8
4 2 1 9
5 3 2 4

should get transformed to

1 2 3 4
4 7 1 5
5 6 2 8
3 2 4 9

I thought about the solution

1> For clockwise circle rotation, read elements in the order

i -> 0 to n-1 and j = 0
j -> 0 to n-1 and i = n-1
i -> n-1 to 0 and j = n-1
j -> n-1 to 0 and i = 0

2> For anti-clockwise circle rotation, read elements in the order

j -> 0 to n-1 and i = 0
i -> 0 to n-1 and j = n-1
j -> n-1 to 0 and i = n-1
i -> n-1 to 0 and j = 0

Code

for(int cnt = 0; cnt < n/2; cnt++)
    {
        if(cnt%2 == 0) // Clockwise
        {
            i = cnt; j = cnt;
            // while loops for each case
        }
        else // anti-clockwise
        {
            i = cnt; j = cnt;
            // while loops for each case
        }
}

Is there any better approach to solve this problem in O(n2) or better ?


问:
Are there no built in C# GUI Layouts?
I'm used to the GUI frameworks in Java as well as the QT GUI framework, and I'm used to the various layout managers. It doesn't seem that C# has any layout managers built in, or am I missing something?

2 Year Later Edit

I just want to point out to any readers of this question that in hind-sight, my question was misplaced. With proper anchoring and docking of child controls, having a need for the layout managers of Java and QT4 is nearly non-existent.

答:
WPF does have layout managers, see:

http://msdn.microsoft.com/en-us/library/ms745058.aspx

If you're coming from a Java background, then the section "Panel Elements and Custom Layout Behaviors" will be of particular interest.

Title: Are there no built in C# GUI Layouts?


问:
Error on smack 4.2.0 : IN AAAA yielded an error response NX_DOMAIN
i start openFire and test it with spark everything is ok but when i try to connect with smack 4.2.0 in android studio i got this error:

Ljavax/naming/directory/InitialDirContext;

and my dependencies is this:

compile "org.igniterealtime.smack:smack-java7:4.2.0" compile
  "org.igniterealtime.smack:smack-tcp:4.2.0" compile
  "org.igniterealtime.smack:smack-im:4.2.0" compile
  "org.igniterealtime.smack:smack-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-android-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-bosh:4.2.0"

when remove this :
"compile org.igniterealtime.smack:smack-java7:4.2.0"
from dependencies and add this:
compile "org.igniterealtime.smack:smack-android:4.2.0"
my dependencies become like this:

compile 'com.android.support:appcompat-v7:24.0.0' compile
  "org.igniterealtime.smack:smack-android:4.2.0" compile
  "org.igniterealtime.smack:smack-tcp:4.2.0" compile
  "org.igniterealtime.smack:smack-im:4.2.0" compile
  "org.igniterealtime.smack:smack-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-android-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-bosh:4.2.0"

I got This Error:

org.jivesoftware.smack.SmackException$ConnectionException: The
  following addresses failed: '192.168.209.2:5222' failed because:
  de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for
  192.168.209.2. IN A yielded an error response NX_DOMAIN, '192.168.209.2:5222' failed because:
  de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for
  192.168.209.2. IN AAAA yielded an error response NX_DOMAIN

the part of code that make error when i try to conn.connect() is this:

```<code>XMPPTCPConnectionConfiguration config = null;
            try {
                config = XMPPTCPConnectionConfiguration.builder()
                        .setUsernameAndPassword("admin", "thepass")
                        .setXmppDomain("192.168.1.3")
                        .setHost("192.168.209.2")
                        .setPort(5222)
                        .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
                AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
                conn1.setReplyTimeout(60000);
                conn1.setPacketReplyTimeout(60000);
                conn1.connect();
</code>```

答:
The error you have encountered is stemming from incomplete addressing of your XMPP server.

Imagine this scenario:

my ejabberd server is running on this address: 192.168.209.2 #ejabberd
  server

There is a xmpp domain named "localhost" There are two JIDs,

"davood@localhost" and "sadegh@localhost"

In smack, I want to authenticate with my user, say "davood@localhost".
Then I do it as follow:

```<code>            InetAddress addr = InetAddress.getByName("192.168.209.2");
            HostnameVerifier verifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return false;
                }
            };
            DomainBareJid serviceName = JidCreate.domainBareFrom("localhost");
            XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                    .setHost(server) # it will be resolved by setHostAddress method
                    .setUsernameAndPassword("davood","mypass")
                    .setPort(5222)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setXmppDomain(serviceName)
                    .setHostnameVerifier(verifier)
                    .setHostAddress(addr)
                    .setDebuggerEnabled(true)
                    .build();
            AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);

            conn1.connect();

            if(conn1.isConnected()){
                Log.d("XMPP","Connected");
            }
            conn1.login();

            if(conn1.isAuthenticated()){
                Log.d("XMPP","Authenticated");
                EntityBareJid jid = JidCreate.entityBareFrom("sadegh@localhost");
                org.jivesoftware.smack.chat2.Chat chat = ChatManager.getInstanceFor(conn1).chatWith(jid);
                chat.send("Eureka, I am connected!");

            }
</code>```

Body:
i start openFire and test it with spark everything is ok but when i try to connect with smack 4.2.0 in android studio i got this error:

Ljavax/naming/directory/InitialDirContext;

and my dependencies is this:

compile "org.igniterealtime.smack:smack-java7:4.2.0" compile
  "org.igniterealtime.smack:smack-tcp:4.2.0" compile
  "org.igniterealtime.smack:smack-im:4.2.0" compile
  "org.igniterealtime.smack:smack-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-android-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-bosh:4.2.0"

when remove this :
"compile org.igniterealtime.smack:smack-java7:4.2.0"
from dependencies and add this:
compile "org.igniterealtime.smack:smack-android:4.2.0"
my dependencies become like this:

compile 'com.android.support:appcompat-v7:24.0.0' compile
  "org.igniterealtime.smack:smack-android:4.2.0" compile
  "org.igniterealtime.smack:smack-tcp:4.2.0" compile
  "org.igniterealtime.smack:smack-im:4.2.0" compile
  "org.igniterealtime.smack:smack-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-android-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-bosh:4.2.0"

I got This Error:

org.jivesoftware.smack.SmackException$ConnectionException: The
  following addresses failed: '192.168.209.2:5222' failed because:
  de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for
  192.168.209.2. IN A yielded an error response NX_DOMAIN, '192.168.209.2:5222' failed because:
  de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for
  192.168.209.2. IN AAAA yielded an error response NX_DOMAIN

the part of code that make error when i try to conn.connect() is this:

XMPPTCPConnectionConfiguration config = null;
            try {
                config = XMPPTCPConnectionConfiguration.builder()
                        .setUsernameAndPassword("admin", "thepass")
                        .setXmppDomain("192.168.1.3")
                        .setHost("192.168.209.2")
                        .setPort(5222)
                        .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
                AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
                conn1.setReplyTimeout(60000);
                conn1.setPacketReplyTimeout(60000);
                conn1.connect();

Body:
The error you have encountered is stemming from incomplete addressing of your XMPP server.

Imagine this scenario:

my ejabberd server is running on this address: 192.168.209.2 #ejabberd
  server

There is a xmpp domain named "localhost" There are two JIDs,

"davood@localhost" and "sadegh@localhost"

In smack, I want to authenticate with my user, say "davood@localhost".
Then I do it as follow:

            InetAddress addr = InetAddress.getByName("192.168.209.2");
            HostnameVerifier verifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return false;
                }
            };
            DomainBareJid serviceName = JidCreate.domainBareFrom("localhost");
            XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                    .setHost(server) # it will be resolved by setHostAddress method
                    .setUsernameAndPassword("davood","mypass")
                    .setPort(5222)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setXmppDomain(serviceName)
                    .setHostnameVerifier(verifier)
                    .setHostAddress(addr)
                    .setDebuggerEnabled(true)
                    .build();
            AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);

            conn1.connect();

            if(conn1.isConnected()){
                Log.d("XMPP","Connected");
            }
            conn1.login();

            if(conn1.isAuthenticated()){
                Log.d("XMPP","Authenticated");
                EntityBareJid jid = JidCreate.entityBareFrom("sadegh@localhost");
                org.jivesoftware.smack.chat2.Chat chat = ChatManager.getInstanceFor(conn1).chatWith(jid);
                chat.send("Eureka, I am connected!");

            }


问:
Jquery unbind() not working for contact form
I am building my first contact form.

I am trying to unbind my function given no error message.

Code is below - for whatever reason I keep getting the follow error message in my dev console :

Uncaught TypeError: $(...).unbind is not a function

Appreciate any help.

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  </head>
  <body>

  <div class ='container'>
    <h1>Get in touch!</h1>

    <div id='error'></div>

      <form>
        <div class="form-group">
          <label for="exampleInputEmail1">Email address</label>
          <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">
        </div>

        <div class="form-group">
          <label for="exampleInputPassword1">Subject</label>
          <input type="password" class="form-control" id="subject" placeholder="Subject">
        </div>

        <div class="form-group">
          <label for="exampleTextarea">Message</label>
          <textarea class="form-control" id="message" rows="3"></textarea>
        </div>
        <button type="submit" class="btn btn-primary" id="submit">Submit</button>
      </form>

    </div>

    <!-- jQuery first, then Tether, then Bootstrap JS. -->
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

    <script type='text/javascript'>
    $('form').submit(function (e) {

      e.preventDefault();
      var error ="";

      if ($('#subject').val() == "") {
        error += 'The subject field is required.<br>';
      }

      if ($('#message').val() == "") {
        error += 'The message field is required.<br>';
      }

      if ($('#email').val() == "") {
        error += 'The email field is required.';
      }

      if (error != "" ) {
        $("#error").html(
        '<div class="alert alert-danger" role="alert"></p> <strong>Error(s) in your form:</strong></p>' + error +  '</div>');
      }else{
        $("form").unbind('submit').submit();
      }

    });
    </script>
  </body>
</html>
</code>```

答:
You are using the 3.1.1.slim build of jQuery. According to the jQuery site:

[the slim build] "...excludes ajax, effects, and currently deprecated code."

The .unbind() method was deprecated in v3.0, and so is not included in the build you are using.

Use the .off() method instead.

Body:
I am building my first contact form.

I am trying to unbind my function given no error message.

Code is below - for whatever reason I keep getting the follow error message in my dev console :

Uncaught TypeError: $(...).unbind is not a function

Appreciate any help.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Get in touch!

      <form>

          Email address
          <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">

          Subject
          <input type="password" class="form-control" id="subject" placeholder="Subject">

          Message
          <textarea class="form-control" id="message" rows="3"></textarea>

        <button type="submit" class="btn btn-primary" id="submit">Submit</button>
      </form>


问:
Unable to map a hashmap using JPA annotations
I am using dropwizard which internally uses JPA annotatons and hibernate to map  objects. One of the object has a map field which I have defined as

```<code>    @Column
    @ElementCollection(targetClass=String.class)
    Map<String, String> routes;
</code>```

I keep seeing the following error

```<code>org.hibernate.MappingException: Could not determine type for: java.util.Map, at table
</code>```

I have tried a number of things mentioned on SO

Added the @MapKey annotation
Added annotations on getters
changed Map to HashMap nothing seems to fix it.

答: You can use @MapKeyColumn(name="column_name"). This link might be useful: https://en.wikibooks.org/wiki/Java_Persistence/Relationships#Map_Key_Columns_.28JPA_2.0.29</p>

Body:
I am using dropwizard which internally uses JPA annotatons and hibernate to map  objects. One of the object has a map field which I have defined as

    @Column
    @ElementCollection(targetClass=String.class)
    Map<String, String> routes;

I keep seeing the following error

org.hibernate.MappingException: Could not determine type for: java.util.Map, at table

I have tried a number of things mentioned on SO

Added the @MapKey annotation
Added annotations on getters
changed Map to HashMap nothing seems to fix it.


问:
Bash script for iterating through defined set of file names and performing commands
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

```<code>/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;
</code>```

Then the next command is analogous:

```<code>/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;
</code>```

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command.
Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.

答:
The no brainer way is:

```<code>for dir in [0-9][0-9]/; do
    cd "$dir"
    cp /home/files/*Session${dir%/}.* .
    svn add *Session${dir%/}.*
    svn commit
    cd ..
done
</code>```

This will only iterate over directories which are composed of 2 digits.

Body:
I have a set of folders named for example 10, 12, 13, 14, 18, 24 etc. They don't change numbers in any standard increment. I then need to move repetitively into the folders and then into the next one to perform SVN commands which are the same except for some variable extension, e.g.:

/home/boy$ cp /home/files/*Session10.* . ; svn add *Session10.*; svn commit; cd ..; cd 12;

Then the next command is analogous:

/home/boy$ cp /home/files/*Session12.* . ; svn add *Session12.*; svn commit; cd ..; cd 14;

So there should be an array or list defined, and then a for loop through that list, and then a variable whose name is expanded to be fed into the cp and svn command.
Any thoughts? I hope that it can be done in the command prompt rather than in a bash script file.

Body:
The no brainer way is:

for dir in [0-9][0-9]/; do
    cd "$dir"
    cp /home/files/*Session${dir%/}.* .
    svn add *Session${dir%/}.*
    svn commit
    cd ..
done

This will only iterate over directories which are composed of 2 digits.


问:
The while loop doesn't continue as intended
For some reason, the while loop in main terminates once I enter a character to search, but the intention is for you to be able to enter a line and then a character to search until you enter a blank line (enter nothing). Basically I would want to do step 1 and step 2 infinitely until I type nothing and hit enter. Why doesn't this work? Thanks anyone for help!

Also, a little side question, how do I clear any garbage after a character is entered for searching?

```<code>#include <stdio.h>
#define SIZE 41
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
    char array[SIZE],search;
    int found[SIZE],i,charsFound;
    //Step 1
    printf("Enter a line of text(empty line to quit): ");
    while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
    //Step 2
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout);
        printf("Character being searched for: %c\n",search);
        printf("Character found at %d location(s).\n",charsFound);
        for (i=0;i<charsFound;i++)
            printf("%c was found at %d\n",search,found[i]);
        printf("Enter a line of text(empty line to quit): ");
    }
    return 0;
}
int CharIsAt(char *pStr,char ch,int loc[],int mLoc){
    //Searches for ch in *pStr by incrementing a pointer to access
    //and compare each character in *pStr to ch.
    int i,x;
    for (i=0,x=0;i<mLoc;i++){
        if (*(pStr+i)==ch){
            //Stores index of ch's location to loc
            loc[x]=i;
            x++;    //Increment for each time ch was counted in pStr
        }
    }
    //Returns the number of times ch was found
    return x;
}
</code>```

I included my entire code if that's not too annoying, I can try and make a simpler version of the problem if that would help. I figured posting the entire code might be more useful for answering the question.

Thanks again, cheers!

答:
```<code>   while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout);
        printf("Character being searched for: %c\n",search);
        printf("Character found at %d location(s).\n",charsFound);
        for (i=0;i<charsFound;i++)
            printf("%c was found at %d\n",search,found[i]);
        if (fgets(array,SIZE, stdin)==NULL) break;
    }
    return 0;
</code>```

This should work

Body:
For some reason, the while loop in main terminates once I enter a character to search, but the intention is for you to be able to enter a line and then a character to search until you enter a blank line (enter nothing). Basically I would want to do step 1 and step 2 infinitely until I type nothing and hit enter. Why doesn't this work? Thanks anyone for help!

Also, a little side question, how do I clear any garbage after a character is entered for searching?

#include <stdio.h>
#define SIZE 41
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
    char array[SIZE],search;
    int found[SIZE],i,charsFound;
    //Step 1
    printf("Enter a line of text(empty line to quit): ");
    while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
    //Step 2
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout);
        printf("Character being searched for: %c\n",search);
        printf("Character found at %d location(s).\n",charsFound);
        for (i=0;i<charsFound;i++)
            printf("%c was found at %d\n",search,found[i]);
        printf("Enter a line of text(empty line to quit): ");
    }
    return 0;
}
int CharIsAt(char *pStr,char ch,int loc[],int mLoc){
    //Searches for ch in *pStr by incrementing a pointer to access
    //and compare each character in *pStr to ch.
    int i,x;
    for (i=0,x=0;i<mLoc;i++){
        if (*(pStr+i)==ch){
            //Stores index of ch's location to loc
            loc[x]=i;
            x++;    //Increment for each time ch was counted in pStr
        }
    }
    //Returns the number of times ch was found
    return x;
}

I included my entire code if that's not too annoying, I can try and make a simpler version of the problem if that would help. I figured posting the entire code might be more useful for answering the question.

Thanks again, cheers!

Body:
   while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout);
        printf("Character being searched for: %c\n",search);
        printf("Character found at %d location(s).\n",charsFound);
        for (i=0;i<charsFound;i++)
            printf("%c was found at %d\n",search,found[i]);
        if (fgets(array,SIZE, stdin)==NULL) break;
    }
    return 0;

This should work


问:
Pandas: How can I add two timestamp values?
I am trying to add more than two timestamp values and I expect to see output in minutes/seconds. How can I add two timestamps? I basically want to do: '1995-07-01 00:00:01' + '1995-07-01 00:05:06' and see if total time>=60minutes.
I tried this code: df['timestamp'][0]+df['timestamp'][1]. I referred this post but my timestamps are coming from dataframe.
Head of my dataframe column looks like this:

0   1995-07-01 00:00:01
1   1995-07-01 00:00:06
2   1995-07-01 00:00:09
3   1995-07-01 00:00:09
4   1995-07-01 00:00:09
Name: timestamp, dtype: datetime64[ns]```

I am getting this error:
TypeError: unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'

答:
```<code>#Adding two timestamps is not supported and not logical
#Probably, you really want to add the time rather than the timestamp itself
#This is how to extract the time from the timestamp then summing it up

import datetime
import time

t = ['1995-07-01 00:00:01','1995-07-01 00:00:06','1995-07-01 00:00:09','1995-07-01 00:00:09','1995-07-01 00:00:09']
tSum = datetime.timedelta()
df = pd.DataFrame(t, columns=['timestamp'])
for i in range(len(df)):
    df['timestamp'][i] = datetime.datetime.strptime(df['timestamp'][i], "%Y-%m-%d %H:%M:%S").time()
    dt=df['timestamp'][i]
    (hr, mi, sec) = (dt.hour, dt.minute, dt.second)
    sum = datetime.timedelta(hours=int(hr), minutes=int(mi),seconds=int(sec))
    tSum += sum
if tSum.seconds >= 60*60:
    print("more than 1 hour")
else:
    print("less than 1 hour")
</code>```

Body:
I am trying to add more than two timestamp values and I expect to see output in minutes/seconds. How can I add two timestamps? I basically want to do: '1995-07-01 00:00:01' + '1995-07-01 00:05:06' and see if total time>=60minutes.
I tried this code: df['timestamp'][0]+df['timestamp'][1]. I referred this post but my timestamps are coming from dataframe.
Head of my dataframe column looks like this:

0   1995-07-01 00:00:01
1   1995-07-01 00:00:06
2   1995-07-01 00:00:09
3   1995-07-01 00:00:09
4   1995-07-01 00:00:09
Name: timestamp, dtype: datetime64[ns]

I am getting this error:
TypeError: unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'


问:
glfwInit taking a long time to initialize
It used to work fine last week but now that I'm trying to open the project again, it stays stuck on glfwInit() for a good 30 second every time. I've tried it using both a project on VS2015 and the new 2017 one to see if it fixed it.

There's nothing before glfwInit(); and when I put a breakpoint right after, it takes 30 seconds to break.

I can't seem to find anything on this, is there any known solution?

答:
Reboot.

I was having this same problem, and it immediately went away once I rebooted my PC.


问:
How can I most efficiently get these group_by stats in MYSQL statement
Suppose I have a MySQL table that was created like this:

```<code>CREATE TABLE `my_table` (
  `my_id` char(32) NOT NULL,
  `my_boolean_field` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`my_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

This table is very large. It has approximately 10 million rows in it. my_boolean_field's only possible values are 1, 0 and null.

Now separately, I have a list of 500 IDs. Let's call this my_list. They are in a text file separated by newlines. The name of that file is myfile.txt. The entries in this file are too long to include in a single where clause of an SQL statement.

I want to answer the following questions:

How many of the rows in my_table have and ID that is in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==0.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==0.

What is the most performant way to get the above 6 counts??

答:
Use left join and conditional aggregation to get the desired counts.

```<code>select
 sum(l.id is not null and t.my_boolean_field is null)
,sum(l.id is not null and t.my_boolean_field =1)
,sum(l.id is not null and t.my_boolean_field =0)
,sum(l.id is null and t.my_boolean_field is null)
,sum(l.id is null and t.my_boolean_field =1)
,sum(l.id is null and t.my_boolean_field =0)
from my_table t
left join my_list l on l.id=t.my_id
</code>```

The conditions in sum are treated as booleans and return 1 for true and 0 for false.

Body:
Suppose I have a MySQL table that was created like this:

CREATE TABLE `my_table` (
  `my_id` char(32) NOT NULL,
  `my_boolean_field` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`my_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This table is very large. It has approximately 10 million rows in it. my_boolean_field's only possible values are 1, 0 and null.

Now separately, I have a list of 500 IDs. Let's call this my_list. They are in a text file separated by newlines. The name of that file is myfile.txt. The entries in this file are too long to include in a single where clause of an SQL statement.

I want to answer the following questions:

How many of the rows in my_table have and ID that is in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==0.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==0.

What is the most performant way to get the above 6 counts??

Body:
Use left join and conditional aggregation to get the desired counts.

select
 sum(l.id is not null and t.my_boolean_field is null)
,sum(l.id is not null and t.my_boolean_field =1)
,sum(l.id is not null and t.my_boolean_field =0)
,sum(l.id is null and t.my_boolean_field is null)
,sum(l.id is null and t.my_boolean_field =1)
,sum(l.id is null and t.my_boolean_field =0)
from my_table t
left join my_list l on l.id=t.my_id

The conditions in sum are treated as booleans and return 1 for true and 0 for false.


问:
@Keyframes to scale transform site body
How can I use @keyframes to scale transform (enlarge) all content in my HTML  tags?

Is there a way to use Keyframes instead of my temporary solution of body:hover?

The body should be scaled by 1.01 over a period of 1.5s as the website page is first loaded.

```<code>body {
    transition: all 1.5s ease-in-out;
    transform: scale(1.00);
</code>```

}

```<code>body:hover {
    transition: all 1.5s ease-in-out;
    transform: scale(1.01);
}
</code>```

答:
Using css animation like this

@keyframes anime {
  0% {
    transform: scale(1.00);
  }
  100% {
    transform: scale(1.01);
  }
}

@-webkit-keyframes anime {
  0% {
    transform: scale(1.00);
  }
  100% {
    transform: scale(1.01);
  }
}

@-moz-keyframes anime {
  0% {
    transform: scale(1.00);
  }
  100% {
    transform: scale(1.01);
  }
}

@-o-keyframes anime {
  0% {
    transform: scale(1.00);
  }
  100% {
    transform: scale(1.01);
  }
}

body {
  transition: all 1.5s ease-in-out;
  /*     transform: scale(1.00); */
  border: solid red;
  animation-name: anime;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  The earliest computers dealt with numeric data only, and made no provision for character data. Six-bit BCD was used by IBM on early computers such as the IBM 704 in 1954.[1]:p.35 This encoding was replaced by the 8-bit EBCDIC code when System/360 standardized
  on 8-bit bytes. There are some variants of this type of code (see below). Six-bit character codes generally succeeded the five-bit Baudot code and preceded seven-bit ASCII. One popular variant was DEC SIXBIT. This is simply the ASCII character codes
  from 32 to 95 coded as 0 to 63 by subtracting 32 (i.e., columns 2, 3, 4, and 5 of the ASCII table (16 characters to a column), shifted to columns 0 through 3, by subtracting 2 from the high bits); it includes the space, punctuation characters, numbers,
  and capital letters, but no control characters. Since it included no control characters, not even end-of-line, it was not used for general text processing. However, six-character names such as filenames and assembler symbols could be stored in a single
  36-bit word of PDP-10, and three characters fit in each word of the PDP-1 and two characters fit in each word of the PDP-8. Six-bit codes could encode more than 64 characters by the use of Shift Out and Shift In characters, essentially incorporating
  two distinct 62-character sets and switching between them. For example, the popular IBM 2741 communications terminal supported a variety of character sets of up to 88 printing characters plus control characters.

</div></code>```

Title: @Keyframes to scale transform site body

Body:
How can I use @keyframes to scale transform (enlarge) all content in my HTML  tags?

Is there a way to use Keyframes instead of my temporary solution of body:hover?

The body should be scaled by 1.01 over a period of 1.5s as the website page is first loaded.

body {
    transition: all 1.5s ease-in-out;
    transform: scale(1.00);

}

body:hover {
    transition: all 1.5s ease-in-out;
    transform: scale(1.01);
}

Body:
Using css animation like this

@keyframes anime {
  0% {
    transform: scale(1.00);
  }
  100% {
    transform: scale(1.01);
  }
}

@-webkit-keyframes anime {
  0% {
    transform: scale(1.00);
  }
  100% {
    transform: scale(1.01);
  }
}

@-moz-keyframes anime {
  0% {
    transform: scale(1.00);
  }
  100% {
    transform: scale(1.01);
  }
}

@-o-keyframes anime {
  0% {
    transform: scale(1.00);
  }
  100% {
    transform: scale(1.01);
  }
}

body {
  transition: all 1.5s ease-in-out;
  /*     transform: scale(1.00); */
  border: solid red;
  animation-name: anime;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

<div>
  The earliest computers dealt with numeric data only, and made no provision for character data. Six-bit BCD was used by IBM on early computers such as the IBM 704 in 1954.[1]:p.35 This encoding was replaced by the 8-bit EBCDIC code when System/360 standardized
  on 8-bit bytes. There are some variants of this type of code (see below). Six-bit character codes generally succeeded the five-bit Baudot code and preceded seven-bit ASCII. One popular variant was DEC SIXBIT. This is simply the ASCII character codes
  from 32 to 95 coded as 0 to 63 by subtracting 32 (i.e., columns 2, 3, 4, and 5 of the ASCII table (16 characters to a column), shifted to columns 0 through 3, by subtracting 2 from the high bits); it includes the space, punctuation characters, numbers,
  and capital letters, but no control characters. Since it included no control characters, not even end-of-line, it was not used for general text processing. However, six-character names such as filenames and assembler symbols could be stored in a single
  36-bit word of PDP-10, and three characters fit in each word of the PDP-1 and two characters fit in each word of the PDP-8. Six-bit codes could encode more than 64 characters by the use of Shift Out and Shift In characters, essentially incorporating
  two distinct 62-character sets and switching between them. For example, the popular IBM 2741 communications terminal supported a variety of character sets of up to 88 printing characters plus control characters.

</div>


问:
I need to split an array of data into cells in excel
I have a spreadsheet that queries a data source and returns an array of about 230 rows of comma separated results. The data looks like this:

I need to have all those comma separated values that are now in one cell (column B) split into separate cells. There are typically 21 results for each row. So the result should look like this:

The row the data starts on could vary, but typically starts around row 80. The top rows are used for displaying results from the data below it. The starting point could be fixed at say row 120 (if that makes scripting easier), which would leave plenty of room for future dev.

I've tried modifying a few different solutions I've found on here, but none worked. Any help is supremely appreciated!

答:
I didn't fully test this but maybe you can try something like this. The procedure should iterate through the rows and split out the values in column B.

You will need to change the name of "Sheet1" in Set ws = ActiveWorkbook.Worksheets("Sheet1") to the name of the worksheet you are using.

```<code>Public Sub SplitData()

    Dim ws As Worksheet
    Set ws = ActiveWorkbook.Worksheets("Sheet1")

    Dim row As Integer
    For row = 1 To ws.Range("A" & ws.Rows.Count).End(xlUp).row

        Dim split_array() As String
        split_array = Split(ws.Range("B" & row).Value, ",")
        Dim split_str As Variant
        Dim col As Integer
        col = 3
        For Each split_str In split_array
            ws.Cells(row, col).Value = split_str
            col = col + 1
        Next split_str

    Next row

End Sub
</code>```

My sheet started out looking like this.

It ended up looking like this after running the procedure.

Body:
I didn't fully test this but maybe you can try something like this. The procedure should iterate through the rows and split out the values in column B.

You will need to change the name of "Sheet1" in Set ws = ActiveWorkbook.Worksheets("Sheet1") to the name of the worksheet you are using.

Public Sub SplitData()

    Dim ws As Worksheet
    Set ws = ActiveWorkbook.Worksheets("Sheet1")

    Dim row As Integer
    For row = 1 To ws.Range("A" & ws.Rows.Count).End(xlUp).row

        Dim split_array() As String
        split_array = Split(ws.Range("B" & row).Value, ",")
        Dim split_str As Variant
        Dim col As Integer
        col = 3
        For Each split_str In split_array
            ws.Cells(row, col).Value = split_str
            col = col + 1
        Next split_str

    Next row

End Sub

My sheet started out looking like this.

It ended up looking like this after running the procedure.