问:
Help with using FFT to determine frequency of an audio sample
I'm currently developing a percussion tutorial program. The program requires that I can determine what drum is being played, to do this I was going to analyse the frequency of the drum recording and see if the frequency is within a given range.

I have been using the Apache math commons implementation for FFT so far (http://commons.apache.org/math/) but my question is, once I preform the FFT, how do I use the array of results to calculate the frequencies contained in the signal?

Note: I have also tried experimenting with using Autocorrelation, but it didn't seem to work to well with sample from a drum kit

Any help or alternative suggestions of how to determine what drum is being hit would be greatly appreciated

Edit: Since writing this I've found a great online lesson on implementing FFT in java for Time/ frequency transformations Spectrum Analysis in Java

答:
In the area of music information retrieval, people often use a related metric known as the mel-frequency cepstral coefficients (MFCCs).

For any N-sample segment of your signal, take the FFT. Those resulting N samples are transformed into a set of MFCCs containing, say, 12 elements (i.e., coefficients). This 12-element vector is used to classify the instrument, including which drum is used.

To do supervised classification, you can use something like a support vector machine (SVM). LIBSVM is a commonly used library that has Java compatibility (and many other languages). You train the SVM with these MFCCs and their corresponding instrument labels. Then, you test it by feeding a query MFCC vector, and it will tell you which instrument it is.

So the basic procedure, in summary:

Get FFT.

Get MFCCs from FFT.

Train SVM with MFCCs and instrument labels.

Query the SVM with MFCCs of the query signal.

Check for Java packages that do these things. (They must exist. I just don't know them.) Relatively, drum transcription is easier than most other instrument groups, so I am optimistic that this would work.

For further reading, there are a whole bunch of articles on drum transcription.


来源: stackexchange

问:
arrange one below the other every 2 columns from data frame in R
Hi I have a df as below which show date and their respected

```<code>date   1_val   date  2_val  . . . .  date  n_val
  2014   23      2014  33    . . . .  2014   34
  2015   22      2016  12    . . . .  2016   99
</code>```

i have tried with hard coding to arrange the columns one below the other

```<code>for 1&2 columns
a=1
b=2
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out<-names_2

for 3&4 columns
a=3
b=4
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out1<-names_2

till n-numbers
df1= rbind(samp_out,samp_out1,......samp_out_n)
</code>```

output

```<code> date   variable   value
2014     1_val       23
2015     1_val       22
2014     2_val       33
2016     2_val       12
.
.
2014     n_val      34
2016     n_val      99
</code>```

Thanks in advance

答:
The function melt in the package data.table does that:

```<code>melt(df, id = "Date", measure = patterns("_val"))
</code>```

You can specify the name of the variable to pivot on (Date in this case) and a pattern in the variables you want to keep the values of. You can also supply a vector with all the variablenames instead.

```<code>> DT <- data.table(Date = c(2014,2013), `1_val` = c(33, 32), Date = c(2014, 2013), `2_val` = c(65, 34))
> DT
   Date 1_val Date 2_val
1: 2014    33 2014    65
2: 2013    32 2013    34
> melt(DT, id = "Date", measure = patterns("_val"))
   Date variable value
1: 2014    1_val    33
2: 2013    1_val    32
3: 2014    2_val    65
4: 2013    2_val    34
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I have a df as below which show date and their respected

date   1_val   date  2_val  . . . .  date  n_val
  2014   23      2014  33    . . . .  2014   34
  2015   22      2016  12    . . . .  2016   99

i have tried with hard coding to arrange the columns one below the other

for 1&2 columns
a=1
b=2
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out<-names_2

for 3&4 columns
a=3
b=4
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out1<-names_2

till n-numbers
df1= rbind(samp_out,samp_out1,......samp_out_n)

output

 date   variable   value
2014     1_val       23
2015     1_val       22
2014     2_val       33
2016     2_val       12
.
.
2014     n_val      34
2016     n_val      99

Thanks in advance

Body:
The function melt in the package data.table does that:

melt(df, id = "Date", measure = patterns("_val"))

You can specify the name of the variable to pivot on (Date in this case) and a pattern in the variables you want to keep the values of. You can also supply a vector with all the variablenames instead.

> DT <- data.table(Date = c(2014,2013), `1_val` = c(33, 32), Date = c(2014, 2013), `2_val` = c(65, 34))
> DT
   Date 1_val Date 2_val
1: 2014    33 2014    65
2: 2013    32 2013    34
> melt(DT, id = "Date", measure = patterns("_val"))
   Date variable value
1: 2014    1_val    33
2: 2013    1_val    32
3: 2014    2_val    65
4: 2013    2_val    34


问:
How to add the output of an object's function to an array
This is hard to phrase into words but I want to get the returned value of a function that is stored in an object, add that value to an array and output it. I have made this all work but it doesn't change once ran again, so say it outputs the random number of 678 it will also output that same number next time and so on. I created this cool terminal in react that gets the command of the key if it exists and outputs it in my console by returning jsx.

Here is my file structure...

Here is my react code... ( I had issues formatting, here is a better version of the code below)

```<code>import React, { Component } from "react";
import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom';
import "./Main.css";
import Commands from "../Commands/Commands.js"

class Main extends Component {
    constructor(props){
        super(props);
        this.state = {inputValue: ''}
        this.outputs = ["type 'help' for information about     plunketTheTerminal"];

        this.commands = Commands;

        this.commands.keys = Object.keys(this.commands)
    }
handleSubmit = (event) => {
    if(event.key == "Enter") {
        if( this.state.inputValue != "" ) {
            if( this.commands.keys.includes(this.state.inputValue)) {
                this.outputs.unshift(this.commands[this.state.inputValue]);
            }
            else{
                this.outputs.unshift(`No command '${this.state.inputValue}' found.`)
            }
        }
        document.querySelector(".input-section").value = "";
    }
    this.forceUpdate()
}

handleChange = (e) => {
    this.setState({ inputValue: e.target.value })
}
render() {
    return(
        <div>
            <div className="terminal-header"></div>
            <div className="terminal-body">
                <div className="terminal-contents-wrapper">
                    <div className="output-item-wrapper">
                        {
                            this.outputs.map((output, index) => {
                                return <h1 className="output-item" key={ index }>{output}</h1>;
                            })
                        }
                    </div>
                    <div className="input-section-wrapper">
                        <input type="text" className="input-section" onKeyPress={this.handleSubmit} onChange={this.handleChange}/>
                        <span className="input-section-label">plunketTheTerminal@plunketTheTerminal-H170-D3H:~$</span>
                    </div>
                </div>
            </div>
        </div>
    )
    }
    };

export default Main;
</code>```

Finally my JavaScript file for the commands... ( again better code here )

```<code>const rand = () => {
   return Math.floor(Math.random() * 1000 ) + 1;
}

const Commands = {
    help: "plunketTheTerminal is a online terminal for fun, it contains lots     of different functions and commands. In fact you can actually SUBMIT YOUR OWN      COMMANDS at our github if you are good with computers :).",
    rand: rand(),
    "rand --info": "Will generate a random number between 1 and 1000",

}
export default Commands
</code>```

EDIT: Trying to use either of the following returns nothing.

```<code>rand: () => (
    "x"
),
</code>```

or

```<code>rand: () => {
    return "x"
},
</code>```

Here is a demonstration of what is happening...

I type the command...

I get my output which is fine...

but from then on repeating that same command won't generate a new random number i will continue to repeat the first returned value.

I would really appreciate some help but please keep in mind I am still learning react and JavaScript and would love to hear any constructive feedback. I will also continue to update information if needed. Thanks!

答:
Found out what was wrong, I was calling the function without its parentheses. I had to change the command file to the following...

```<code>const Commands = {
help: "plunketTheTerminal is a online terminal for fun, it contains lots of different functions and commands. In fact you can SUBMIT YOUR OWN COMMANDS at our github if you are good with computers :).",
rand: () => {
    return Math.floor(Math.random() * 1000 ) + 1;
},
//"rand --info": "Will generate a random number between 1 and 1000",

}
</code>```

and I had to change the line

```<code>this.outputs.unshift(this.commands[this.state.inputValue]);
</code>```

to

```<code>this.outputs.unshift(this.commands[this.state.inputValue]());
</code>```

silly mistake, hopefully this helps someone who has a somewhat similar problem, though I think it would be unlikely.

Body:
This is hard to phrase into words but I want to get the returned value of a function that is stored in an object, add that value to an array and output it. I have made this all work but it doesn't change once ran again, so say it outputs the random number of 678 it will also output that same number next time and so on. I created this cool terminal in react that gets the command of the key if it exists and outputs it in my console by returning jsx.

Here is my file structure...

Here is my react code... ( I had issues formatting, here is a better version of the code below)

import React, { Component } from "react";
import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom';
import "./Main.css";
import Commands from "../Commands/Commands.js"

class Main extends Component {
    constructor(props){
        super(props);
        this.state = {inputValue: ''}
        this.outputs = ["type 'help' for information about     plunketTheTerminal"];

        this.commands = Commands;

        this.commands.keys = Object.keys(this.commands)
    }
handleSubmit = (event) => {
    if(event.key == "Enter") {
        if( this.state.inputValue != "" ) {
            if( this.commands.keys.includes(this.state.inputValue)) {
                this.outputs.unshift(this.commands[this.state.inputValue]);
            }
            else{
                this.outputs.unshift(`No command '${this.state.inputValue}' found.`)
            }
        }
        document.querySelector(".input-section").value = "";
    }
    this.forceUpdate()
}

handleChange = (e) => {
    this.setState({ inputValue: e.target.value })
}
render() {
    return(

                        {
                            this.outputs.map((output, index) => {
                                return
{output}
;
                            })
                        }

                        <input type="text" className="input-section" onKeyPress={this.handleSubmit} onChange={this.handleChange}/>
                        plunketTheTerminal@plunketTheTerminal-H170-D3H:~$

    )
    }
    };

export default Main;

Finally my JavaScript file for the commands... ( again better code here )

const rand = () => {
   return Math.floor(Math.random() * 1000 ) + 1;
}

const Commands = {
    help: "plunketTheTerminal is a online terminal for fun, it contains lots     of different functions and commands. In fact you can actually SUBMIT YOUR OWN      COMMANDS at our github if you are good with computers :).",
    rand: rand(),
    "rand --info": "Will generate a random number between 1 and 1000",

}
export default Commands

EDIT: Trying to use either of the following returns nothing.

rand: () => (
    "x"
),

or

rand: () => {
    return "x"
},

Here is a demonstration of what is happening...

I type the command...

I get my output which is fine...

but from then on repeating that same command won't generate a new random number i will continue to repeat the first returned value.

I would really appreciate some help but please keep in mind I am still learning react and JavaScript and would love to hear any constructive feedback. I will also continue to update information if needed. Thanks!

Body:
Found out what was wrong, I was calling the function without its parentheses. I had to change the command file to the following...

const Commands = {
help: "plunketTheTerminal is a online terminal for fun, it contains lots of different functions and commands. In fact you can SUBMIT YOUR OWN COMMANDS at our github if you are good with computers :).",
rand: () => {
    return Math.floor(Math.random() * 1000 ) + 1;
},
//"rand --info": "Will generate a random number between 1 and 1000",

}

and I had to change the line

this.outputs.unshift(this.commands[this.state.inputValue]);

to

this.outputs.unshift(this.commands[this.state.inputValue]());

silly mistake, hopefully this helps someone who has a somewhat similar problem, though I think it would be unlikely.


问:
Detect if a user prints something via javascript
I've got a problem with detecting a print event in javascript.
For example, a user wats to print document and presses print in a web-page, then another window appers, e.g. to print from Adobe Reader, then appears another window of Adobe Reader where you can set properties, choose pages to print and what not...and there is the print button in this window. Can I actually detect when the user presses this print button inside this Adobe Reader window in browser using javascript?

I've already tried using onafterprint but maybe I didn't do this correctly or I'dont know.

it was something like this inside my main js file.

```<code>window.onbeforeprint = function() {
    console.log('This will be called before the user prints.');
};
window.onafterprint = function() {
    console.log('This will be called after the user prints');
};
</code>```

I took that from here: https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

答:
Have you tried using the matchMedia in that same link?

```<code>(function() {
    var beforePrint = function() {
        console.log('Functionality to run before printing.');
    };
    var afterPrint = function() {
        console.log('Functionality to run after printing');
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());
</code>```

Haven't done the full battery of browser compatibility checks, but that code works and prints both statements for me in Safari 10.1.1 whereas the onafterprint stuff doesn't work (though I exported as pdf once I was in the print dialog, since I don't have a printer).

I'm assume by Adobe Reader you just mean the normal print popup where you select a printer and number of copies/which pages/etc, since as far as I'm aware Adobe Reader is a desktop software

Body:
I've got a problem with detecting a print event in javascript.
For example, a user wats to print document and presses print in a web-page, then another window appers, e.g. to print from Adobe Reader, then appears another window of Adobe Reader where you can set properties, choose pages to print and what not...and there is the print button in this window. Can I actually detect when the user presses this print button inside this Adobe Reader window in browser using javascript?

I've already tried using onafterprint but maybe I didn't do this correctly or I'dont know.

it was something like this inside my main js file.

window.onbeforeprint = function() {
    console.log('This will be called before the user prints.');
};
window.onafterprint = function() {
    console.log('This will be called after the user prints');
};

I took that from here: https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

Body:
Have you tried using the matchMedia in that same link?

(function() {
    var beforePrint = function() {
        console.log('Functionality to run before printing.');
    };
    var afterPrint = function() {
        console.log('Functionality to run after printing');
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());

Haven't done the full battery of browser compatibility checks, but that code works and prints both statements for me in Safari 10.1.1 whereas the onafterprint stuff doesn't work (though I exported as pdf once I was in the print dialog, since I don't have a printer).

I'm assume by Adobe Reader you just mean the normal print popup where you select a printer and number of copies/which pages/etc, since as far as I'm aware Adobe Reader is a desktop software


问:
How to set more than one limit on for loop : javascript
I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

```<code>for(let a=0;a<usss.length || a<3;a++)
</code>```

Simple

```<code>var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}
</code>```

problem

```<code>var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}
</code>```

The way around,

```<code>var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}
</code>```

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it.
Any help or information will be appreciated. Thanks for your time.

答:
Its very simple, I think you just need to go through the length of the array.</p>

```<code> var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
  console.log(users2[a]);
}
</code>```

Body:
I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

for(let a=0;a<usss.length || a<3;a++)

Simple

var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}

problem

var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}

The way around,

var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it.
Any help or information will be appreciated. Thanks for your time.

Body:
Its very simple, I think you just need to go through the length of the array.

 var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
  console.log(users2[a]);
}


问:
changing the width of the rear view in SWRevealController
I have my views designed in the storyboard.
When I slide out the menu, the rear view does not automatically resize to the width of the device.

How can i set the width of the view so that it matches up with the width defined by self.revealViewController().rearViewRevealWidth?

thanks

答:
I wrote di swift 3 statements in the viewDidLoad of the my MasterController, where I programmatically configure SWRevealViewController (FrontController and RearController) and assign SWRevealViewController() to UIApplication.shared.delegate!.window?.rootViewController, but it it would work also in the viewDidLoad of your initial UIViewController </p>

```<code>let revealController = SWRevealViewController()

// settings to show full screen menu

// set width menu to screen size
revealController.rearViewRevealWidth = self.view.frame.width
// hide totally shadow
revealController.frontViewShadowOffset = CGSize.zero
revealController.frontViewShadowOpacity = 0

// optional settings

// no overdraw when dragging
revealController.rearViewRevealOverdraw = 0

// no displacement when animating or dragging the content
revealController.rearViewRevealDisplacement = 0
</code>```

Body:
I wrote di swift 3 statements in the viewDidLoad of the my MasterController, where I programmatically configure SWRevealViewController (FrontController and RearController) and assign SWRevealViewController() to UIApplication.shared.delegate!.window?.rootViewController, but it it would work also in the viewDidLoad of your initial UIViewController

let revealController = SWRevealViewController()

// settings to show full screen menu

// set width menu to screen size
revealController.rearViewRevealWidth = self.view.frame.width
// hide totally shadow
revealController.frontViewShadowOffset = CGSize.zero
revealController.frontViewShadowOpacity = 0

// optional settings

// no overdraw when dragging
revealController.rearViewRevealOverdraw = 0

// no displacement when animating or dragging the content
revealController.rearViewRevealDisplacement = 0


问:
As an abstract class cannot be instantiated, why is a constructor still allowed inside the abstract class?
what's the pure virtual function?what's the constructor function?</p>

```<code>public abstract class AmAbstract
{
    private String name;
    public  AmAbstract(){
    }
    public  AmAbstract(String name){
    }
}
</code>```

答:
The constructors of concrete sub-classes of an abstract class still have to invoke the constructor of their super-class, even when its abstract.

That said, there is no reason for the abstract class constructor to have public access. protected access is sufficient.

```<code>public class Concrete extends AmAbstract
{
    public Concrete () {
        super (); // invoke the constructor of the abstract class
    }
    public Concrete (String name){
        super (name); // invoke the constructor of the abstract class
    }
}
</code>```

Body:
what's the pure virtual function?what's the constructor function?

public abstract class AmAbstract
{
    private String name;
    public  AmAbstract(){
    }
    public  AmAbstract(String name){
    }
}

Body:
The constructors of concrete sub-classes of an abstract class still have to invoke the constructor of their super-class, even when its abstract.

That said, there is no reason for the abstract class constructor to have public access. protected access is sufficient.

public class Concrete extends AmAbstract
{
    public Concrete () {
        super (); // invoke the constructor of the abstract class
    }
    public Concrete (String name){
        super (name); // invoke the constructor of the abstract class
    }
}


问:
Android Internet connectivity check better method
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

答:
You can try this for check Internet connectivity:

```<code>/**
 * Check Connectivity of network.
 */
public static boolean isOnline(Context context) {
    try {
        if (context == null)
            return false;

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm != null) {
            if (cm.getActiveNetworkInfo() != null) {
                return cm.getActiveNetworkInfo().isConnected();
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    catch (Exception e) {
        Log.error("Exception", e);
        return false;
    }
}
</code>```

In your activity you call this function like this.

```<code>if(YourClass.isOnline(context))
{
  // Do your stuff here.
}
else
{
  // Show alert, no Internet connection.
}
</code>```

Don't forget to add ACCESS_NETWORK_STATE PERMISSION:

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

Try this if you want to just ping the URL:

```<code>public static boolean isPingAvailable(String myUrl) {
    boolean isAvailable = false;
    try {
        URL url = new URL(myUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        // 30 second time out.
        httpURLConnection.setConnectTimeout(30000);
        httpURLConnection.connect();
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            isAvailable = true;
        }
    } catch (Exception e) {
        isAvailable = false;
        e.printStackTrace();
    }
    return isAvailable;
}
</code>```

Body:
You can try this for check Internet connectivity:

/**
 * Check Connectivity of network.
 */
public static boolean isOnline(Context context) {
    try {
        if (context == null)
            return false;

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm != null) {
            if (cm.getActiveNetworkInfo() != null) {
                return cm.getActiveNetworkInfo().isConnected();
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    catch (Exception e) {
        Log.error("Exception", e);
        return false;
    }
}

In your activity you call this function like this.

if(YourClass.isOnline(context))
{
  // Do your stuff here.
}
else
{
  // Show alert, no Internet connection.
}

Don't forget to add ACCESS_NETWORK_STATE PERMISSION:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Try this if you want to just ping the URL:

public static boolean isPingAvailable(String myUrl) {
    boolean isAvailable = false;
    try {
        URL url = new URL(myUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        // 30 second time out.
        httpURLConnection.setConnectTimeout(30000);
        httpURLConnection.connect();
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            isAvailable = true;
        }
    } catch (Exception e) {
        isAvailable = false;
        e.printStackTrace();
    }
    return isAvailable;
}


问:
jQuery incrementing a cloned elements instead of cloned div
I had this HTML script which contains a drop list and a text box, and I just need to clone those two instead of the whole div, and then send the data to AJAX, and each drop list with text box will form an array that should be add as a single row in a table, that's what I have now:

```<code>        <div class="col-sm-4 rounded" style="background-color: #D3D3D3">
          <div class="row clonedInput" id="clonedInput1">
          <div class="col-sm-6 ">
              <label for="diagnosis_data">Medication</label>
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <div class="col-sm-6">
              <label for="medication_quantity">Quantity</label>
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <!-- End class="col-sm-6" -->
          </div>
          <div class="actions pull-right">
            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>
          </div>

        <!-- End class="col-sm-4" -->
        </div>
</code>```

And here is the jQuery Script:

```<code>$(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){

        $(this).closest(".rounded").clone()
            .insertAfter(".rounded:last")
            .attr("id", "rounded" +  (cloneIndex+1))
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = id.split('-')[0] +'-'+(cloneIndex);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parent().parent(".rounded").remove();
    }
</code>```

The problem is that the whole div is being cloned and just the div id is being changed:

Here is the id of each div is being incremented:

I need to clone the 2 elements only not the whole div and buttons

At the end I need t add them to database using Ajax and PHP

答:
You can add style to your actions class to prevent it from showing on all cloned elements

css

```<code>.actions {
  display: none;
}

.clonedInput:first-child .actions {
  display: block;
}
</code>```

Also for the removing function you could use .closest() instead of .parent().parent()

$(this).closest(".rounded").remove();

Body:
I had this HTML script which contains a drop list and a text box, and I just need to clone those two instead of the whole div, and then send the data to AJAX, and each drop list with text box will form an array that should be add as a single row in a table, that's what I have now:

              Medication
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>

              Quantity
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
                </fieldset>

            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>

And here is the jQuery Script:

$(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){

        $(this).closest(".rounded").clone()
            .insertAfter(".rounded:last")
            .attr("id", "rounded" +  (cloneIndex+1))
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = id.split('-')[0] +'-'+(cloneIndex);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parent().parent(".rounded").remove();
    }

The problem is that the whole div is being cloned and just the div id is being changed:

Here is the id of each div is being incremented:

I need to clone the 2 elements only not the whole div and buttons

At the end I need t add them to database using Ajax and PHP

Body:
You can add style to your actions class to prevent it from showing on all cloned elements

css

.actions {
  display: none;
}

.clonedInput:first-child .actions {
  display: block;
}

Also for the removing function you could use .closest() instead of .parent().parent()

$(this).closest(".rounded").remove();


问:
Delete statement conflicts with Reference constraint
I assume this has a very simple answer. I am brand new to entity framework and I am creating a test application consisting of Contacts and Groups as objects/entities.

Here is my code to delete a group:

```<code>    private void button_DeleteGroup_Click(object sender, EventArgs e)
    {
        var _selectedGroup = dataGridView_Groups.SelectedRows[0].DataBoundItem as Group;

        try
        {
            cgContext.Groups.Remove(_selectedGroup);
            cgContext.SaveChanges();

            PopulateGroupGrid();
            MessageBox.Show("Successfully deleted group from database!");
        }
        catch(Exception ex) { MessageBox.Show("Failed to delete group from database.\r\n\r\n" + ex); }
    }
</code>```

If I delete a group that a contact belongs to, to test referential integrity, an exception is thrown (as it should):

"The DELETE statement conflicted with the REFERENCE constraint
  "FK_dbo.Contacts_dbo.Groups_Group_Id". The conflict occurred in
  database "ContactGroups", table "dbo.Contacts", column
  'Group_Id'. The statement has been terminated."

I then catch this exception and display a message to the user. If I then go to add a new group or contact or do anything, the transaction fails with the same exception as before:

"The DELETE statement conflicted with the REFERENCE constraint
  "FK_dbo.Contacts_dbo.Groups_Group_Id". The conflict occurred in
  database "ContactGroups", table "dbo.Contacts", column
  'Group_Id'. The statement has been terminated."

So, obviously i'm not clearing / ending a transaction or something when the initial exception occurs. What am I doing wrong or missing?

答:
use WillCascadeOnDelete(true) for WithOptional

```<code>  modelBuilder.Entity<Parent>()
  .HasMany<Child>(c => c.Children)
  .WithOptional(x => x.Parent)
  .WillCascadeOnDelete(true);
</code>```

use Include

```<code>  var adv = db.Adv.Include(b => b.Features)
                  .Include(b => b.AdvDetails)
                  .Include(b => b.AdvGallery)
                  .FirstOrDefault(b => b.Id == id);
  db.Adv.Remove(adv);
</code>```

for .HasMany(...).WithMany(...) Include is ok

Body:
I assume this has a very simple answer. I am brand new to entity framework and I am creating a test application consisting of Contacts and Groups as objects/entities.

Here is my code to delete a group:

    private void button_DeleteGroup_Click(object sender, EventArgs e)
    {
        var _selectedGroup = dataGridView_Groups.SelectedRows[0].DataBoundItem as Group;

        try
        {
            cgContext.Groups.Remove(_selectedGroup);
            cgContext.SaveChanges();

            PopulateGroupGrid();
            MessageBox.Show("Successfully deleted group from database!");
        }
        catch(Exception ex) { MessageBox.Show("Failed to delete group from database.\r\n\r\n" + ex); }
    }

If I delete a group that a contact belongs to, to test referential integrity, an exception is thrown (as it should):

"The DELETE statement conflicted with the REFERENCE constraint
  "FK_dbo.Contacts_dbo.Groups_Group_Id". The conflict occurred in
  database "ContactGroups", table "dbo.Contacts", column
  'Group_Id'. The statement has been terminated."

I then catch this exception and display a message to the user. If I then go to add a new group or contact or do anything, the transaction fails with the same exception as before:

"The DELETE statement conflicted with the REFERENCE constraint
  "FK_dbo.Contacts_dbo.Groups_Group_Id". The conflict occurred in
  database "ContactGroups", table "dbo.Contacts", column
  'Group_Id'. The statement has been terminated."

So, obviously i'm not clearing / ending a transaction or something when the initial exception occurs. What am I doing wrong or missing?

Body:
use WillCascadeOnDelete(true) for WithOptional

  modelBuilder.Entity<Parent>()
  .HasMany<Child>(c => c.Children)
  .WithOptional(x => x.Parent)
  .WillCascadeOnDelete(true);

use Include

  var adv = db.Adv.Include(b => b.Features)
                  .Include(b => b.AdvDetails)
                  .Include(b => b.AdvGallery)
                  .FirstOrDefault(b => b.Id == id);
  db.Adv.Remove(adv);

for .HasMany(...).WithMany(...) Include is ok


问:
evaluating else if after an if condition is true
Consider this snippet:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}
</code>```

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

答:
You want the second if statement to run even if the first was true?
Get rid of the else</p>

ContentLicense: CC BY-SA 2.5

Body:
Consider this snippet:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?


问:
Create install anywhere launcher from executable jar
I have a jar file that is being created by Spring Boot. Application runs smoothly when run by command java -jar. I want to create an install anywhere launcher with this jar file.

What I have tried is to send the Spring Boot main class (PropertiesLauncher). The issue is that calling it like this won't load the nested jars inside my executable jar and also the loader.path doesn't seems to work.

Is there a way to call the executable jar like java -jar from the install anywhere launcher?

I was thinking that another option was to create an install anywhere launcher for a script file and inside have the java -jar call. So another question will be:
How do I create an install anywhere launcher for a script file?

答:
'execute command' step will do the trick:

Use this command line:

```<code>java -jar <path.to.jar.file>
</code>```

Use EXECUTE_STDOUT, EXECUTE_STDERR and EXECUTE_EXITCODE built-in variables to catch errors and parse the jar's execution result.

Important notes:

You'll have to make sure your jar includes all of the dependencies (or at least set the classpath in the command line);

To include the dependencies within your jar using eclipse you can:

Export your project as a 'runnable jar file' and select the
'Extract/Package required libraries into generated JAR' option/s

Use Maven to build the project with dependencies; the
maven-assembly-plugin is required.

The 'execute command' will work for batch/cmd/shell scripts as well, but you'll have to make sure the scripts are extracted to a local folder such as %TEMP% or /tmp before you can use them.

Goodluck

Body:
'execute command' step will do the trick:

Use this command line:

java -jar <path.to.jar.file>

Use EXECUTE_STDOUT, EXECUTE_STDERR and EXECUTE_EXITCODE built-in variables to catch errors and parse the jar's execution result.

Important notes:

You'll have to make sure your jar includes all of the dependencies (or at least set the classpath in the command line);

To include the dependencies within your jar using eclipse you can:

Export your project as a 'runnable jar file' and select the
'Extract/Package required libraries into generated JAR' option/s

Use Maven to build the project with dependencies; the
maven-assembly-plugin is required.

The 'execute command' will work for batch/cmd/shell scripts as well, but you'll have to make sure the scripts are extracted to a local folder such as %TEMP% or /tmp before you can use them.

Goodluck


问:
Counting number of words in Python file
I'm trying to count the number of instances several words appear in a file.

Here is my code:

```<code>#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))
</code>```

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

答:
Can you try this:  </p>

```<code>file = open('my_output', 'r')

splitFile = file.read().split()

lst = ['wordA','wordB','wordC']

for wrd in lst:
    print(wrd, splitFile.count(wrd))
</code>```

Title: Counting number of words in Python file

Body:
I'm trying to count the number of instances several words appear in a file.

Here is my code:

#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

Body:
Can you try this:

file = open('my_output', 'r')

splitFile = file.read().split()

lst = ['wordA','wordB','wordC']

for wrd in lst:
    print(wrd, splitFile.count(wrd))


答:
Define the untidy rectangle

```<code>library(magrittr)
csv <- "date,1_val,date,2_val,date,3_val
  2014,23,2014,33,2014,34
  2015,22,2016,12,2016,99"
</code>```

Read into a data frame, then transform into a long/eav rectangle.

```<code>ds_eav <- csv %>%
  readr::read_csv() %>%
  tibble::rownames_to_column(var="height") %>%
  tidyr::gather(key=key, value=value, -height)
</code>```

output:

```<code># A tibble: 12 x 4
     key index value height
   <chr> <int> <int>  <int>
 1  date     1  2014      1
 2  date     1  2015      2
 3 value     1    23      1
 4 value     1    22      2
 5  date     2  2014      1
 6  date     2  2016      2
 7 value     2    33      1
 8 value     2    12      2
 9  date     3  2014      1
10  date     3  2016      2
11 value     3    34      1
12 value     3    99      2
</code>```

Identify which rows are dates/values.  Then shift up dates' index by 1.

```<code>ds_eav <- ds_eav %>%
  dplyr::mutate(
    index_val  = sub("^(\\d+)_val$" , "\\1", key),
    index_date = sub("^date_(\\d+)$", "\\1", key),
    index_date = dplyr::if_else(key=="date", "0", index_date),
    key        = dplyr::if_else(grepl("^date(_\\d+)*", key), "date", "value"),
    index      = dplyr::if_else(key=="date", index_date, index_val),
    index      = as.integer(index),
    index      = index + dplyr::if_else(key=="date", 1L, 0L)
  ) %>%
  dplyr::select(key, index, value, height)
</code>```

Follow the advice of @jarko-dubbeldam and use spread/gather on the last step too

```<code>ds_eav %>%
  tidyr::spread(key=key, value=value)
</code>```

output:

```<code># A tibble: 6 x 4
  index height  date value
* <int>  <int> <int> <int>
1     1      1  2014    23
2     1      2  2015    22
3     2      1  2014    33
4     2      2  2016    12
5     3      1  2014    34
6     3      2  2016    99
</code>```

You can use paste0(index, "_val") to get you exact output.  But I'd prefer to keep them as integers, so you can do math on them in necessary (eg, max()).

edit 1: incorporate the advice & corrections of @jarko-dubbeldam and @hnskd.
edit 2: use rownames_to_column() in case the input isn't a balanced rectangle (eg, one column doesn't all all the rows).

Title: arrange one below the other every 2 columns from data frame in R

Body:
Hi I have a df as below which show date and their respected

date   1_val   date  2_val  . . . .  date  n_val
  2014   23      2014  33    . . . .  2014   34
  2015   22      2016  12    . . . .  2016   99

i have tried with hard coding to arrange the columns one below the other

for 1&2 columns
a=1
b=2
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out<-names_2

for 3&4 columns
a=3
b=4
names_2<-df[,c(a,b)]
colnames(names_2)[1]<-"Date"
names_2 <- names_2[!apply(is.na(names_2) | names_2 == "", 1, all),]
names_2<-melt(names_2,id=colnames(names_2)[1])
samp_out1<-names_2

till n-numbers
df1= rbind(samp_out,samp_out1,......samp_out_n)

output

 date   variable   value
2014     1_val       23
2015     1_val       22
2014     2_val       33
2016     2_val       12
.
.
2014     n_val      34
2016     n_val      99

Thanks in advance

Body:
Define the untidy rectangle

library(magrittr)
csv <- "date,1_val,date,2_val,date,3_val
  2014,23,2014,33,2014,34
  2015,22,2016,12,2016,99"

Read into a data frame, then transform into a long/eav rectangle.

ds_eav <- csv %>%
  readr::read_csv() %>%
  tibble::rownames_to_column(var="height") %>%
  tidyr::gather(key=key, value=value, -height)

output:

# A tibble: 12 x 4
     key index value height
   <chr> <int> <int>  <int>
 1  date     1  2014      1
 2  date     1  2015      2
 3 value     1    23      1
 4 value     1    22      2
 5  date     2  2014      1
 6  date     2  2016      2
 7 value     2    33      1
 8 value     2    12      2
 9  date     3  2014      1
10  date     3  2016      2
11 value     3    34      1
12 value     3    99      2

Identify which rows are dates/values.  Then shift up dates' index by 1.

ds_eav <- ds_eav %>%
  dplyr::mutate(
    index_val  = sub("^(\\d+)_val$" , "\\1", key),
    index_date = sub("^date_(\\d+)$", "\\1", key),
    index_date = dplyr::if_else(key=="date", "0", index_date),
    key        = dplyr::if_else(grepl("^date(_\\d+)*", key), "date", "value"),
    index      = dplyr::if_else(key=="date", index_date, index_val),
    index      = as.integer(index),
    index      = index + dplyr::if_else(key=="date", 1L, 0L)
  ) %>%
  dplyr::select(key, index, value, height)

Follow the advice of @jarko-dubbeldam and use spread/gather on the last step too

ds_eav %>%
  tidyr::spread(key=key, value=value)

output:

# A tibble: 6 x 4
  index height  date value
* <int>  <int> <int> <int>
1     1      1  2014    23
2     1      2  2015    22
3     2      1  2014    33
4     2      2  2016    12
5     3      1  2014    34
6     3      2  2016    99

You can use paste0(index, "_val") to get you exact output.  But I'd prefer to keep them as integers, so you can do math on them in necessary (eg, max()).

edit 1: incorporate the advice & corrections of @jarko-dubbeldam and @hnskd.
edit 2: use rownames_to_column() in case the input isn't a balanced rectangle (eg, one column doesn't all all the rows).


问:
Share on Facebook Image+AppLink Android
I have an app that enables users to share images on facebook; I'd like that automatically the link of the app could be shared together with the image.

This is the code I'm using but the part with the link is just ignored and doesn't appear:

```<code>Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/png");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath)));
shareIntent.putExtra(Intent.EXTRA_TEXT, "http://www.google.com"); //doesn't appear
PackageManager pm = context.getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList)
{

    Log.d("CitationsManager-ShareOnFb", app.activityInfo.name);
    if ((app.activityInfo.name).contains("facebook.katana")
        || (app.activityInfo.name).contains("facebook.composer.shareintent")
        || (app.activityInfo.name).contains("facebook.composer.activity"))
    {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(
            activity.applicationInfo.packageName, activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        shareIntent.setComponent(name);
        context.startActivity(shareIntent);
        break;
    }
</code>```

Do you have any idea how I can get the result? I've read questions on the topic but couldn't find a suitable solution.

Thanks

答:
Facebook provides shareDialog class to share images or content on facebook. You can read more details, check here</p>

```<code>     shareDialog = new ShareDialog(this);  // initialize facebook shareDialog.
    button.setOnClickListener(new View.OnClickListener() {
    @Override
   public void onClick(View v) {
   if (ShareDialog.canShow(ShareLinkContent.class)) {
         ShareLinkContent linkContent = new ShareLinkContent.Builder()
             .setContentTitle("Android Facebook Integration and Login Tutorial")
             .setImageUrl(Uri.parse("https://www.studytutorial.in/
                   wp-content/uploads/2017/02/FacebookLoginButton-min-300x136.png"))
             .setContentDescription(
                     "This tutorial explains how to integrate Facebook and Login
                     through Android Application")
             .setContentUrl(Uri.parse("https://www.studytutorial.in/
                         android-facebook-integration-and-login-tutorial"))
             .build();
                shareDialog.show(linkContent);  // Show facebook ShareDialog
       }
    }
});
</code>```

Title: Share on Facebook Image+AppLink Android

Body:
I have an app that enables users to share images on facebook; I'd like that automatically the link of the app could be shared together with the image.

This is the code I'm using but the part with the link is just ignored and doesn't appear:

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/png");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath)));
shareIntent.putExtra(Intent.EXTRA_TEXT, "http://www.google.com"); //doesn't appear
PackageManager pm = context.getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList)
{

    Log.d("CitationsManager-ShareOnFb", app.activityInfo.name);
    if ((app.activityInfo.name).contains("facebook.katana")
        || (app.activityInfo.name).contains("facebook.composer.shareintent")
        || (app.activityInfo.name).contains("facebook.composer.activity"))
    {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(
            activity.applicationInfo.packageName, activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        shareIntent.setComponent(name);
        context.startActivity(shareIntent);
        break;
    }

Do you have any idea how I can get the result? I've read questions on the topic but couldn't find a suitable solution.

Thanks

Body:
Facebook provides shareDialog class to share images or content on facebook. You can read more details, check here

     shareDialog = new ShareDialog(this);  // initialize facebook shareDialog.
    button.setOnClickListener(new View.OnClickListener() {
    @Override
   public void onClick(View v) {
   if (ShareDialog.canShow(ShareLinkContent.class)) {
         ShareLinkContent linkContent = new ShareLinkContent.Builder()
             .setContentTitle("Android Facebook Integration and Login Tutorial")
             .setImageUrl(Uri.parse("https://www.studytutorial.in/
                   wp-content/uploads/2017/02/FacebookLoginButton-min-300x136.png"))
             .setContentDescription(
                     "This tutorial explains how to integrate Facebook and Login
                     through Android Application")
             .setContentUrl(Uri.parse("https://www.studytutorial.in/
                         android-facebook-integration-and-login-tutorial"))
             .build();
                shareDialog.show(linkContent);  // Show facebook ShareDialog
       }
    }
});


问:
Autotools: should config.guess, depcomp or ltmain.sh be stored in the SVN repo?
I am taking over a project and I see in the subversion repository some files that belong to the distribution of libtool and automake such as config.guess, depcomp or ltmain.sh. I believe this is simply wrong because when I do the check out, I should have the autotools installed on my machine and do an autoreconf. </p>

<p>What do you think ?
Am I missing the point of having these files in the repository ? </p>

答: Almost anything that can be generated - and depcomp, etc. belong to that - should not be part of a tracked source repository.</p>

Body:
I am taking over a project and I see in the subversion repository some files that belong to the distribution of libtool and automake such as config.guess, depcomp or ltmain.sh. I believe this is simply wrong because when I do the check out, I should have the autotools installed on my machine and do an autoreconf.

What do you think ?
Am I missing the point of having these files in the repository ?


问:
Automatically sync using Unison
I am new to unison- the file synchronizing software.

I use unison to sync files between my local machine and a remote server. However, I have to do the synchronization manually every time.

Is there a way to trigger unison to synchronize automatically whenever a change is detected in the local folders set to be synchronized?

My OS : Ubuntu 16.04 LTS

答:
Yes. Check out the repeat = watch option.

Or if you want more control over what is watched and exactly what events trigger unison to run, check out inotify-tools and write a small script that runs in the background.

Title: Automatically sync using Unison


问:
Can't import opencv in Python 2.7: ImportError: No module named cv2 despite installed opencv 3.2.0
I used brew to install opencv 3.2.0 and it seems successful to me. Yet module cv2 still cannot be found when I tried to run this:

```<code>FF-MBP:read_video_frames ff$ python v2f.py
Traceback (most recent call last):
  File "v2f.py", line 4, in <module>
    import cv2
ImportError: No module named cv2
</code>```

The brew installation looks like this:

```<code>FF-MBP:read_video_frames ff$ brew install opencv3
==> Installing opencv3 from homebrew/science
==> Installing dependencies for homebrew/science/opencv3: eigen, jpeg, libpng, libtiff, ilmbase, openexr
==> Installing homebrew/science/opencv3 dependency: eigen
==> Downloading https://homebrew.bintray.com/bottles/eigen-3.3.4.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring eigen-3.3.4.sierra.bottle.tar.gz
==> Using the sandbox
  /usr/local/Cellar/eigen/3.3.4: 486 files, 6.5MB
==> Installing homebrew/science/opencv3 dependency: jpeg
==> Downloading https://homebrew.bintray.com/bottles/jpeg-8d.sierra.bottle.2.tar.gz
######################################################################## 100.0%
==> Pouring jpeg-8d.sierra.bottle.2.tar.gz
  /usr/local/Cellar/jpeg/8d: 19 files, 708.3KB
==> Installing homebrew/science/opencv3 dependency: libpng
==> Downloading https://homebrew.bintray.com/bottles/libpng-1.6.29.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libpng-1.6.29.sierra.bottle.tar.gz
  /usr/local/Cellar/libpng/1.6.29: 26 files, 1.2MB
==> Installing homebrew/science/opencv3 dependency: libtiff
==> Downloading https://homebrew.bintray.com/bottles/libtiff-4.0.8.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libtiff-4.0.8.sierra.bottle.tar.gz
  /usr/local/Cellar/libtiff/4.0.8: 245 files, 3.4MB
==> Installing homebrew/science/opencv3 dependency: ilmbase
==> Downloading https://homebrew.bintray.com/bottles/ilmbase-2.2.0.sierra.bottle.2.tar.gz
######################################################################## 100.0%
==> Pouring ilmbase-2.2.0.sierra.bottle.2.tar.gz
  /usr/local/Cellar/ilmbase/2.2.0: 362 files, 5.6MB
==> Installing homebrew/science/opencv3 dependency: openexr
==> Downloading https://homebrew.bintray.com/bottles/openexr-2.2.0.sierra.bottle.1.tar.gz
######################################################################## 100.0%
==> Pouring openexr-2.2.0.sierra.bottle.1.tar.gz
  /usr/local/Cellar/openexr/2.2.0: 131 files, 11.2MB
==> Installing homebrew/science/opencv3
==> Downloading https://homebrew.bintray.com/bottles-science/opencv3-3.2.0.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring opencv3-3.2.0.sierra.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local,
because opencv3 and opencv install many of the same files.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/opencv3/bin:$PATH"' >> ~/.bash_profile

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/opencv3/lib
    CPPFLAGS: -I/usr/local/opt/opencv3/include

If you need Python to find bindings for this keg-only formula, run:
  echo /usr/local/opt/opencv3/lib/python2.7/site-packages >> /usr/local/lib/python2.7/site-packages/opencv3.pth
==> Summary
  /usr/local/Cellar/opencv3/3.2.0: 286 files, 47.4MB
</code>```

Is it because opencv 3.0+ only compiles with Python3.x? I tried import cv3 - doesn't work.
Appreciate any inputs. Thank you!

Mac OS X: Sierra 10.12.5

Python: 2.7

OpenCV: 3.2.0

答: Use pip install to install opencv in windows. To install first go to cmd. Browse to opencv in cmd. pip install opencv to install it.

Body:
I used brew to install opencv 3.2.0 and it seems successful to me. Yet module cv2 still cannot be found when I tried to run this:

FF-MBP:read_video_frames ff$ python v2f.py
Traceback (most recent call last):
  File "v2f.py", line 4, in <module>
    import cv2
ImportError: No module named cv2

The brew installation looks like this:

FF-MBP:read_video_frames ff$ brew install opencv3
==> Installing opencv3 from homebrew/science
==> Installing dependencies for homebrew/science/opencv3: eigen, jpeg, libpng, libtiff, ilmbase, openexr
==> Installing homebrew/science/opencv3 dependency: eigen
==> Downloading https://homebrew.bintray.com/bottles/eigen-3.3.4.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring eigen-3.3.4.sierra.bottle.tar.gz
==> Using the sandbox
  /usr/local/Cellar/eigen/3.3.4: 486 files, 6.5MB
==> Installing homebrew/science/opencv3 dependency: jpeg
==> Downloading https://homebrew.bintray.com/bottles/jpeg-8d.sierra.bottle.2.tar.gz
######################################################################## 100.0%
==> Pouring jpeg-8d.sierra.bottle.2.tar.gz
  /usr/local/Cellar/jpeg/8d: 19 files, 708.3KB
==> Installing homebrew/science/opencv3 dependency: libpng
==> Downloading https://homebrew.bintray.com/bottles/libpng-1.6.29.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libpng-1.6.29.sierra.bottle.tar.gz
  /usr/local/Cellar/libpng/1.6.29: 26 files, 1.2MB
==> Installing homebrew/science/opencv3 dependency: libtiff
==> Downloading https://homebrew.bintray.com/bottles/libtiff-4.0.8.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libtiff-4.0.8.sierra.bottle.tar.gz
  /usr/local/Cellar/libtiff/4.0.8: 245 files, 3.4MB
==> Installing homebrew/science/opencv3 dependency: ilmbase
==> Downloading https://homebrew.bintray.com/bottles/ilmbase-2.2.0.sierra.bottle.2.tar.gz
######################################################################## 100.0%
==> Pouring ilmbase-2.2.0.sierra.bottle.2.tar.gz
  /usr/local/Cellar/ilmbase/2.2.0: 362 files, 5.6MB
==> Installing homebrew/science/opencv3 dependency: openexr
==> Downloading https://homebrew.bintray.com/bottles/openexr-2.2.0.sierra.bottle.1.tar.gz
######################################################################## 100.0%
==> Pouring openexr-2.2.0.sierra.bottle.1.tar.gz
  /usr/local/Cellar/openexr/2.2.0: 131 files, 11.2MB
==> Installing homebrew/science/opencv3
==> Downloading https://homebrew.bintray.com/bottles-science/opencv3-3.2.0.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring opencv3-3.2.0.sierra.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local,
because opencv3 and opencv install many of the same files.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/opencv3/bin:$PATH"' >> ~/.bash_profile

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/opencv3/lib
    CPPFLAGS: -I/usr/local/opt/opencv3/include

If you need Python to find bindings for this keg-only formula, run:
  echo /usr/local/opt/opencv3/lib/python2.7/site-packages >> /usr/local/lib/python2.7/site-packages/opencv3.pth
==> Summary
  /usr/local/Cellar/opencv3/3.2.0: 286 files, 47.4MB

Is it because opencv 3.0+ only compiles with Python3.x? I tried import cv3 - doesn't work.
Appreciate any inputs. Thank you!

Mac OS X: Sierra 10.12.5

Python: 2.7

OpenCV: 3.2.0


问:
dynamic Google Map triggering the null object reference error
I am trying to add a dynamic google map to a fragment, this fragment contains a simple form which is working ok, i am getting an error when i add the google map part.

Unable to start activity ComponentInfo{com.jdplee.proyecto/com.jdplee.proyecto.ClientDetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.jdplee.proyecto.ClientDetailFragment com.jdplee.proyecto.ClientDetailFragment.newInstance()' on a null object reference

What i have is a mainActivity with a button that opens a detail view, this is done using a second Activity:

```<code>public class ClientDetailActivity extends AppCompatActivity {

    public static final int REQUEST_ADD_TASK = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.client_detail);

        ClientDetailFragment mClientDetailFragment = (ClientDetailFragment)
                getSupportFragmentManager().findFragmentById(R.id.cd_fragment_container);

        if (mClientDetailFragment == null) {

            mClientDetailFragment = ClientDetailFragment.newInstance();

            utilities.addFragmentToActivity(getSupportFragmentManager(), mClientDetailFragment, R.id.cd_fragment_container);
        }
    }
}
</code>```

the client_layout only has a FrameLayout where the fragment is going to be put, the fragment class is:

```<code>public class ClientDetailFragment extends Fragment {

    private static final int PERMISSION_REQUEST_CODE = 1;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    public static ClientDetailFragment newInstance() {
        return new ClientDetailFragment();
    }

    public ClientDetailFragment(){
        //required empty constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.client_detail_fragment, container, false);

        if (getChildFragmentManager().findFragmentById(R.id.cd_maplocation) == null) {
            SupportMapFragment mapFragment = new SupportMapFragment();

            getChildFragmentManager()
                    .beginTransaction()
                    .replace(R.id.cd_maplocation, mapFragment)
                    .commit();
}

        return root;
    }
</code>```

and this fragment has his layout which inside has the framelayout for the google map:

```<code><FrameLayout
        android:id="@+id/cd_maplocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
</code>```

that is why i am using getChildFragment(), for me all this makes sense, i dont get why the error, am i missing something?

答:
put this thing on onActivityCreated()</p>

```<code>if (getChildFragmentManager().findFragmentById(R.id.cd_maplocation) == null) {
            SupportMapFragment mapFragment = new SupportMapFragment();

            getChildFragmentManager()
                    .beginTransaction()
                    .replace(R.id.cd_maplocation, mapFragment)
                    .commit();
    }
</code>```

Body:
I am trying to add a dynamic google map to a fragment, this fragment contains a simple form which is working ok, i am getting an error when i add the google map part.

Unable to start activity ComponentInfo{com.jdplee.proyecto/com.jdplee.proyecto.ClientDetailActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.jdplee.proyecto.ClientDetailFragment com.jdplee.proyecto.ClientDetailFragment.newInstance()' on a null object reference

What i have is a mainActivity with a button that opens a detail view, this is done using a second Activity:

public class ClientDetailActivity extends AppCompatActivity {

    public static final int REQUEST_ADD_TASK = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.client_detail);

        ClientDetailFragment mClientDetailFragment = (ClientDetailFragment)
                getSupportFragmentManager().findFragmentById(R.id.cd_fragment_container);

        if (mClientDetailFragment == null) {

            mClientDetailFragment = ClientDetailFragment.newInstance();

            utilities.addFragmentToActivity(getSupportFragmentManager(), mClientDetailFragment, R.id.cd_fragment_container);
        }
    }
}

the client_layout only has a FrameLayout where the fragment is going to be put, the fragment class is:

public class ClientDetailFragment extends Fragment {

    private static final int PERMISSION_REQUEST_CODE = 1;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    public static ClientDetailFragment newInstance() {
        return new ClientDetailFragment();
    }

    public ClientDetailFragment(){
        //required empty constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.client_detail_fragment, container, false);

        if (getChildFragmentManager().findFragmentById(R.id.cd_maplocation) == null) {
            SupportMapFragment mapFragment = new SupportMapFragment();

            getChildFragmentManager()
                    .beginTransaction()
                    .replace(R.id.cd_maplocation, mapFragment)
                    .commit();
}

        return root;
    }

and this fragment has his layout which inside has the framelayout for the google map:

<FrameLayout
        android:id="@+id/cd_maplocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

that is why i am using getChildFragment(), for me all this makes sense, i dont get why the error, am i missing something?

Body:
put this thing on onActivityCreated()

if (getChildFragmentManager().findFragmentById(R.id.cd_maplocation) == null) {
            SupportMapFragment mapFragment = new SupportMapFragment();

            getChildFragmentManager()
                    .beginTransaction()
                    .replace(R.id.cd_maplocation, mapFragment)
                    .commit();
    }


问:
How to export multiple excel columns into a text file without a tab indentation using VBA?
I was trying to export two columns into a text file. I've written the following code:

```<code>Dim wb As Workbook
Dim WorkRng As Range
Dim saveFile As String
//Some code for selecting the range

Set wb = Application.Workbooks.Add
WorkRng.Copy
wb.Worksheets(1).Paste

//Code for saving the file in *.txt
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False
</code>```

After saving the file. The rows in two columns are getting pasted as Tab separated. Is there any way I can paste them without any indentation?

As mentioned in one of the answers, if File format is xlCSV , I will get a file with Comma Separated Values. Similarly, I'd like to know how to get a ":" separated columns.

答:
You can loop through each line and concatenate the two columns before saving.</p>

```<code>Dim wb As Workbook
Dim WorkRng As Range
Dim saveFile As String
Dim sh As Worksheet
Dim rw As Range

//Some code for selecting the range

Set wb = Application.Workbooks.Add
WorkRng.Copy

Set sh = wb.Worksheets(1)
sh.Paste

For Each rw In sh.Rows
  If sh.Cells(rw.Row, 1).Value = "" Then
    Exit For
  End If

  rw.Cells(rw.Row, 1).Value = Concat(rw.Cells(rw.Row, 1).Value, rw.Cells(rw.Row, 2).Value)
  rw.Cells(rw.Row, 2).Value = ""
Next rw

//Code for saving the file in *.txt
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False
</code>```

Body:
I was trying to export two columns into a text file. I've written the following code:

Dim wb As Workbook
Dim WorkRng As Range
Dim saveFile As String
//Some code for selecting the range

Set wb = Application.Workbooks.Add
WorkRng.Copy
wb.Worksheets(1).Paste

//Code for saving the file in *.txt
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False

After saving the file. The rows in two columns are getting pasted as Tab separated. Is there any way I can paste them without any indentation?

As mentioned in one of the answers, if File format is xlCSV , I will get a file with Comma Separated Values. Similarly, I'd like to know how to get a ":" separated columns.

Body:
You can loop through each line and concatenate the two columns before saving.

Dim wb As Workbook
Dim WorkRng As Range
Dim saveFile As String
Dim sh As Worksheet
Dim rw As Range

//Some code for selecting the range

Set wb = Application.Workbooks.Add
WorkRng.Copy

Set sh = wb.Worksheets(1)
sh.Paste

For Each rw In sh.Rows
  If sh.Cells(rw.Row, 1).Value = "" Then
    Exit For
  End If

  rw.Cells(rw.Row, 1).Value = Concat(rw.Cells(rw.Row, 1).Value, rw.Cells(rw.Row, 2).Value)
  rw.Cells(rw.Row, 2).Value = ""
Next rw

//Code for saving the file in *.txt
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False


问:
Executing PHP via command line
I want to be able to execute PHP via command line with a $_GET variable.  I understand I can do this with exec, but I'd like to understand more of the security risk and what things I should look out for.  The parameter I want to pass is a MySQL auto_incremented ID returned from MySQL, so I'm not concerned with user input.  But by merely allowing this to happen what things should be considered in regards to security?

The script will accept an order ID and send the customer an email invoice.  This allows me to perform this function from multiple sections of the site only maintaining the code in 1 location.

答:
I don't think you really need to execute this from command line. Create a PHP function and include it in your multiple sections instead: it will be faster. Per example:

```<code>function sendInvoice($orderId) {
    // do something
}
</code>```

Then call it:

```<code>include_once('send_invoice.inc.php');
sendInvoice(42);
</code>```

This still allows code reuse and a single place where to maintain the code.

Title: Executing PHP via command line

Body:
I don't think you really need to execute this from command line. Create a PHP function and include it in your multiple sections instead: it will be faster. Per example:

function sendInvoice($orderId) {
    // do something
}

Then call it:

include_once('send_invoice.inc.php');
sendInvoice(42);

This still allows code reuse and a single place where to maintain the code.


问:
MS Bot framework emulator chang user id
Is there a way to change the default user id (which is 'default-user')  in bot emulator?

Or maybe it supports something about multi conversations in the same time?

I want to emulate two different users at the same time (because I have multiple user types in my project.

When I try to create new conversation like this

```<code>....
var connector = new ConnectorClient(new Uri(context.Activity.ServiceUrl));
var userAccount = new ChannelAccount("//here we need to provide user id which is always default-user", "Provider");
var botAccount = context.Activity.Recipient;

var conversation = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
var message = context.MakeMessage();
message.Recipient = userAccount;
message.From = botAccount;
message.Conversation = new ConversationAccount(false, conversation.Id);
await connector.Conversations.SendToConversationAsync((Activity) message);
</code>```

My emulator opens new conversation in the same chat-window

答:
Bot Framework Channel Emulator had the functions you need in the previous versions. In the latest one AFAIK changing user id and group conversation simulation are not available out of the box. However the good thing is that what this tool is doing - it is just sending http requests to your WebApi endpoint. It means that you can catch those requests using Fiddler or any other similar tool and then edit and reissue the request. It is a workaround, but for testing pusposes I think it is okay to use such an approach.

Below is the Fiddler screen and screen of debug session to show it is working:

If you want to go further and automate it - there is a REST Api documentation on botframework site, so you can build your own client.

Title: MS Bot framework emulator chang user id

Body:
Is there a way to change the default user id (which is 'default-user')  in bot emulator?

Or maybe it supports something about multi conversations in the same time?

I want to emulate two different users at the same time (because I have multiple user types in my project.

When I try to create new conversation like this

....
var connector = new ConnectorClient(new Uri(context.Activity.ServiceUrl));
var userAccount = new ChannelAccount("//here we need to provide user id which is always default-user", "Provider");
var botAccount = context.Activity.Recipient;

var conversation = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
var message = context.MakeMessage();
message.Recipient = userAccount;
message.From = botAccount;
message.Conversation = new ConversationAccount(false, conversation.Id);
await connector.Conversations.SendToConversationAsync((Activity) message);

My emulator opens new conversation in the same chat-window


问:
Uploading multiple images with crop images in codeigniter, but getting too much time & giving errors of $_FILES.. but working fine for low size images
I am uploading images using codeigniter:

1) path//uploads/Property/.. (original image)

2) path/uploads/Property/100X100/.. (cropped image)

3) path/uploads/Property/300X300/.. (cropped image)

My Code Snippet:

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

$cpt="";

$prp_id=$this->session->userdata('main_prop_id');
$user_email =$this->session->userdata('email');

if($_FILES['userfile']['name'] != ""){

$allowed =  array('jpg','jpeg' ,'gif','png');
$filename = $_FILES['userfile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);

    $testimg =$_FILES["userfile"]["name"];

      $ppfilename = preg_replace("/[^A-Za-z0-9_\w]+/", "", $testimg).".".$ext;

      $ppfilename = $ppfilename;
      $ppfilename = explode(".", $ppfilename);
      $ppnew_filename = "ad_" . $ppfilename[0] . time() . "." . $ppfilename[1];

      $ppthumb = explode(".", $ppnew_filename);
      $ppthumb = $ppthumb[0] . "_thumb". "." . $ppthumb[1];

      $_FILES["userfile"]["name"] = $ppnew_filename;
      $this->load->library("upload");

      $this->upload->initialize($this->set_upload_options());

      if($this->upload->do_upload()){
          $ppimagedata = $this -> upload -> data();
          $ppnewimagename = $ppimagedata["file_name"];

          $this -> load -> library("image_lib");
          $config['image_library']   = 'gd2';
          $config['source_image']    = $ppimagedata["full_path"];
          $config['create_thumb']    = TRUE;
          $config['maintain_ratio']  = TRUE;
          $config['new_image']       = './uploads/Property/100X100/';
          $config['width']           = 100;
          $config['height']          = 100;

          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();

          $config['new_image']    = './uploads/Property/300X300/';
          $config['width']       = 300;
          $config['height']       = 300;
          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();
           }
        }
        else{
          $ppnewimagename = "";
          $ppthumb = "";
        }

          $room_id = $this->input->post('roomid');

          $where = array('room_id'=>$room_id,'prop_id' => $prp_id,'user'=>$user_email);

           $arr3 =   array(
               'image_name' => $ppnewimagename,
               'image_thumb' => $ppthumb,

              );

        $insert_id = $this->home->updateTable('ci_room_details',$arr3,$where);

        $arr_f = array(
                  'property_id_fk' => $prp_id,
                  'image_name' => $ppnewimagename,
                  'image_thumb' => $ppthumb,
                  'room_id'=>$_POST['roomid'],
                  'entity_type_id_fk'=>$_POST['entity_type_id'],
                  'sub_entity_type_id_fk'=>$_POST['sub_entity_type_id']
              );

        $insert_id_f = $this->home->insertIntoTable('ci_property_images',$arr_f);

    $cpt = count($_FILES['images']['name']);

    if($cpt > 0){

      $img = array();

      for($i = 0; $i < $cpt; $i++) {
        if($_FILES['images']['name'][$i] == ""){
          unset($_FILES['images']['name'][$i]);
          unset($_FILES['images']['type'][$i]);
          unset($_FILES['images']['tmp_name'][$i]);
          unset($_FILES['images']['error'][$i]);
          unset($_FILES['images']['size'][$i]);
        }
      }

      $cpt = count($_FILES['images']['name']);

      for($i = 0; $i < $cpt; $i++) {
      if(isset($_FILES['images']['name'][$i])){
        if($_FILES['images']['name'][$i] != ""){

        $filename = $_FILES['images']['name'][$i];
        $ext1 = pathinfo($filename, PATHINFO_EXTENSION);
        $ranstr=random_string('alnum', 3);
        $new_filename = time() .$ranstr. "." . $ext1;
        $thumb = time() . $ranstr. "_thumb." . $ext1;

        $_FILES['imag']['name']     = $new_filename;
        $_FILES['imag']['type']     = $_FILES['images']['type'] [$i];
        $_FILES['imag']['tmp_name']   = $_FILES['images']['tmp_name'] [$i];
        $_FILES['imag']['error']     = $_FILES ['images']['error'] [$i];
        $_FILES['imag']['size']     = $_FILES ['images']['size'] [$i];

        $this->upload->initialize ( $this->set_upload_options());
        if($this->upload->do_upload ('imag')){

          $imagedata = $this -> upload -> data();
          $newimagename = $imagedata["file_name"];
          //100x100 resize thumb
          $this -> load -> library("image_lib");
          $config['image_library']  = 'gd2';
          $config['source_image']   = $imagedata["full_path"];
          $config['create_thumb']   = TRUE;
          $config['maintain_ratio'] = TRUE;
          $config['new_image']      = './uploads/Property/100X100/';
          $config['width']          = 100;
          $config['height']         = 100;
          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();
          //300x300 resize img
          $config['source_image']   = $imagedata["full_path"];
          $config['create_thumb']   = TRUE;
          $config['maintain_ratio'] = TRUE;
          $config['new_image']    = './uploads/Property/300X300/';
          $config['width']       = 300;
          $config['height']       = 300;
          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();
        }
        unset($_FILES['imag']);

        $img[] = array(
            'image_name' => $new_filename,
            'image_thumb' => $thumb
          );
      }
      }// end if

    } // end for

    }
    else{
      $img[] = array(

            'image_name' => "",
            'image_thumb' => ""
          );
    }

   $img_cnt=count($img);

      if($img_cnt > 0){
        for($i = 0; $i < $img_cnt; $i++) {

          $arr3 = array(
              'property_id_fk' => $prp_id,
                'image_name' => $img[$i]['image_name'],
                  'image_thumb' => $img[$i]['image_thumb'],
                  'room_id'=>$_POST['roomid'],
                  'entity_type_id_fk'=>$_POST['entity_type_id'],
                 'sub_entity_type_id_fk'=>$_POST['sub_entity_type_id']
              );

         $insert_id1 = $this->home->insertIntoTable('ci_property_images',$arr3);
        }
      }

       if($insert_id!=""){

        echo $room_id;

       }else{
          echo "";
       }

  exit;
}
</code>```

Working fine for low size images, but giving problem during high size image uploading.. due to much time to upload mozilla gives $_FILES['userfile']['..'] (undefined index error, but work properly low size images) & chrome alerts to kill operation.

I am offering to upload 5 images at time means 15 images (including crop images)

please suggest the changes in above code.. how can i speed up the upload process??

答:
The default values for PHP will restrict you to a maximum 2 MB upload file size. So to upload a file more than 2 MB you need to set the value of:

upload_max_filesize and post_max_size in your php.ini :

```<code>; Maximum allowed size for uploaded files.
upload_max_filesize = 10M

; Must be greater than or equal to upload_max_filesize
post_max_size = 10M
</code>```

and than restart your server to apply these settings.

Body:
I am uploading images using codeigniter:

1) path//uploads/Property/.. (original image)

2) path/uploads/Property/100X100/.. (cropped image)

3) path/uploads/Property/300X300/.. (cropped image)

My Code Snippet:

public function photoform(){

$cpt="";

$prp_id=$this->session->userdata('main_prop_id');
$user_email =$this->session->userdata('email');

if($_FILES['userfile']['name'] != ""){

$allowed =  array('jpg','jpeg' ,'gif','png');
$filename = $_FILES['userfile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);

    $testimg =$_FILES["userfile"]["name"];

      $ppfilename = preg_replace("/[^A-Za-z0-9_\w]+/", "", $testimg).".".$ext;

      $ppfilename = $ppfilename;
      $ppfilename = explode(".", $ppfilename);
      $ppnew_filename = "ad_" . $ppfilename[0] . time() . "." . $ppfilename[1];

      $ppthumb = explode(".", $ppnew_filename);
      $ppthumb = $ppthumb[0] . "_thumb". "." . $ppthumb[1];

      $_FILES["userfile"]["name"] = $ppnew_filename;
      $this->load->library("upload");

      $this->upload->initialize($this->set_upload_options());

      if($this->upload->do_upload()){
          $ppimagedata = $this -> upload -> data();
          $ppnewimagename = $ppimagedata["file_name"];

          $this -> load -> library("image_lib");
          $config['image_library']   = 'gd2';
          $config['source_image']    = $ppimagedata["full_path"];
          $config['create_thumb']    = TRUE;
          $config['maintain_ratio']  = TRUE;
          $config['new_image']       = './uploads/Property/100X100/';
          $config['width']           = 100;
          $config['height']          = 100;

          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();

          $config['new_image']    = './uploads/Property/300X300/';
          $config['width']       = 300;
          $config['height']       = 300;
          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();
           }
        }
        else{
          $ppnewimagename = "";
          $ppthumb = "";
        }

          $room_id = $this->input->post('roomid');

          $where = array('room_id'=>$room_id,'prop_id' => $prp_id,'user'=>$user_email);

           $arr3 =   array(
               'image_name' => $ppnewimagename,
               'image_thumb' => $ppthumb,

              );

        $insert_id = $this->home->updateTable('ci_room_details',$arr3,$where);

        $arr_f = array(
                  'property_id_fk' => $prp_id,
                  'image_name' => $ppnewimagename,
                  'image_thumb' => $ppthumb,
                  'room_id'=>$_POST['roomid'],
                  'entity_type_id_fk'=>$_POST['entity_type_id'],
                  'sub_entity_type_id_fk'=>$_POST['sub_entity_type_id']
              );

        $insert_id_f = $this->home->insertIntoTable('ci_property_images',$arr_f);

    $cpt = count($_FILES['images']['name']);

    if($cpt > 0){

      $img = array();

      for($i = 0; $i < $cpt; $i++) {
        if($_FILES['images']['name'][$i] == ""){
          unset($_FILES['images']['name'][$i]);
          unset($_FILES['images']['type'][$i]);
          unset($_FILES['images']['tmp_name'][$i]);
          unset($_FILES['images']['error'][$i]);
          unset($_FILES['images']['size'][$i]);
        }
      }

      $cpt = count($_FILES['images']['name']);

      for($i = 0; $i < $cpt; $i++) {
      if(isset($_FILES['images']['name'][$i])){
        if($_FILES['images']['name'][$i] != ""){

        $filename = $_FILES['images']['name'][$i];
        $ext1 = pathinfo($filename, PATHINFO_EXTENSION);
        $ranstr=random_string('alnum', 3);
        $new_filename = time() .$ranstr. "." . $ext1;
        $thumb = time() . $ranstr. "_thumb." . $ext1;

        $_FILES['imag']['name']     = $new_filename;
        $_FILES['imag']['type']     = $_FILES['images']['type'] [$i];
        $_FILES['imag']['tmp_name']   = $_FILES['images']['tmp_name'] [$i];
        $_FILES['imag']['error']     = $_FILES ['images']['error'] [$i];
        $_FILES['imag']['size']     = $_FILES ['images']['size'] [$i];

        $this->upload->initialize ( $this->set_upload_options());
        if($this->upload->do_upload ('imag')){

          $imagedata = $this -> upload -> data();
          $newimagename = $imagedata["file_name"];
          //100x100 resize thumb
          $this -> load -> library("image_lib");
          $config['image_library']  = 'gd2';
          $config['source_image']   = $imagedata["full_path"];
          $config['create_thumb']   = TRUE;
          $config['maintain_ratio'] = TRUE;
          $config['new_image']      = './uploads/Property/100X100/';
          $config['width']          = 100;
          $config['height']         = 100;
          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();
          //300x300 resize img
          $config['source_image']   = $imagedata["full_path"];
          $config['create_thumb']   = TRUE;
          $config['maintain_ratio'] = TRUE;
          $config['new_image']    = './uploads/Property/300X300/';
          $config['width']       = 300;
          $config['height']       = 300;
          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();
        }
        unset($_FILES['imag']);

        $img[] = array(
            'image_name' => $new_filename,
            'image_thumb' => $thumb
          );
      }
      }// end if

    } // end for

    }
    else{
      $img[] = array(

            'image_name' => "",
            'image_thumb' => ""
          );
    }

   $img_cnt=count($img);

      if($img_cnt > 0){
        for($i = 0; $i < $img_cnt; $i++) {

          $arr3 = array(
              'property_id_fk' => $prp_id,
                'image_name' => $img[$i]['image_name'],
                  'image_thumb' => $img[$i]['image_thumb'],
                  'room_id'=>$_POST['roomid'],
                  'entity_type_id_fk'=>$_POST['entity_type_id'],
                 'sub_entity_type_id_fk'=>$_POST['sub_entity_type_id']
              );

         $insert_id1 = $this->home->insertIntoTable('ci_property_images',$arr3);
        }
      }

       if($insert_id!=""){

        echo $room_id;

       }else{
          echo "";
       }

  exit;
}

Working fine for low size images, but giving problem during high size image uploading.. due to much time to upload mozilla gives $_FILES['userfile']['..'] (undefined index error, but work properly low size images) & chrome alerts to kill operation.

I am offering to upload 5 images at time means 15 images (including crop images)

please suggest the changes in above code.. how can i speed up the upload process??

Body:
The default values for PHP will restrict you to a maximum 2 MB upload file size. So to upload a file more than 2 MB you need to set the value of:

upload_max_filesize and post_max_size in your php.ini :

; Maximum allowed size for uploaded files.
upload_max_filesize = 10M

; Must be greater than or equal to upload_max_filesize
post_max_size = 10M

and than restart your server to apply these settings.