问:
Multilevel Slicing Pandas DataFrame
I have 3 DataFrames:

```<code>import pandas as pd
df1 =  pd.DataFrame( np.random.randn(100,4), index = pd.date_range('1/1/2010', periods=100), columns = {"A", "B", "C", "D"}).T.sort_index()
df2 =  pd.DataFrame( np.random.randn(100,4), index = pd.date_range('1/1/2010', periods=100), columns = {"A", "B", "C", "D"}).T.sort_index()
df3 =  pd.DataFrame( np.random.randn(100,4), index = pd.date_range('1/1/2010', periods=100), columns = {"A", "B", "C", "D"}).T.sort_index()
</code>```

I concatenate them creating a DataFrame with multi levels:

```<code>df_c = pd.concat([df1, df2, df3], axis = 1, keys = ["df1", "df2", "df3"])
</code>```

Swap levels and sort:

```<code>df_c.columns = df_c.columns.swaplevel(0,1)
df_c = df_c.reindex_axis(sorted(df_c.columns), axis = 1)

ipdb> df_c
    2010-01-01                     2010-01-02
     df1       df2       df3        df1       df2       df3
A  -0.798407  0.124091  0.271089   0.754759 -0.575769  1.501942
B   0.602091 -0.415828  0.152780   0.530525  0.118447  0.057240
C  -0.440619 -1.074837 -0.618084   0.627520 -1.298814  1.029443
D  -0.242851 -0.738948 -1.312393   0.559021  0.196936 -1.074277
</code>```

I would like to slice it to get values for individual rows, but so far I have only achieved such a degree of slicing:

```<code>cols = df_c.T.index.get_level_values(0)

ipdb> df_c.xs(cols[0], axis = 1, level = 0)
        df1       df2       df3
A -0.798407  0.124091  0.271089
B  0.602091 -0.415828  0.152780
C -0.440619 -1.074837 -0.618084
D -0.242851 -0.738948 -1.312393
</code>```

The only way I found to get the values for each raw is to define a new dataframe,

```<code>   slcd_df = df_c.xs(cols[0], axis = 1, level = 0)
</code>```

and then select rows using the usual proceadure:

```<code>  ipdb> slcd_df.ix["A", :]
  df1   -0.798407
  df2    0.124091
  df3    0.271089
</code>```

But I was wondering whether there exists a better (meaning faster and more elegant) way to slice multilevel Dataframes.

Title: Multilevel Slicing Pandas DataFrame

Body:
I have 3 DataFrames:

import pandas as pd
df1 =  pd.DataFrame( np.random.randn(100,4), index = pd.date_range('1/1/2010', periods=100), columns = {"A", "B", "C", "D"}).T.sort_index()
df2 =  pd.DataFrame( np.random.randn(100,4), index = pd.date_range('1/1/2010', periods=100), columns = {"A", "B", "C", "D"}).T.sort_index()
df3 =  pd.DataFrame( np.random.randn(100,4), index = pd.date_range('1/1/2010', periods=100), columns = {"A", "B", "C", "D"}).T.sort_index()

I concatenate them creating a DataFrame with multi levels:

df_c = pd.concat([df1, df2, df3], axis = 1, keys = ["df1", "df2", "df3"])

Swap levels and sort:

df_c.columns = df_c.columns.swaplevel(0,1)
df_c = df_c.reindex_axis(sorted(df_c.columns), axis = 1)

ipdb> df_c
    2010-01-01                     2010-01-02
     df1       df2       df3        df1       df2       df3
A  -0.798407  0.124091  0.271089   0.754759 -0.575769  1.501942
B   0.602091 -0.415828  0.152780   0.530525  0.118447  0.057240
C  -0.440619 -1.074837 -0.618084   0.627520 -1.298814  1.029443
D  -0.242851 -0.738948 -1.312393   0.559021  0.196936 -1.074277

I would like to slice it to get values for individual rows, but so far I have only achieved such a degree of slicing:

cols = df_c.T.index.get_level_values(0)

ipdb> df_c.xs(cols[0], axis = 1, level = 0)
        df1       df2       df3
A -0.798407  0.124091  0.271089
B  0.602091 -0.415828  0.152780
C -0.440619 -1.074837 -0.618084
D -0.242851 -0.738948 -1.312393

The only way I found to get the values for each raw is to define a new dataframe,

   slcd_df = df_c.xs(cols[0], axis = 1, level = 0)

and then select rows using the usual proceadure:

  ipdb> slcd_df.ix["A", :]
  df1   -0.798407
  df2    0.124091
  df3    0.271089

But I was wondering whether there exists a better (meaning faster and more elegant) way to slice multilevel Dataframes.

Body:
You can use pd.IndexSlice:

idx = pd.IndexSlice
sliced = df_c.loc["A", idx["2010-01-01", :]]
print(sliced)

2010-01-01  df1    0.199332
            df2    0.887018
            df3   -0.346778
Name: A, dtype: float64

Or you may also use slice(None):

print(df_c.loc["A", ("2010-01-01", slice(None))])

2010-01-01  df1    0.199332
            df2    0.887018
            df3   -0.346778
Name: A, dtype: float64


来源: stackexchange

问:
QuantLib installation fatal error C1083 boost/config.hpp & boost/test/unit_test.hpp
I know this issue has been discussed here before. But after I followed the suggestions and added the paths via Visual Studio, I'm still stuck:

In VS, I have:
Additional Include Directories: C:\local\boost_1_58_0
Additional Library Directories: C:\local\boost_1_58_0\libs

When I built QuantLib within VS, I could see C:\local\boost_1_58_0 is among the included paths. I can also see the valid config.hpp file in C:\local\boost_1_58_0\boost and unit_test.hpp in C:\local\boost_1_58_0\boost\test. Nevertheless I still got the C1083 error.

Have been stuck for 2+ days, I'm puzzled how to get around this. Any advice?

Thanks much in advance!

答: Follow the official instructions at http://quantlib.org/install/vc10.shtml.  In VS 10 and beyond, include and library paths are set through the Property Manager.  Steps 5 and 6 in the instructions linked above describe the procedure.  You might want to exit and restart the IDE to make sure that the changes are saved.</p>

ContentLicense: CC BY-SA 3.0


问:
Check CMTime Equals
Is there any method to check a CMTime is equal to another CMTime. In my case I need to check CMTime is equal to KCMTimeZero. I tried CMTimeCompare method, but it will be True for all the CMTimes which is equal to KCMTimeZero or greater than KCMTimeZero.</p>

答:
I prefer using CMTIME_COMPARE_INLINE macro defined in CMTime.h to keep code more readable.
Here is the code for your case (comparison with kCMTimeZero):

```<code>if (CMTIME_COMPARE_INLINE(myTime, ==, kCMTimeZero))
{
    // Your code here
}
</code>```

Title: Check CMTime Equals

Body:
I prefer using CMTIME_COMPARE_INLINE macro defined in CMTime.h to keep code more readable.
Here is the code for your case (comparison with kCMTimeZero):

if (CMTIME_COMPARE_INLINE(myTime, ==, kCMTimeZero))
{
    // Your code here
}


问:
List assignment
I have lists like this,

```<code>a=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
b=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
c=['name test', 'maximum-net-data-rate 4294967296', 'minimum-expected-throughput 1', 'maximum-gamma-data-rate 4294967296', 'minimum-gamma-data-rate 1']
</code>```

Here I am trying to replace each element of list 'a' one by one with the element of list 'c'.
I tried this code:

```<code>for i in range(len(a)):
    a[i]=c[i]
    print a
    a=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
</code>```

With this code I am getting correct output which is:

```<code>['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967296', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 1', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967296', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 1']
</code>```

But when I replaced the last statement(assigning) as

```<code>for i in range(len(a)):
    a[i]=c[i]
    print a
    a=b
</code>```

list 'b' also updating. How can i achieve this with out assigning the entire list directly.

答:
Just replace the last line with:</p>

```<code>a=b[:]
</code>```

Title: List assignment

Body:
I have lists like this,

a=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
b=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
c=['name test', 'maximum-net-data-rate 4294967296', 'minimum-expected-throughput 1', 'maximum-gamma-data-rate 4294967296', 'minimum-gamma-data-rate 1']

Here I am trying to replace each element of list 'a' one by one with the element of list 'c'.
I tried this code:

for i in range(len(a)):
    a[i]=c[i]
    print a
    a=['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']

With this code I am getting correct output which is:

['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967296', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 1', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967296', 'minimum-gamma-data-rate 0']
['name test', 'maximum-net-data-rate 4294967295', 'minimum-expected-throughput 0', 'maximum-gamma-data-rate 4294967295', 'minimum-gamma-data-rate 1']

But when I replaced the last statement(assigning) as

for i in range(len(a)):
    a[i]=c[i]
    print a
    a=b

list 'b' also updating. How can i achieve this with out assigning the entire list directly.

Body:
Just replace the last line with:

a=b[:]


问:
How to update a UITextField when receiving input from a UIPickerView?
Currently, I am programmatically creating a UITextField and UIPickerView within cellForRowAt. I can easily update the selected UIPickerView value within didSelectRow if I connect my UITextField to an IBOutlet.

However, I require the UITextField to be created programmatically with applied AutoLayout constraints.

However, I don't know how to update the UITextField as I have no reference to it in the UIPickerView's didSelectRow function since it's created programmatically within cellForRowAt like so:

```<code>var testing: [String] = []

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    // Dequeue the cell to load data
    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    if indexPath.section == 2
    {
        let wearsPickerView: UIPickerView = UIPickerView()

        wearsPickerView.delegate = self
        wearsPickerView.dataSource = self

        let textField: UITextField = UITextField()

        textField.translatesAutoresizingMaskIntoConstraints = false

        textField.textColor = UIColor.black

        textField.text = "Test"

        textField.delegate = self
        textField.inputView = wearsPickerView

        cell.contentView.addSubview(textField)

        let leadingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 0)
        let trailingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0)
        cell.contentView.addConstraint(leadingConstraint)
        cell.contentView.addConstraint(trailingConstraint)

        let topConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
        let bottomConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
        cell.contentView.addConstraint(topConstraint)
        cell.contentView.addConstraint(bottomConstraint)
    }

    return cell
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
    textField.resignFirstResponder()

    return true
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    return testing.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
    return testing[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    // How to update UITextField string?

}
</code>```

答:
You can get the cell for the corresponding index path, and find the textfield in that cell. You have 2 options for finding the textField. One would be to use tags, in case you had more than one UITextFields in that cell, which you don't. So you can do it like this:

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
  {
    // choose the correct row. I've assumed you only have one row.
    if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 2)) {
      for subview in cell.subviews {
        if let textField = subview as? UITextField {
          textField.text = testing[row]
          break
        }
      }
    }
  }
</code>```

Body:
Currently, I am programmatically creating a UITextField and UIPickerView within cellForRowAt. I can easily update the selected UIPickerView value within didSelectRow if I connect my UITextField to an IBOutlet.

However, I require the UITextField to be created programmatically with applied AutoLayout constraints.

However, I don't know how to update the UITextField as I have no reference to it in the UIPickerView's didSelectRow function since it's created programmatically within cellForRowAt like so:

var testing: [String] = []

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    // Dequeue the cell to load data
    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    if indexPath.section == 2
    {
        let wearsPickerView: UIPickerView = UIPickerView()

        wearsPickerView.delegate = self
        wearsPickerView.dataSource = self

        let textField: UITextField = UITextField()

        textField.translatesAutoresizingMaskIntoConstraints = false

        textField.textColor = UIColor.black

        textField.text = "Test"

        textField.delegate = self
        textField.inputView = wearsPickerView

        cell.contentView.addSubview(textField)

        let leadingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 0)
        let trailingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0)
        cell.contentView.addConstraint(leadingConstraint)
        cell.contentView.addConstraint(trailingConstraint)

        let topConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
        let bottomConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: textField, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
        cell.contentView.addConstraint(topConstraint)
        cell.contentView.addConstraint(bottomConstraint)
    }

    return cell
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
    textField.resignFirstResponder()

    return true
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    return testing.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
    return testing[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    // How to update UITextField string?

}

Body:
You can get the cell for the corresponding index path, and find the textfield in that cell. You have 2 options for finding the textField. One would be to use tags, in case you had more than one UITextFields in that cell, which you don't. So you can do it like this:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
  {
    // choose the correct row. I've assumed you only have one row.
    if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 2)) {
      for subview in cell.subviews {
        if let textField = subview as? UITextField {
          textField.text = testing[row]
          break
        }
      }
    }
  }


问:
Creating 2D matrix from RDD
I have the following RDD of the Type ((UserID, MovieID),1):

```<code>val data_wo_header=dropheader(data).map(_.split(",")).map(x=>((x(0).toInt,x(1).toInt),1))
</code>```

I want to convert this data structure into a 2D array such that all elements(userID Movie ID) present in the original RDD have a 1 else 0.

I think we have to map the user ID's to 0-N if N is the number of distinct users and map Movie ID's to 0-M if Mis the number of distinct movies.

EDIT: example

```<code>        Movie ID->

Userid  1 2 3 4 5 6 7

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

The RDD will be of the sort
(userID, movID,rating)
101,1002,3.5
101,1003,2.5
101,1006,3
102,1002,3.5
102,1004,4.0
103,1002,1.0
103,1003,1.0
103,1007,5.0
….
</code>```

Title: Creating 2D matrix from RDD

Body:
I have the following RDD of the Type ((UserID, MovieID),1):

val data_wo_header=dropheader(data).map(_.split(",")).map(x=>((x(0).toInt,x(1).toInt),1))

I want to convert this data structure into a 2D array such that all elements(userID Movie ID) present in the original RDD have a 1 else 0.

I think we have to map the user ID's to 0-N if N is the number of distinct users and map Movie ID's to 0-M if Mis the number of distinct movies.

EDIT: example

        Movie ID->

Userid  1 2 3 4 5 6 7

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

The RDD will be of the sort
(userID, movID,rating)
101,1002,3.5
101,1003,2.5
101,1006,3
102,1002,3.5
102,1004,4.0
103,1002,1.0
103,1003,1.0
103,1007,5.0
….

Body:
val baseRDD = sc.parallelize(Seq((101, 1002, 3.5), (101, 1003, 2.5), (101, 1006, 3), (102, 1002, 3.5), (102, 1004, 4.0), (103, 1002, 1.0), (103, 1003, 1.0), (103, 1007, 5.0)))
      baseRDD.map(x => (x._1, x._2)).groupByKey().foreach(println)

(userID, movID,rating) format as you mentioned

Result:

(101,CompactBuffer(1002, 1003, 1006))

(102,CompactBuffer(1002, 1004))

(103,CompactBuffer(1002, 1003, 1007))


问:
Get a date range covering 2 business weeks starting with current monday
I am having trouble adjusting a week range in PHP.

I have it working to show the current work week starting on monday.

So for this week it shows 11/29/2010 - 12/03/2010.

I need to modify this to start from the current work week's monday and show and end date of two fridays from the monday.

So for example currently it would show a start date of 11/29/2010 and and end date of 12/10/2010.

Here is my code

```<code><?
$timestamp = time();
echo date("m/d/Y", strtotime("this monday", $timestamp));
echo " - ";
echo date("m/d/Y", strtotime("Next Friday", $timestamp));
?>
</code>```

How do I add +7 to "Next Friday"

thx

答:
Just realised that "previous monday" only works the current day is tuesday or later...but it's a starting point for you..</p>

```<code><?php
    $monday = date('m/d/Y', strtotime("previous monday"));
    $friday = date('m/d/Y', strtotime($monday . " + 11 days"));
    echo $monday . ' - ' . $friday ;
?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am having trouble adjusting a week range in PHP.

I have it working to show the current work week starting on monday.

So for this week it shows 11/29/2010 - 12/03/2010.

I need to modify this to start from the current work week's monday and show and end date of two fridays from the monday.

So for example currently it would show a start date of 11/29/2010 and and end date of 12/10/2010.

Here is my code

<?
$timestamp = time();
echo date("m/d/Y", strtotime("this monday", $timestamp));
echo " - ";
echo date("m/d/Y", strtotime("Next Friday", $timestamp));
?>

How do I add +7 to "Next Friday"

thx

Body:
Just realised that "previous monday" only works the current day is tuesday or later...but it's a starting point for you..

<?php
    $monday = date('m/d/Y', strtotime("previous monday"));
    $friday = date('m/d/Y', strtotime($monday . " + 11 days"));
    echo $monday . ' - ' . $friday ;
?>


问:
Create a counting variable
I am given a vector "a":

```<code>a <-c(2, 1, 5)
</code>```

From this I need to create a vector (i.e. counting variable) that looks like that:

```<code>b <- c(1, 2, 1, 1, 2, 3, 4, 5)
</code>```

My input will be "a" the output should be "b".

So I want to count until I reach the first element in a(1)=2 --> 1,2; then I count until I reach the second element a(2)=1 --> 1; then the third a(3) --> 1,2,3,4,5;
Then combine it in one vector to get b=1,2,1,1,2,3,4,5

答:
Hello I don't know if it's the best answer but it works

```<code>b <- unlist(sapply(a,function(x) 1:x))
</code>```

edit : Jogo answer sequence(a) should be used

Title: Create a counting variable

Body:
I am given a vector "a":

a <-c(2, 1, 5)

From this I need to create a vector (i.e. counting variable) that looks like that:

b <- c(1, 2, 1, 1, 2, 3, 4, 5)

My input will be "a" the output should be "b".

So I want to count until I reach the first element in a(1)=2 --> 1,2; then I count until I reach the second element a(2)=1 --> 1; then the third a(3) --> 1,2,3,4,5;
Then combine it in one vector to get b=1,2,1,1,2,3,4,5

Body:
Hello I don't know if it's the best answer but it works

b <- unlist(sapply(a,function(x) 1:x))

edit : Jogo answer sequence(a) should be used


问:
css not loading property using express .ejs nodejs
Good evening everyone,

I would appreciate any help.

I got these two routes:

```<code>app.get('/', function(req,res){

        res.render('index');
});

app.get('/registration/add', function(req,res){

        res.render('clientRegistration');
});
</code>```

and this is part of the server:

```<code>app.use( express.static(path.join( __dirname, './client/static/')));
app.use(body_parser.urlencoded());
app.set( "views", path.join(__dirname, "./client/views/"));
app.set( "view engine", 'ejs');
</code>```

Directory is:

```<code>MyApp/
    client/
        static/
            registration.css
            styles.css
        views/
            index.ejs
            clientRegistration.ejs
</code>```

On my index.ejs, I have:
    link rel="stylesheet" type="text/css" href="styles.css" which loads the .css file perfectly. But when I click the link:
    a href="/registration/add"> on index.ejs,
it takes me to the clientRegistration.ejs page but the registration.css does not load even though I have:
    link rel="stylesheet" type="text/css" href="registration.css"

What am I doing wrong?

Thanks for your time.

答: Try to add a forward slash before your style.css href. As it seems to me, everything is setup correctly and it might be only a problem with the current folder reference.

Body:
Good evening everyone,

I would appreciate any help.

I got these two routes:

app.get('/', function(req,res){

        res.render('index');
});

app.get('/registration/add', function(req,res){

        res.render('clientRegistration');
});

and this is part of the server:

app.use( express.static(path.join( __dirname, './client/static/')));
app.use(body_parser.urlencoded());
app.set( "views", path.join(__dirname, "./client/views/"));
app.set( "view engine", 'ejs');

Directory is:

MyApp/
    client/
        static/
            registration.css
            styles.css
        views/
            index.ejs
            clientRegistration.ejs

On my index.ejs, I have:
    link rel="stylesheet" type="text/css" href="styles.css" which loads the .css file perfectly. But when I click the link:
    a href="/registration/add"> on index.ejs,
it takes me to the clientRegistration.ejs page but the registration.css does not load even though I have:
    link rel="stylesheet" type="text/css" href="registration.css"

What am I doing wrong?

Thanks for your time.


问:
generate a matrix of possible combinations using fortran
I have an array X(9,2) and I want to generate another array B(512,9) with all the possible combinations.

I thought about doing 9 do loops, but I was hoping for a more efficient way.

This is what I have

```<code>    do i1=1, 2
    do i2=1, 2
        do i3=1,2
            do i4=1,2
                do i5=1,2
                    do i6=1,2
                        do i7=1,2
                            do i8=i,2
                                do i9=1,2
                                    B(row, col) = X(1,i1)
                                    col = col + 1
                                    B(row, col) = X(2,i2)
                                    col = col + 1
                                    B(row, col) = X(3,i3)
                                    col = col + 1
                                    B(row, col) = X(4,i4)
                                    col = col + 1
                                    B(row, col) = X(5,i5)
                                    col = col + 1
                                    B(row, col) = X(6,i6)
                                    col = col + 1
                                    B(row, col) = X(7,i7)
                                    col = col + 1
                                    B(row, col) = X(8,i8)
                                    col = col + 1
                                    B(row, col) = X(9,i9)
                                    col = 1
                                    row = row + 1
                                end do
                            end do
                        end do
                    end do
                end do
            end do
        end do
    end do
end do
</code>```

Is there something wrong with this way? Is there a better way of doing this?

Thanks!

答:
```<code>  character *70 ofil
  ofil='allcomb.txt'
  write(*,*)'feed n and m (Note: n or m larger than 20 takes time)'
  read(*,*) n,m
  write(*,*)'feed file name to store results'
  read(*,*) ofil
  call combin(n,m,ofil)
  write(*,*)'Over'
  end
  !---------------------------------------------------------------
  subroutine combin(n,m,ofil)
  ! Generates all ncm combinatins
  parameter (mx=20)! mx is maximum dimension
  Integer a(mx),b(mx),c
  double precision ncm,ic
  character *70 ofil
  open(15,file=ofil)
  ncm=1
    do i=1,m
    a(i)=i ! a is least indexed combination
    b(i)=n-m+i ! b is maximum indexed combination
    ncm=ncm*b(i)/i ! total possible combinations
    enddo
  write (15,*) (a(i),i=1,m)! Initial (least indexed) combination
  incmpl=1
  ic=1
  ! --------------------------------------------------------------
  do while (incmpl.ne.0 .and.int(ic).lt.ncm)
  incm=0
    do i=1,m
    incm=incm+(b(i)-a(i))
    enddo
  incmpl=incm
  a(m)=a(m)+1
    do i=1,m
    ii=m-i+1
      if(a(ii).gt.b(ii)) then
      a(ii-1)=a(ii-1)+1
         do j=ii,m
         a(j)=a(j-1)+1
         enddo
      endif
    enddo
  ic=ic+1
  write(15,*)(a(k),k=1,m)
  enddo ! end do while loop
  ! --------------------------------------------------------------
  close(15)
  return
  end
</code>```

Body:
I have an array X(9,2) and I want to generate another array B(512,9) with all the possible combinations.

I thought about doing 9 do loops, but I was hoping for a more efficient way.

This is what I have

    do i1=1, 2
    do i2=1, 2
        do i3=1,2
            do i4=1,2
                do i5=1,2
                    do i6=1,2
                        do i7=1,2
                            do i8=i,2
                                do i9=1,2
                                    B(row, col) = X(1,i1)
                                    col = col + 1
                                    B(row, col) = X(2,i2)
                                    col = col + 1
                                    B(row, col) = X(3,i3)
                                    col = col + 1
                                    B(row, col) = X(4,i4)
                                    col = col + 1
                                    B(row, col) = X(5,i5)
                                    col = col + 1
                                    B(row, col) = X(6,i6)
                                    col = col + 1
                                    B(row, col) = X(7,i7)
                                    col = col + 1
                                    B(row, col) = X(8,i8)
                                    col = col + 1
                                    B(row, col) = X(9,i9)
                                    col = 1
                                    row = row + 1
                                end do
                            end do
                        end do
                    end do
                end do
            end do
        end do
    end do
end do

Is there something wrong with this way? Is there a better way of doing this?

Thanks!


问:
Synchronize all active threads C and release them one by one?
Is there a way in C to make all threads in a C program, wait for the other active Threads and then release them in the order they came, like a Queue of waiting threads?

答:
I'll attempt to help by giving you some notes I took last semester...

Threads

GCC program -lpthread

```<code>#include <pthread.h>
int main(int argc, char *argv[]) {
</code>```

This initiates the class / scheduler and names it mulo

```<code>pthread_mutex_t mulo = PTHREAD_MUTEX_INITIALIZER;
</code>```

This initiates a condition to stop and start executions of threads

```<code>pthread_cond_t  c = PTHREAD_COND_INITIALIZER;
</code>```

Define the structs that will be threads

```<code>pthread_t t1, t2, t3;
pthread_t array[3];   // this is valid to set multiple variables
</code>```

Define your scope / namespace

```<code>pthread_mutex_init(&mulo, NULL);
</code>```

Create the Processes

```<code>pthread_create(&t1, NULL, printMessage, NULL);
</code>```

or just..

```<code>fork();
</code>```

Validating creation, thread ids have type pid_t (int)

```<code>pid_t  pid;
pid = fork();   // All child processes return 0.. if    error = -1
</code>```

Locks (& unlock) a function so only one process can run it at a time

```<code>pthread_mutex_lock(&mulo);
pthread_mutex_unlock(&mulo);
</code>```

For signaling the unlock

```<code>pthread_cond_signal(&c);
pthread_cond_wait(&c, &mulo);
</code>```

All functions that use threading must be pointers to functions

```<code>void *printMessage() { …. }
pthread_create(&t1, NULL, printMessage, NULL);
</code>```

passing in values from the thread

```<code>pthread_create(&array[i], NULL, runCommand, (void *) &command);

void *inc_count(void *idp) {
    int passed_in_value = *((int *) idp);
    .
    .
    .
}
</code>```

finish it off

```<code>pthread_join(t1,NULL);
pthread_join(t2,NULL);
</code>```

Body:
I'll attempt to help by giving you some notes I took last semester...

Threads

GCC program -lpthread

#include <pthread.h>
int main(int argc, char *argv[]) {

This initiates the class / scheduler and names it mulo

pthread_mutex_t mulo = PTHREAD_MUTEX_INITIALIZER;

This initiates a condition to stop and start executions of threads

pthread_cond_t  c = PTHREAD_COND_INITIALIZER;

Define the structs that will be threads

pthread_t t1, t2, t3;
pthread_t array[3];   // this is valid to set multiple variables

Define your scope / namespace

pthread_mutex_init(&mulo, NULL);

Create the Processes

pthread_create(&t1, NULL, printMessage, NULL);

or just..

fork();

Validating creation, thread ids have type pid_t (int)

pid_t  pid;
pid = fork();   // All child processes return 0.. if    error = -1

Locks (& unlock) a function so only one process can run it at a time

pthread_mutex_lock(&mulo);
pthread_mutex_unlock(&mulo);

For signaling the unlock

pthread_cond_signal(&c);
pthread_cond_wait(&c, &mulo);

All functions that use threading must be pointers to functions

void *printMessage() { …. }
pthread_create(&t1, NULL, printMessage, NULL);

passing in values from the thread

pthread_create(&array[i], NULL, runCommand, (void *) &command);

void *inc_count(void *idp) {
    int passed_in_value = *((int *) idp);
    .
    .
    .
}

finish it off

pthread_join(t1,NULL);
pthread_join(t2,NULL);


问:
Get just header from remote csv file using papa parse
I need to extract just the header from a remote csv file.

My current method is as follows:

Papa parse has a method to stream data and look at each row individually which is great, and I can terminate the stream using parser.abort() to prevent it going any further after the first row, this looks as follows:

```<code>Papa.parse(csv_file_and_path,{header:true, worker:true,
    download: true,
    step: function(row, parser)
    {
        //DO MY STUFF HERE
        parser.abort();
    }
});
</code>```

This works fine, but because I am using a remote file, it has to download the data in order to read it.  Even though the code releases control back to the browser after the first line has been parsed, the download continues long after the parsing has found the first row and given me the information I need, particularly for large files where the download can continue for a long time after I've got what I need.

Is there a more efficient way of doing this?  Can I prevent papa parse from downloading the whole file?

I have tried using

```<code>Papa.parse(csv_file,{header:true,
download: true,
preview:1,
complete: function(results){
    //DO MY STUFF HERE
}
});
</code>```

But this does the same thing, it downloads the entire file, but as with the first approach gives back control to the browser after the first line is parsed.

答:
The solution I came up with is very similar to my original question, the difference being that I abort, complete and clear the memory.

Using the following method, only a single chunk of the file is downloaded, massively reducing bandwidth overhead for a large file as there is no downloading continuing after the first line is parsed.

```<code>Papa.parse(csv_file,{header:true,
    download: true,
    step: function(results, parser) {

        //DO MY THING HERE

        parser.abort();
        results=null;   //Attempting to clear the results from memory
        delete results; //Attempting to clear the results from memory

    }, complete: function(results){

        results=null;   //Attempting to clear the results from memory
        delete results; //Attempting to clear the results from memory

    }
});
</code>```

Body:
I need to extract just the header from a remote csv file.

My current method is as follows:

Papa parse has a method to stream data and look at each row individually which is great, and I can terminate the stream using parser.abort() to prevent it going any further after the first row, this looks as follows:

Papa.parse(csv_file_and_path,{header:true, worker:true,
    download: true,
    step: function(row, parser)
    {
        //DO MY STUFF HERE
        parser.abort();
    }
});

This works fine, but because I am using a remote file, it has to download the data in order to read it.  Even though the code releases control back to the browser after the first line has been parsed, the download continues long after the parsing has found the first row and given me the information I need, particularly for large files where the download can continue for a long time after I've got what I need.

Is there a more efficient way of doing this?  Can I prevent papa parse from downloading the whole file?

I have tried using

Papa.parse(csv_file,{header:true,
download: true,
preview:1,
complete: function(results){
    //DO MY STUFF HERE
}
});

But this does the same thing, it downloads the entire file, but as with the first approach gives back control to the browser after the first line is parsed.

Body:
The solution I came up with is very similar to my original question, the difference being that I abort, complete and clear the memory.

Using the following method, only a single chunk of the file is downloaded, massively reducing bandwidth overhead for a large file as there is no downloading continuing after the first line is parsed.

Papa.parse(csv_file,{header:true,
    download: true,
    step: function(results, parser) {

        //DO MY THING HERE

        parser.abort();
        results=null;   //Attempting to clear the results from memory
        delete results; //Attempting to clear the results from memory

    }, complete: function(results){

        results=null;   //Attempting to clear the results from memory
        delete results; //Attempting to clear the results from memory

    }
});


问:
Google Universal Analytics - Track download details
I am using the new Google Universal Analytics code and it tracks my page-views perfectly.

In addition to that I would like to track downloaded document details such as document name, UserID, etc.

When I googled, the suggestion was to include tracking code in OnClick method. But in my MVC application I am using ajax call and I am not using OnClick.

Is there any other option to track the same. Please let me know if there is a solution.

答:
Onclick is an implementation detail - the principle is that the tracking call should be placed in some sort of callback for the user action.

If you do an ajax call then you would presumably place the tracking call in the ajax success event (and check the response to see if the user action did return the expected result from the server). It's hard to be more specific without seeing some code.


问:
Backup-manager archive name when uploading to s3
I am using backup-manager to back up a directory's content say /home.

I want to upload the archive file to s3 bucket.
I have a directory structure in s3 bucket say /bucket_name/x/y/

If I write export BM_UPLOAD_S3_DESTINATION="bucket_name", the archive will be uploaded to bucket_name/

If I write in export BM_UPLOAD_S3_DESTINATION="bucket_name/x/y/", then error occurs that bucket name should not be like IP addresses.
But I want the archive to be uploaded to bucket_name/x/y/.

How can I achieve this?

答: As BM_ARCHIVE_PREFIX doesn't help, we can ask backup-manager to generate the backup file but not to upload it. We can write a script to upload the file and can specify whatever address we want in the script. That's the only feasible solution.


问:
connecting between two separate socket connections
I wrote a c# app that listens to port 8000 and 8001.

There are two different applications that connects to 8000 and 8001.
I have used socket arrays so that any number of connections are accepted.

Will I be able to some how attach one 8000 connection and 8001 connection in such a way that what ever data send by the application connected at 8000 will be received by the app at 8001 and vise versa. What is this concept known as ? sorry if this is a very basic question.

答: In Java there are PipedInputStream and PipedOutputStream. Maybe the C# library offers something similar?</p>

OwnerDisplayName: Nik Matt

OwnerDisplayName: Bombe


问:
How can I estimate the disk size of a string with JavaScript?
I need to try to estimate the DISK size of a text string (which could be raw text or a Base64 encoded string for an image/audio/etc) in JavaScript. I'm not sure how to estimate this. The only thing when Googling i can find is .length so i thought maybe someone on StackOverflow might know...

The reason i need to know is i have a localStorage script that needs (or would love to have) the ability to check when a user is nearing his 5MB (or 10MB in IE) quota and prompt them to increase the max size for the domain. So, if a user hits, lets say, 4.5MBs of data it'd prompt with

You're nearing your browsers 5MB data cap. Please increase your max data by... [instructions on increasing it for the browser]

答:
It's not going to be exact, but you can count the number of bytes in a string to get a rough estimation.

```<code>function bytes(string) {
    var escaped_string = encodeURI(string);
    if (escaped_string.indexOf("%") != -1) {
        var count = escaped_string.split("%").length - 1;
        count = count == 0 ? 1 : count;
        count = count + (escaped_string.length - (count * 3));
    }
    else {
        count = escaped_string.length;
    }</p>

```return count;
```

<p>}</p>

<p>var mystring = 'tâ';
alert(bytes(mystring));```

Body:
It's not going to be exact, but you can count the number of bytes in a string to get a rough estimation.

function bytes(string) {
    var escaped_string = encodeURI(string);
    if (escaped_string.indexOf("%") != -1) {
        var count = escaped_string.split("%").length - 1;
        count = count == 0 ? 1 : count;
        count = count + (escaped_string.length - (count * 3));
    }
    else {
        count = escaped_string.length;
    }

return count;

}

var mystring = 'tâ';
alert(bytes(mystring));


问:
SQL Trigger after insert not working
I tried to write a trigger that updates the data after an insert.

I'm using the SQL Server 2016 Import Export Data tool to transfer my data from Excel into the database.

After the import I need to run a few update statements.

I can save my trigger, but it's not updating any data. Where is my fault?

Trigger:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[TRG_InsertMappinng]
   ON  [dbo].[T_CCG_MBR2017_Across]
   AFTER  INSERT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE  [DB_CC_FC_Database_SQL].[dbo].[T_CCG_MBR2017_Across]
    SET [Colum1] = 'Text1'
    Where [Colum1] IS NULL
    AND [Colum2] = 'Text2'
    AND [Colum3] = 'Text3'
    AND [Colum4] = 'Text4'

END
</code>```

答: As written here, th SQL Import Export Data Tool doesn't fire any trigger. You can find more information about that here.</p>

Title: SQL Trigger after insert not working

Body:
I tried to write a trigger that updates the data after an insert.

I'm using the SQL Server 2016 Import Export Data tool to transfer my data from Excel into the database.

After the import I need to run a few update statements.

I can save my trigger, but it's not updating any data. Where is my fault?

Trigger:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[TRG_InsertMappinng]
   ON  [dbo].[T_CCG_MBR2017_Across]
   AFTER  INSERT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE  [DB_CC_FC_Database_SQL].[dbo].[T_CCG_MBR2017_Across]
    SET [Colum1] = 'Text1'
    Where [Colum1] IS NULL
    AND [Colum2] = 'Text2'
    AND [Colum3] = 'Text3'
    AND [Colum4] = 'Text4'

END


问:
Sliding Menu Bar is Working- But Not Well
I've been having a lot of trouble with this menu.  I have it working but the method I'm using is both buggy and inefficient.  Take a look at the jsfiddle, on first hover the pop-up menu does not have any animation.  However, on second hover and every hover after that the desired animation works.  Even if I get it to work on first hover it will still not be well made because when the user tries to access any of the items on the drop down the mouse out event is triggered and the menu begins to slide up.  Here's the Jquery I am using:

```<code>$(function(){
$('.dropdown').hover(function(){
    $('.dropdown-menu').stop().slideDown(250);
});
$('.dropdown').mouseout(function(){
    $('.dropdown-menu').stop().slideUp(250);
});
</code>```

I tried making the mouse out apply to the drop down menu as well by using:

```<code>$('.dropdown','.dropdown-menu').mouseout(function(){
</code>```

That just made it worse.  I am looking for a more efficient and user-friendly way to make my menu bar have the desired animations.

https://jsfiddle.net/ghcywu6L/

答:
You Can use this js code</p>

```<code>$(function(){
$(".dropdown").hover(
        function() {
            $('.dropdown-menu', this).stop( true, true ).slideDown("250");
            $(this).toggleClass('open');
            $('b', this).toggleClass("caret caret-up");
        },
        function() {
            $('.dropdown-menu', this).stop( true, true ).slideUp("250");
            $(this).toggleClass('open');
            $('b', this).toggleClass("caret caret-up");
        });
});
</code>```

Body:
I've been having a lot of trouble with this menu.  I have it working but the method I'm using is both buggy and inefficient.  Take a look at the jsfiddle, on first hover the pop-up menu does not have any animation.  However, on second hover and every hover after that the desired animation works.  Even if I get it to work on first hover it will still not be well made because when the user tries to access any of the items on the drop down the mouse out event is triggered and the menu begins to slide up.  Here's the Jquery I am using:

$(function(){
$('.dropdown').hover(function(){
    $('.dropdown-menu').stop().slideDown(250);
});
$('.dropdown').mouseout(function(){
    $('.dropdown-menu').stop().slideUp(250);
});

I tried making the mouse out apply to the drop down menu as well by using:

$('.dropdown','.dropdown-menu').mouseout(function(){

That just made it worse.  I am looking for a more efficient and user-friendly way to make my menu bar have the desired animations.

https://jsfiddle.net/ghcywu6L/

Body:
You Can use this js code

$(function(){
$(".dropdown").hover(
        function() {
            $('.dropdown-menu', this).stop( true, true ).slideDown("250");
            $(this).toggleClass('open');
            $('b', this).toggleClass("caret caret-up");
        },
        function() {
            $('.dropdown-menu', this).stop( true, true ).slideUp("250");
            $(this).toggleClass('open');
            $('b', this).toggleClass("caret caret-up");
        });
});


问:
Default timeout for HttpComponent Client
I can't find any documentation on the default httpParams for httpclient 4.1 ?

What's the default socket timeout when I do a GET ?

答:
https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/config/RequestConfig.html#getSocketTimeout%28%29

A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default).

Default: -1


问:
Image is getting scaled (zoom) when I merge image into word file
I am using below code to merge image in word document .it is not working for image with width 377 and height 650 .here is my code snippet.Please tell me how  to solve this issue  as the image that come in word format is getting zoom with ratio of 123% height and 123% width.</p>

```<code>                            private void createImage(){
                            List<Object> objects = sourceDocumentEl.getBody().getEGBlockLevelElts();

                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            ImageIO.write(bufferedImage, extension, baos);
                            baos.flush();

                            byte[] imageInByte = baos.toByteArray();

                            String filenameHint = null;
                            String altText = null;
                            int id1 = 0;
                            int id2 = 1;

                            org.docx4j.wml.P p = newImage(wordML, imageInByte,
                                    filenameHint, altText, id1, id2);
                            objects .add(p);
                        }

                     public static org.docx4j.wml.P newImage( WordprocessingMLPackage wordMLPackage,
                             byte[] bytes,
                             String filenameHint, String altText,
                             int id1, int id2) throws Exception {

                         BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);

                         Inline inline = imagePart.createImageInline( filenameHint, altText,
                                 id1, id2);

                         // Now add the inline in w:p/w:r/w:drawing
                         org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
                         org.docx4j.wml.P  p = factory.createP();
                         org.docx4j.wml.R  run = factory.createR();
                         p.getParagraphContent().add(run);
                         org.docx4j.wml.Drawing drawing = factory.createDrawing();
                         run.getRunContent().add(drawing);
                         drawing.getAnchorOrInline().add(inline);

                         return p;

                     }

enter code here
</code>```

答:
@jason -please check the attach image where u can clearly see the difference on local machine when i run above code and after is ,same code when i try to run on VM machine or Ubuntu Server.AfterImage

Before Image

The after image is getting zoomed.

Body:
I am using below code to merge image in word document .it is not working for image with width 377 and height 650 .here is my code snippet.Please tell me how  to solve this issue  as the image that come in word format is getting zoom with ratio of 123% height and 123% width.

                            private void createImage(){
                            List<Object> objects = sourceDocumentEl.getBody().getEGBlockLevelElts();

                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            ImageIO.write(bufferedImage, extension, baos);
                            baos.flush();

                            byte[] imageInByte = baos.toByteArray();

                            String filenameHint = null;
                            String altText = null;
                            int id1 = 0;
                            int id2 = 1;

                            org.docx4j.wml.P p = newImage(wordML, imageInByte,
                                    filenameHint, altText, id1, id2);
                            objects .add(p);
                        }

                     public static org.docx4j.wml.P newImage( WordprocessingMLPackage wordMLPackage,
                             byte[] bytes,
                             String filenameHint, String altText,
                             int id1, int id2) throws Exception {

                         BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);

                         Inline inline = imagePart.createImageInline( filenameHint, altText,
                                 id1, id2);

                         // Now add the inline in w:p/w:r/w:drawing
                         org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
                         org.docx4j.wml.P  p = factory.createP();
                         org.docx4j.wml.R  run = factory.createR();
                         p.getParagraphContent().add(run);
                         org.docx4j.wml.Drawing drawing = factory.createDrawing();
                         run.getRunContent().add(drawing);
                         drawing.getAnchorOrInline().add(inline);

                         return p;

                     }

enter code here


问:
libphp5.so missing
i installed php-5.2.17 with the following commands

```<code>./configure
make
make install
</code>```

installation went fine. but i dont find libphp5.so file can any one suggest me what went wrong and how to fix this error.

答: I had this same problem. I had installed php56.x86_64 from remi-safe, but when I installed php.x86_64 from remi-php56, then the library downloaded properly. </p>

Title: libphp5.so missing

Body:
i installed php-5.2.17 with the following commands

./configure
make
make install

installation went fine. but i dont find libphp5.so file can any one suggest me what went wrong and how to fix this error.


问:
How to upload pdf file in Laravel 5.2
I want to upload with this controller:

```<code>if(Input::has('status-text'))
        {
            $text=e(Input::get('status-text'));
            $rules = [
            'status_text'=>'required|string',
            ];
            $validator = Validator::make($request->all(), $rules);

            if(Input::hasFile('status_image_upload'))
            {
                $rules['status_image_upload'] = 'image';
                $validator = Validator::make($request->all(), $rules);
                if($validator->fails())
                {
                    $image = $request->file('status_image_upload');
                    $imageName = str_random(8).'_'.$image->getClientOriginalName();
                    $image->move('status_images', $imageName);
                    $userStatus = new Status();
                    $userStatus -> class_id = $id;
                    $userStatus -> status_text = $text;
                    $userStatus -> image_url = $imageName;
                    $userStatus -> type = 1;
                    $userStatus -> users_id = Auth::user()->id;
                    $userStatus -> save();
                    Flash::success('Your status has been posted');
                    return redirect(route('class',['class_id'=>$id]));
                }
            }
</code>```

I know this controller will work for upload pdf. But i want to store another colunm pdf_url. Whats why i can view file and pdf in my blade page.

答:
May this help

Don't forget to add 'files'=>'true' to the header of the form

```<code>{!! Form::open(array('url'=>'', 'method'=>'post', 'files'=>'true')) !!}
</code>```

and then in the controller

```<code>if ($file = $request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time() . '.' . $file->getClientOriginalExtension();
            $destinationPath = public_path() . '/images/';
            $file->move($destinationPath, $filename);
            $support->image = $filename;
        }
</code>```

and I suggest you use this package

intervention/image

Title: How to upload pdf file in Laravel 5.2

Body:
I want to upload with this controller:

if(Input::has('status-text'))
        {
            $text=e(Input::get('status-text'));
            $rules = [
            'status_text'=>'required|string',
            ];
            $validator = Validator::make($request->all(), $rules);

            if(Input::hasFile('status_image_upload'))
            {
                $rules['status_image_upload'] = 'image';
                $validator = Validator::make($request->all(), $rules);
                if($validator->fails())
                {
                    $image = $request->file('status_image_upload');
                    $imageName = str_random(8).'_'.$image->getClientOriginalName();
                    $image->move('status_images', $imageName);
                    $userStatus = new Status();
                    $userStatus -> class_id = $id;
                    $userStatus -> status_text = $text;
                    $userStatus -> image_url = $imageName;
                    $userStatus -> type = 1;
                    $userStatus -> users_id = Auth::user()->id;
                    $userStatus -> save();
                    Flash::success('Your status has been posted');
                    return redirect(route('class',['class_id'=>$id]));
                }
            }

I know this controller will work for upload pdf. But i want to store another colunm pdf_url. Whats why i can view file and pdf in my blade page.

Body:
May this help

Don't forget to add 'files'=>'true' to the header of the form

{!! Form::open(array('url'=>'', 'method'=>'post', 'files'=>'true')) !!}

and then in the controller

if ($file = $request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time() . '.' . $file->getClientOriginalExtension();
            $destinationPath = public_path() . '/images/';
            $file->move($destinationPath, $filename);
            $support->image = $filename;
        }

and I suggest you use this package

intervention/image


问:
How to send a file from one email to another email id in PHP?
I have PHP code where i code for sending attached file via email from one email id to another email id, But the name ,message ,email_id all send but not attached file sended.

```<code><?php

   $name=$_REQUEST['name'];
   $email_id=$_REQUEST['email_id'];
   $message=$_REQUEST['message'];
   $attached_file=$_REQUEST['attached_file'];
   $name= mysql_real_escape_string($name);
   $email_id = mysql_real_escape_string($email_id);
   if(isset($_REQUEST['submit']))
   {
    $sql="select * from user where BINARY name = BINARY '$name' AND
     BINARY email_id = BINARY '$email_id' and status='1'";
   $qex=mysql_query($sql);
   $numrow=mysql_num_rows($qex);
   $res=mysql_fetch_array($qex);
   if($numrow==1)
  {
    $_SESSION['name']=$res['name'];
   $_SESSION['email_id']=$res['email_id'];

        $email_to .= "nehamitta919@gmail.com";
        $email_subject="A user send Tariffs file to their Client";
        $email_from="neha@studioscue.in";

        $email_message = "User Attached File Successfully send     ".$time."\n\n";

        $email_message .= "User Name  : ".$name."\n\n";
        $email_message .= "User Email: ".$email_id."\n\n";
        $email_message .= "User Message: ".$message."\n\n";
        $email_message .= "User Send File: ".$attached_file."\n\n";

        $headers = 'From: '.$email_from."\r\n".
        'Reply-To: '.$email_from."\r\n" .
        'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers);

        ?>
</code>```

html code :

```<code><form class="form-horizontal" method="post" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-4 control-label">User name</font></label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="inputEmail3" placeholder="Name" required
                                name="name" value="<?Php echo $uvw['name']; ?>">
                            </div>
                            </div>
                        </div>
                    </div><!----row-------->
                    <br>
                    <br>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-4 control-label">User Email Id<br><strong>(Send From)</strong></font></label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="inputEmail3" ng-model="email_id" placeholder="email" required
                            name="email_id" value="<?Php echo $uvw['email_id']; ?>">
                        </div>
                        </div>
                    </div>
                </div><!----row-------->
                <br>
                <br>
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-4 control-label">Send To</font></label>
                    <div class="col-sm-4">
                        <select required class="form-control" id="client_id" name="client_id" ng-model="client_id">
                                          <option required="required" selected="" hidden="" value="">Select Your Client Email Id</option>
                                           <?php
                        $id= $_SESSION['id'];
                        $qex = mysql_query("select * from client where status!='4' and status!='0' and client.user_id='$id'");
                                            while ($res = mysql_fetch_array($qex)) {
                                                ?>
                                                <option value="<?php echo trim($res['group_id']); ?>">
                                                    <?php
                                                    echo trim($res['group_id']);
                                                    ?>
                                                </option>
                                            <?php }
                                            ?>

                    </select>
                </div>
                </div>
            </div>
        </div><!----row-------->
        <br />
        <br />
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="inputEmail3" class="col-sm-4 control-label">Message</font></label>
                <div class="col-sm-4">
                    <textarea class="form-control" id="inputEmail3" placeholder="Message" required style="height: 50px;"
                    name="message"></textarea>
                </div>
                </div>
            </div>
        </div><!----row-------->
        <br>
        <br>
    <div class="row"
        <div class="col-md-12">
            <div class="form-group">
                <label for="inputEmail3" class="img-rounded col-sm-4 control-label animate-css-css" >Attach File</font></label>
            <div class="col-sm-3">
                <input type="file"name="attached_file" id="attached_file" required>
            </div>
            </div>
        </div><!----row-------->
        <br>
        <br />
    <div class="form-group">
        <div class="col-sm-offset-5 col-sm-5">
            <button type="submit" class="btn btn-primary col-md-5" name="submit">Send File</button>
        </div>

    </div>
            </form>
</code>```

Please check & reply me. what am i missing.
Thanks & Regards
Ankit

答:
```<code>include("class.phpmailer.php");
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "mail.example.com";                       //your host name
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "yourname@example.com";                //email username
$mail->Password = "yourpassword";                        // email pass
$mail->setFrom('from@example.com', 'First Last');        //email adress
$mail->addReplyTo('replyto@example.com', 'First Last');,

$mail->addAddress('whoto@example.com', 'John Doe');      // whoto 1
$mail->addAddress('whoto@example.com', 'John Doe');      // whoto 2
$mail->addAddress('whoto@example.com', 'John Doe');      // whoto 3

$mail->Subject = 'PHPMailer SMTP test';                  // title
$mail->msgHTML($body);                                   // your message body

$mail->addAttachment('images/phpmailer_mini.png');        // file url
$mail->addAttachment('images/phpmailer_mini.png');        // file url
$mail->addAttachment('images/phpmailer_mini.png');        // file url

if (!$mail->send()) {
     echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
      echo "Message sent!";
 }
</code>```

Body:
I have PHP code where i code for sending attached file via email from one email id to another email id, But the name ,message ,email_id all send but not attached file sended.

<?php

   $name=$_REQUEST['name'];
   $email_id=$_REQUEST['email_id'];
   $message=$_REQUEST['message'];
   $attached_file=$_REQUEST['attached_file'];
   $name= mysql_real_escape_string($name);
   $email_id = mysql_real_escape_string($email_id);
   if(isset($_REQUEST['submit']))
   {
    $sql="select * from user where BINARY name = BINARY '$name' AND
     BINARY email_id = BINARY '$email_id' and status='1'";
   $qex=mysql_query($sql);
   $numrow=mysql_num_rows($qex);
   $res=mysql_fetch_array($qex);
   if($numrow==1)
  {
    $_SESSION['name']=$res['name'];
   $_SESSION['email_id']=$res['email_id'];

        $email_to .= "nehamitta919@gmail.com";
        $email_subject="A user send Tariffs file to their Client";
        $email_from="neha@studioscue.in";

        $email_message = "User Attached File Successfully send     ".$time."\n\n";

        $email_message .= "User Name  : ".$name."\n\n";
        $email_message .= "User Email: ".$email_id."\n\n";
        $email_message .= "User Message: ".$message."\n\n";
        $email_message .= "User Send File: ".$attached_file."\n\n";

        $headers = 'From: '.$email_from."\r\n".
        'Reply-To: '.$email_from."\r\n" .
        'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers);

        ?>

html code :

<form class="form-horizontal" method="post" enctype="multipart/form-data">

                                User name

                                <input type="text" class="form-control" id="inputEmail3" placeholder="Name" required
                                name="name" value="<?Php echo $uvw['name']; ?>">

                            User Email Id
(Send From)

                            <input type="text" class="form-control" id="inputEmail3" ng-model="email_id" placeholder="email" required
                            name="email_id" value="<?Php echo $uvw['email_id']; ?>">

                        Send To

                        <select required class="form-control" id="client_id" name="client_id" ng-model="client_id">
                                          <option required="required" selected="" hidden="" value="">Select Your Client Email Id</option>
                                           <?php
                        $id= $_SESSION['id'];
                        $qex = mysql_query("select * from client where status!='4' and status!='0' and client.user_id='$id'");
                                            while ($res = mysql_fetch_array($qex)) {
                                                ?>
                                                <option value="<?php echo trim($res['group_id']); ?>">
                                                    <?php
                                                    echo trim($res['group_id']);
                                                    ?>
                                                </option>
                                            <?php }
                                            ?>

                    </select>

                    Message

                    <textarea class="form-control" id="inputEmail3" placeholder="Message" required style="height: 50px;"
                    name="message"></textarea>

    <div class="row"

                Attach File

                <input type="file"name="attached_file" id="attached_file" required>

            <button type="submit" class="btn btn-primary col-md-5" name="submit">Send File</button>

            </form>

Please check & reply me. what am i missing.
Thanks & Regards
Ankit


问:
How to modify ttk Combobox fonts?
I've trying modifing the ttk.Combobox widget fonts using the traditional way

```<code>text_font = ('Courier New', '10')
mycombobox = Combobox(font = text_font)
mycombobox.pack()
</code>```

but the font doesn't really change...

I also tring using ttk.Style but again nothing happens...

```<code>text_font = ('Courier New', '10')
ttk_style = ttk.Style()
ttk_style.configure('App.TCombobox', font=text_font)

mycombobox = Combobox(style = "App.TCombobox")
mycombobox.pack()
</code>```

Is there a way to control the fonts? I want to change both the Entry and the ListBox fonts

答:
It's really strange behavior, because it's works well on my side:

```<code>try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

import random
import string

def insert_something_to_combobox(box):
    box['values'] = [gen_key() for _ in range(10)]

def gen_key(size=6, chars=string.ascii_uppercase + string.digits):
    # just to generate some random stuff
    return ''.join(random.choice(chars) for _ in range(size))

root = tk.Tk()
text_font = ('Courier New', '10')
main_frame = tk.Frame(root, bg='gray')                  # main frame
combo_box = ttk.Combobox(main_frame, font=text_font)    # apply font to combobox
entry_box = ttk.Entry(main_frame, font=text_font)       # apply font to entry
root.option_add('*TCombobox*Listbox.font', text_font)   # apply font to combobox list
combo_box.pack()
entry_box.pack()
main_frame.pack()

insert_something_to_combobox(combo_box)

root.mainloop()
</code>```

It's also possible to specify a font for a particular combobox, since we can rely on ttk::combobox::PopdownWindow function:

```<code>...
class CustomBox(ttk.Combobox):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.bind('<Map>', self._handle_popdown_font)

    def _handle_popdown_font(self, *args):
        popdown = self.tk.eval('ttk::combobox::PopdownWindow %s' % self)
        self.tk.call('%s.f.l' % popdown, 'configure', '-font', self['font'])
...
root = tk.Tk()
text_font = ('Courier New', '10')
main_frame = tk.Frame(root, bg='gray')                  # main frame
combo_box = CustomBox(main_frame, font=text_font)       # apply font to combobox
entry_box = ttk.Entry(main_frame, font=text_font)       # apply font to entry
...
root.mainloop()
</code>```

However, this CustomBox lacks functionality, because popdown's font is configured once combobox widget is mapped, hence any later configuration of the font won't configure this option for the popdown.

Let's try to override default configuration method:

```<code>class CustomBox(ttk.Combobox):
    def __init__(self, *args, **kwargs):
        #   initialisation of the combobox entry
        super().__init__(*args, **kwargs)
        #   "initialisation" of the combobox popdown
        self._handle_popdown_font()

    def _handle_popdown_font(self):
        """ Handle popdown font
        Note: https://github.com/nomad-software/tcltk/blob/master/dist/library/ttk/combobox.tcl#L270
        """
        #   grab (create a new one or get existing) popdown
        popdown = self.tk.eval('ttk::combobox::PopdownWindow %s' % self)
        #   configure popdown font
        self.tk.call('%s.f.l' % popdown, 'configure', '-font', self['font'])

    def configure(self, cnf=None, **kw):
        """Configure resources of a widget. Overridden!

        The values for resources are specified as keyword
        arguments. To get an overview about
        the allowed keyword arguments call the method keys.
        """

        #   default configure behavior
        self._configure('configure', cnf, kw)
        #   if font was configured - configure font for popdown as well
        if 'font' in kw or 'font' in cnf:
            self._handle_popdown_font()

    #   keep overridden shortcut
    config = configure
</code>```

This class will produce a more responsive instance of the combobox.

Title: How to modify ttk Combobox fonts?

Body:
I've trying modifing the ttk.Combobox widget fonts using the traditional way

text_font = ('Courier New', '10')
mycombobox = Combobox(font = text_font)
mycombobox.pack()

but the font doesn't really change...

I also tring using ttk.Style but again nothing happens...

text_font = ('Courier New', '10')
ttk_style = ttk.Style()
ttk_style.configure('App.TCombobox', font=text_font)

mycombobox = Combobox(style = "App.TCombobox")
mycombobox.pack()

Is there a way to control the fonts? I want to change both the Entry and the ListBox fonts

Body:
It's really strange behavior, because it's works well on my side:

try:
    import tkinter as tk
    import tkinter.ttk as ttk
except ImportError:
    import Tkinter as tk
    import ttk

import random
import string

def insert_something_to_combobox(box):
    box['values'] = [gen_key() for _ in range(10)]

def gen_key(size=6, chars=string.ascii_uppercase + string.digits):
    # just to generate some random stuff
    return ''.join(random.choice(chars) for _ in range(size))

root = tk.Tk()
text_font = ('Courier New', '10')
main_frame = tk.Frame(root, bg='gray')                  # main frame
combo_box = ttk.Combobox(main_frame, font=text_font)    # apply font to combobox
entry_box = ttk.Entry(main_frame, font=text_font)       # apply font to entry
root.option_add('*TCombobox*Listbox.font', text_font)   # apply font to combobox list
combo_box.pack()
entry_box.pack()
main_frame.pack()

insert_something_to_combobox(combo_box)

root.mainloop()

It's also possible to specify a font for a particular combobox, since we can rely on ttk::combobox::PopdownWindow function:

...
class CustomBox(ttk.Combobox):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.bind('<Map>', self._handle_popdown_font)

    def _handle_popdown_font(self, *args):
        popdown = self.tk.eval('ttk::combobox::PopdownWindow %s' % self)
        self.tk.call('%s.f.l' % popdown, 'configure', '-font', self['font'])
...
root = tk.Tk()
text_font = ('Courier New', '10')
main_frame = tk.Frame(root, bg='gray')                  # main frame
combo_box = CustomBox(main_frame, font=text_font)       # apply font to combobox
entry_box = ttk.Entry(main_frame, font=text_font)       # apply font to entry
...
root.mainloop()

However, this CustomBox lacks functionality, because popdown's font is configured once combobox widget is mapped, hence any later configuration of the font won't configure this option for the popdown.

Let's try to override default configuration method:

class CustomBox(ttk.Combobox):
    def __init__(self, *args, **kwargs):
        #   initialisation of the combobox entry
        super().__init__(*args, **kwargs)
        #   "initialisation" of the combobox popdown
        self._handle_popdown_font()

    def _handle_popdown_font(self):
        """ Handle popdown font
        Note: https://github.com/nomad-software/tcltk/blob/master/dist/library/ttk/combobox.tcl#L270
        """
        #   grab (create a new one or get existing) popdown
        popdown = self.tk.eval('ttk::combobox::PopdownWindow %s' % self)
        #   configure popdown font
        self.tk.call('%s.f.l' % popdown, 'configure', '-font', self['font'])

    def configure(self, cnf=None, **kw):
        """Configure resources of a widget. Overridden!

        The values for resources are specified as keyword
        arguments. To get an overview about
        the allowed keyword arguments call the method keys.
        """

        #   default configure behavior
        self._configure('configure', cnf, kw)
        #   if font was configured - configure font for popdown as well
        if 'font' in kw or 'font' in cnf:
            self._handle_popdown_font()

    #   keep overridden shortcut
    config = configure

This class will produce a more responsive instance of the combobox.


问:
What could be causing 'error transferring file' in maven?
I have installed maven 2.2.1 on my debian machine and getting the following error

```<code>[WARNING] repository metadata for: 'org.apache.maven.plugins' could not be retrieved  from repository: central due to an error: Error transferring file: repository.exoplatform.org
</code>```

What I have been able to find relating to this problem is its typically caused by not having proxy settings correctly configured or a firewall blocking traffic, but I dont have either on this machine. Also, I have the same settings file on my windows machine and it works fine.

Any suggestions would be greatly appreciated as I am stumped.

```<code>exo@melb-web:~/test$ mvn -v
Apache Maven 2.2.1 (r801777; 2009-08-07 05:16:01+1000)
Java version: 1.5.0_22
Java home: /usr/local/bin/jdk1.5.0_22/jre
Default locale: en_AU, platform encoding: UTF-8
OS name: "linux" version: "2.6.22-3-amd64" arch: "i386" Family: "unix"
exo@melb-web:~/test$ mvn archetype:generate
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] org.apache.maven.plugins: checking for updates from central
[WARNING] repository metadata for: 'org.apache.maven.plugins' could not be retrieved from repository: central due to an error: Error transferring file: repository.exoplatform.org
[INFO] Repository 'central' will be blacklisted
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] The plugin 'org.apache.maven.plugins:maven-archetype-plugin' does not exist or no valid version could be found
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Wed Jun 30 10:18:33 EST 2010
[INFO] Final Memory: 2M/136M
[INFO] ------------------------------------------------------------------------
</code>```

* EDIT *

I tried removing the settings.xml and generating a new maven project. I got the following

```<code>exo@melb-web:~/test$ mvn archetype:generate
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] org.apache.maven.plugins: checking for updates from central
[WARNING] repository metadata for: 'org.apache.maven.plugins' could not be retrieved from repository: central due to an error: Error transferring file: repo1.maven.org
[INFO] Repository 'central' will be blacklisted
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] The plugin 'org.apache.maven.plugins:maven-archetype-plugin' does not exist or no valid version could be found
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Wed Jun 30 11:40:26 EST 2010
[INFO] Final Memory: 1M/136M
[INFO] ------------------------------------------------------------------------
</code>```

I think this rules out it being a problem with the settings.xml or a pom. Is there a way to get more information about why maven cant connect to the repository?

答: I had the same problem.  In my case it was actually a leftover settings.xml file from a prior job.  I backed up and removed ~/.m2/settings.xml and the build went through just fine.</p>

Body:
I have installed maven 2.2.1 on my debian machine and getting the following error

[WARNING] repository metadata for: 'org.apache.maven.plugins' could not be retrieved  from repository: central due to an error: Error transferring file: repository.exoplatform.org

What I have been able to find relating to this problem is its typically caused by not having proxy settings correctly configured or a firewall blocking traffic, but I dont have either on this machine. Also, I have the same settings file on my windows machine and it works fine.

Any suggestions would be greatly appreciated as I am stumped.

exo@melb-web:~/test$ mvn -v
Apache Maven 2.2.1 (r801777; 2009-08-07 05:16:01+1000)
Java version: 1.5.0_22
Java home: /usr/local/bin/jdk1.5.0_22/jre
Default locale: en_AU, platform encoding: UTF-8
OS name: "linux" version: "2.6.22-3-amd64" arch: "i386" Family: "unix"
exo@melb-web:~/test$ mvn archetype:generate
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] org.apache.maven.plugins: checking for updates from central
[WARNING] repository metadata for: 'org.apache.maven.plugins' could not be retrieved from repository: central due to an error: Error transferring file: repository.exoplatform.org
[INFO] Repository 'central' will be blacklisted
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] The plugin 'org.apache.maven.plugins:maven-archetype-plugin' does not exist or no valid version could be found
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Wed Jun 30 10:18:33 EST 2010
[INFO] Final Memory: 2M/136M
[INFO] ------------------------------------------------------------------------

* EDIT *

I tried removing the settings.xml and generating a new maven project. I got the following

exo@melb-web:~/test$ mvn archetype:generate
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] org.apache.maven.plugins: checking for updates from central
[WARNING] repository metadata for: 'org.apache.maven.plugins' could not be retrieved from repository: central due to an error: Error transferring file: repo1.maven.org
[INFO] Repository 'central' will be blacklisted
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] The plugin 'org.apache.maven.plugins:maven-archetype-plugin' does not exist or no valid version could be found
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: < 1 second
[INFO] Finished at: Wed Jun 30 11:40:26 EST 2010
[INFO] Final Memory: 1M/136M
[INFO] ------------------------------------------------------------------------

I think this rules out it being a problem with the settings.xml or a pom. Is there a way to get more information about why maven cant connect to the repository?


问:
React Native pass parameters through map function
I am just learning React Native and I want to create a series of buttons using dynamic data.  My current code is:

```<code>var locations = this.state.campus.map(function(item, key){
            return(
                <TouchableHighlight key={key}
                style={[styles.button, (this.state.location==={item} && styles.buttonPressed)]}
                underlayColor='#dddddd'
                onPress={()=>this.buttonPress({item})} >
               <Text style={
                   styles.plainText}>{item}</Text>
            </TouchableHighlight>
           )
</code>```

My issue is with the lines

```<code>style={[styles.button, (this.state.location==={item} && styles.buttonPressed)]}
</code>```

and

```<code>onPress={()=>this.buttonPress({item})}
</code>```

I am trying generate these lines using the data dynamically off the map function.  These lines of code work perfectly if I use static data (ie generate each button separately), but fail using dynamic data.  The code does produce a display so the issue is not with rendering, the issue is with the functionality.

With the button press I get the error message undefined in not an object while the style simply causes the whole display not to render.

It is obvious that the dynamic data ({item}) works inside the Text element but not when passed to the other two elements as data. I have tried using {{item}} but this throws a syntax error.

Is there a way to handle dynamic data like this in React Native?

答:
This method is work:
1) Create function for creating elements with dynamic datas

```<code>createElement = (item) => {
    return(
        <TouchableHighlight onPress={()=>this.buttonPress({item})}>
            <Text style={ styles.plainText }> {item} </Text>
        </TouchableHighlight>
    )
};
</code>```

2) Use this function into render function how in follow example:

```<code>render (
    elementsList = [];
    for (var i = 0; i < 10; i++){
        elementsList.push( this.createElement(i) );
    };

    return (
        <View>
            {elementsList}
        </View>
    )
);
</code>```

It work, if you understand how use this.

Body:
I am just learning React Native and I want to create a series of buttons using dynamic data.  My current code is:

var locations = this.state.campus.map(function(item, key){
            return(
                <TouchableHighlight key={key}
                style={[styles.button, (this.state.location==={item} && styles.buttonPressed)]}
                underlayColor='#dddddd'
                onPress={()=>this.buttonPress({item})} >
               <Text style={
                   styles.plainText}>{item}</Text>
            </TouchableHighlight>
           )

My issue is with the lines

style={[styles.button, (this.state.location==={item} && styles.buttonPressed)]}

and

onPress={()=>this.buttonPress({item})}

I am trying generate these lines using the data dynamically off the map function.  These lines of code work perfectly if I use static data (ie generate each button separately), but fail using dynamic data.  The code does produce a display so the issue is not with rendering, the issue is with the functionality.

With the button press I get the error message undefined in not an object while the style simply causes the whole display not to render.

It is obvious that the dynamic data ({item}) works inside the Text element but not when passed to the other two elements as data. I have tried using {{item}} but this throws a syntax error.

Is there a way to handle dynamic data like this in React Native?

Body:
This method is work:
1) Create function for creating elements with dynamic datas

createElement = (item) => {
    return(
        <TouchableHighlight onPress={()=>this.buttonPress({item})}>
            <Text style={ styles.plainText }> {item} </Text>
        </TouchableHighlight>
    )
};

2) Use this function into render function how in follow example:

render (
    elementsList = [];
    for (var i = 0; i < 10; i++){
        elementsList.push( this.createElement(i) );
    };

    return (
        <View>
            {elementsList}
        </View>
    )
);

It work, if you understand how use this.


问:
What is the css property for showing the ... when there is overflow-x?
The property overflow-x shows scrollbar when the content exceeds the parent's width. I do not want to show the scrollbar but instead show the three dots "..." How to achieve that ?

答:
This will only apply with text.

MDN - text-overflow

This property only affects content that is overflowing a block
  container element in its inline progression direction (not text
  overflowing at the bottom of a box, for example). Text can overflow
  when it is prevented from wrapping (e.g., due to ‘white-space:
  nowrap’) or a single word being too long to fit.

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  border: 1px solid #ddd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="truncate">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
Anim consequat. magna in et ullamco laborum. qui ea laboris non dolore anim nulla dolor irure sint Excepteur do esse in nostrud consectetur tempor Excepteur ullamco proident, ut enim tempor laboris enim eiusmod exercitation ut sed anim Excepteur dolor enim elit, mollit minim culpa consectetur cupidatat consectetur magna commodo in ut sed eu irure amet, Ut Ut Lorem Excepteur occaecat eiusmod ut ipsum in.
</div></code>```

If you need a working solution that applies to anything other than text, you may need to consider javascript.

Body:
This will only apply with text.

MDN - text-overflow

This property only affects content that is overflowing a block
  container element in its inline progression direction (not text
  overflowing at the bottom of a box, for example). Text can overflow
  when it is prevented from wrapping (e.g., due to ‘white-space:
  nowrap’) or a single word being too long to fit.

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  border: 1px solid #ddd;
}

<div class="truncate">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
Anim consequat. magna in et ullamco laborum. qui ea laboris non dolore anim nulla dolor irure sint Excepteur do esse in nostrud consectetur tempor Excepteur ullamco proident, ut enim tempor laboris enim eiusmod exercitation ut sed anim Excepteur dolor enim elit, mollit minim culpa consectetur cupidatat consectetur magna commodo in ut sed eu irure amet, Ut Ut Lorem Excepteur occaecat eiusmod ut ipsum in.
</div>

If you need a working solution that applies to anything other than text, you may need to consider javascript.