问:
Highcharts Export Server: Polar Chart Ignoring Formatters in Callback
We're currently generating a polar chart in HighCharts that renders correctly on the client-side (in the browser), and correctly applies formatters to the xAxis, yAxis, and plotOptions. Here is a jsFiddle that shows how it is rendering (correctly) in the browser: https://jsfiddle.net/cmodzelewski/38f03Lse/1/

On the server side, we are constructing a JSON payload and sending it to a node-export-server instance and returning a PNG. Based on our research, it is clear that formatters need to be included in the callback key of our JSON payload and passed to the server as a string, rather than in the infile key.

That's fine, and so we're converting our formatter functions into strings, composing them into the options object in our callback key, and then redrawing the chart at the end of our callback key.

This approach works great for non-polar charts, but if polar == true the export server returns a valid PNG from the export server, however that chart does not apply our formatter functions to the xAxis, yAxis, or plotOptions.series.

Here is the JSON payload that we are sending to a node-export-server instance:

```<code>{
    "callback": "function (chart) {var options = chart.options;var xAxisFormatter = function () { var extra_hrs = 0; if (this.value == 0) { extra_hrs = 12; }; return ((this.value / 0.5)/60) + extra_hrs + ':00'; };if (\"labels\" in options[\"xAxis\"]) { options[\"xAxis\"][\"labels\"][\"formatter\"] = xAxisFormatter; } else { options[\"xAxis\"][\"labels\"] = { \"formatter\": xAxisFormatter, \"style\": { \"fontSize\": \"8px\" } }; };var yAxisFormatter = function () { return Highcharts.numberFormat(this.value, 2, '.', ',') + \"%\"; };if (\"labels\" in options[\"yAxis\"]) { options[\"yAxis\"][\"labels\"][\"formatter\"] = yAxisFormatter; } else { options[\"yAxis\"][\"labels\"] = { \"formatter\": yAxisFormatter, \"style\": { \"fontSize\": \"8px\" } };};var plotOptionsFormatter = function () { return Highcharts.numberFormat(this.value, 2, '.', ',') + \"%\"; };options[\"plotOptions\"][\"series\"][\"dataLabels\"][\"formatter\"] = plotOptionsFormatter;chart = new Highcharts.chart(chart.container, options);chart.redraw();}",
    "infile": "{chart: {backgroundColor: \"white\", borderWidth: 0, height: 300, polar: true, width: 300}, colors: [\"#16C1F3\", \"#3C6E71\", \"#EAC435\", \"#E63946\", \"#33658A\", \"#DFD6A7\", \"#627264\", \"#86CCA5\", \"#6268B0\", \"#E8D33F\", \"#DA2C38\"], credits: {enabled: false, position: {align: \"right\", verticalAlign: \"bottom\"}, text: \"(c) Insight Industry Inc., 2017.\"}, exporting: {enabled: false}, legend: {enabled: false}, plotOptions: {column: {groupPadding: 0, pointPadding: 0}, series: {dataLabels: {}, pointInterval: 30, pointStart: 0}}, series: [{data: [{name: \"12:00am - 4:59am\", x: 0, y: 2.737994945240101}, {name: \"5:00am - 5:29am\", x: 150, y: 1.6287559674248806}, {name: \"5:30am - 5:59am\", x: 165, y: 1.6849199663016006}, {name: \"6:00am - 6:29am\", x: 180, y: 5.9112608817747825}, {name: \"6:30am - 6:59am\", x: 195, y: 11.513619769727605}, {name: \"7:00am - 7:29am\", x: 210, y: 17.98652064026959}, {name: \"7:30am - 7:59am\", x: 225, y: 17.733782645324347}, {name: \"8:00am - 8:29am\", x: 240, y: 20.190957596180848}, {name: \"8:30am - 8:59am\", x: 255, y: 7.848918843021623}, {name: \"9:00am - 9:59am\", x: 270, y: 8.438640831227183}, {name: \"10:00am - 10:59am\", x: 300, y: 3.1592249368155008}, {name: \"11:00am - 11:59am\", x: 330, y: 1.1654029766919405}], name: null, pointPlacement: \"on\", type: \"column\"}], title: {text: null}, tooltip: {style: {fontSize: \"10px\"}, valueDecimals: 1, valueSuffix: \"%\"}, xAxis: {labels: {style: {fontSize: \"10px\"}}, max: 360, min: 0, tickInterval: 30, title: {text: null}}, yAxis: {labels: {style: {fontSize: \"10px\"}}, max: 25.0, min: 0, showLastLabel: false, tickInterval: 5, title: {style: {color: \"#0A3B61\", fontSize: \"9px\", fontWeight: \"bold\"}, text: \"Workers, Aged 25+\"}}}",
    "scale": 2,
    "type": "png"
}
</code>```

We have recreated what we (suspect) is the process that the node export server goes through, and have definitely recreated the (weird) behavior that we're seeing in this jsFiddle: https://jsfiddle.net/cmodzelewski/v4gm6t9a/2/

Are we missing something blatantly obvious (which is what we suspect)? Or is there a better way of doing this to get the behavior we're looking for?

Any help would be very much appreciated!

答:
In your fiddle with the suspected process, and in your callback, you are setting the axis labels in the following way:

```<code>options["yAxis"]["labels"]
</code>```

This will set an object labels on the yAxis element, however, since you can have several axis in highcharts, they are indexed, and stored as such. That means you have to edit the first axis like this:

```<code>options["yAxis"][0]["labels"]
</code>```

Here is a picture of the yAxis object in the incorrect configuration:

Here is a picture of the yAxis object in the correct configuration:

Working example using your second fiddle: https://jsfiddle.net/ewolden/v4gm6t9a/4/

Body:
We're currently generating a polar chart in HighCharts that renders correctly on the client-side (in the browser), and correctly applies formatters to the xAxis, yAxis, and plotOptions. Here is a jsFiddle that shows how it is rendering (correctly) in the browser: https://jsfiddle.net/cmodzelewski/38f03Lse/1/

On the server side, we are constructing a JSON payload and sending it to a node-export-server instance and returning a PNG. Based on our research, it is clear that formatters need to be included in the callback key of our JSON payload and passed to the server as a string, rather than in the infile key.

That's fine, and so we're converting our formatter functions into strings, composing them into the options object in our callback key, and then redrawing the chart at the end of our callback key.

This approach works great for non-polar charts, but if polar == true the export server returns a valid PNG from the export server, however that chart does not apply our formatter functions to the xAxis, yAxis, or plotOptions.series.

Here is the JSON payload that we are sending to a node-export-server instance:

{
    "callback": "function (chart) {var options = chart.options;var xAxisFormatter = function () { var extra_hrs = 0; if (this.value == 0) { extra_hrs = 12; }; return ((this.value / 0.5)/60) + extra_hrs + ':00'; };if (\"labels\" in options[\"xAxis\"]) { options[\"xAxis\"][\"labels\"][\"formatter\"] = xAxisFormatter; } else { options[\"xAxis\"][\"labels\"] = { \"formatter\": xAxisFormatter, \"style\": { \"fontSize\": \"8px\" } }; };var yAxisFormatter = function () { return Highcharts.numberFormat(this.value, 2, '.', ',') + \"%\"; };if (\"labels\" in options[\"yAxis\"]) { options[\"yAxis\"][\"labels\"][\"formatter\"] = yAxisFormatter; } else { options[\"yAxis\"][\"labels\"] = { \"formatter\": yAxisFormatter, \"style\": { \"fontSize\": \"8px\" } };};var plotOptionsFormatter = function () { return Highcharts.numberFormat(this.value, 2, '.', ',') + \"%\"; };options[\"plotOptions\"][\"series\"][\"dataLabels\"][\"formatter\"] = plotOptionsFormatter;chart = new Highcharts.chart(chart.container, options);chart.redraw();}",
    "infile": "{chart: {backgroundColor: \"white\", borderWidth: 0, height: 300, polar: true, width: 300}, colors: [\"#16C1F3\", \"#3C6E71\", \"#EAC435\", \"#E63946\", \"#33658A\", \"#DFD6A7\", \"#627264\", \"#86CCA5\", \"#6268B0\", \"#E8D33F\", \"#DA2C38\"], credits: {enabled: false, position: {align: \"right\", verticalAlign: \"bottom\"}, text: \"(c) Insight Industry Inc., 2017.\"}, exporting: {enabled: false}, legend: {enabled: false}, plotOptions: {column: {groupPadding: 0, pointPadding: 0}, series: {dataLabels: {}, pointInterval: 30, pointStart: 0}}, series: [{data: [{name: \"12:00am - 4:59am\", x: 0, y: 2.737994945240101}, {name: \"5:00am - 5:29am\", x: 150, y: 1.6287559674248806}, {name: \"5:30am - 5:59am\", x: 165, y: 1.6849199663016006}, {name: \"6:00am - 6:29am\", x: 180, y: 5.9112608817747825}, {name: \"6:30am - 6:59am\", x: 195, y: 11.513619769727605}, {name: \"7:00am - 7:29am\", x: 210, y: 17.98652064026959}, {name: \"7:30am - 7:59am\", x: 225, y: 17.733782645324347}, {name: \"8:00am - 8:29am\", x: 240, y: 20.190957596180848}, {name: \"8:30am - 8:59am\", x: 255, y: 7.848918843021623}, {name: \"9:00am - 9:59am\", x: 270, y: 8.438640831227183}, {name: \"10:00am - 10:59am\", x: 300, y: 3.1592249368155008}, {name: \"11:00am - 11:59am\", x: 330, y: 1.1654029766919405}], name: null, pointPlacement: \"on\", type: \"column\"}], title: {text: null}, tooltip: {style: {fontSize: \"10px\"}, valueDecimals: 1, valueSuffix: \"%\"}, xAxis: {labels: {style: {fontSize: \"10px\"}}, max: 360, min: 0, tickInterval: 30, title: {text: null}}, yAxis: {labels: {style: {fontSize: \"10px\"}}, max: 25.0, min: 0, showLastLabel: false, tickInterval: 5, title: {style: {color: \"#0A3B61\", fontSize: \"9px\", fontWeight: \"bold\"}, text: \"Workers, Aged 25+\"}}}",
    "scale": 2,
    "type": "png"
}

We have recreated what we (suspect) is the process that the node export server goes through, and have definitely recreated the (weird) behavior that we're seeing in this jsFiddle: https://jsfiddle.net/cmodzelewski/v4gm6t9a/2/

Are we missing something blatantly obvious (which is what we suspect)? Or is there a better way of doing this to get the behavior we're looking for?

Any help would be very much appreciated!

Body:
In your fiddle with the suspected process, and in your callback, you are setting the axis labels in the following way:

options["yAxis"]["labels"]

This will set an object labels on the yAxis element, however, since you can have several axis in highcharts, they are indexed, and stored as such. That means you have to edit the first axis like this:

options["yAxis"][0]["labels"]

Here is a picture of the yAxis object in the incorrect configuration:

Here is a picture of the yAxis object in the correct configuration:

Working example using your second fiddle: https://jsfiddle.net/ewolden/v4gm6t9a/4/


来源: stackexchange

问:
Create json array format in android
I want to create json request string. How can I do that? This is my following array:

```<code>[1,2,3,4,5];
</code>```

Now I want to create this type of json request:

```<code>{
    "contact_approve":[
    {
    "contact_id":1
    },
    {
    "contact_id":2
    },
    {
    "contact_id":3
    },
    {
    "contact_id":4
    },
    {
    "contact_id":5
    },
    ]

}
</code>```

Does anyone has the idea about how to create this type of json string?

答:
JSONObject which start with {}
JSONArray  which start with []
In your case you have a JSONObject which has an JSONArray.

let me give you an example.

```<code>  public void createJson() throws JSONException {
    // Create main JSON object
    JSONObject jsonObject = new JSONObject();

    //Create an JSON ARRAY which will have a key "contact_approve" later on
    JSONArray jsonArray = new JSONArray();

    Integer contacts[] = {1,2,3,4,5};
    for (int i = 0; i < contacts.length ; i++) {
        JSONObject contactID = new JSONObject();
        jsonArray.put(contactID.put("contact_id", i));
    }

    jsonObject.put("contact_approve", jsonArray);

    String json = jsonObject.toString();
    Log.d("JSON", json);
}
</code>```

Incase if you  need to Parse the JSON response, have a look at Moshi and GSON libraries which make your day better. These libraries can Parse JAVA classes in to JSON.
I use [https://codebeautify.org/jsonviewer] to view or minify the json.

Good luck.

ContentLicense: CC BY-SA 3.0

Title: Create json array format in android

Body:
I want to create json request string. How can I do that? This is my following array:

[1,2,3,4,5];

Now I want to create this type of json request:

{
    "contact_approve":[
    {
    "contact_id":1
    },
    {
    "contact_id":2
    },
    {
    "contact_id":3
    },
    {
    "contact_id":4
    },
    {
    "contact_id":5
    },
    ]

}

Does anyone has the idea about how to create this type of json string?

Body:
JSONObject which start with {}
JSONArray  which start with []
In your case you have a JSONObject which has an JSONArray.

let me give you an example.

  public void createJson() throws JSONException {
    // Create main JSON object
    JSONObject jsonObject = new JSONObject();

    //Create an JSON ARRAY which will have a key "contact_approve" later on
    JSONArray jsonArray = new JSONArray();

    Integer contacts[] = {1,2,3,4,5};
    for (int i = 0; i < contacts.length ; i++) {
        JSONObject contactID = new JSONObject();
        jsonArray.put(contactID.put("contact_id", i));
    }

    jsonObject.put("contact_approve", jsonArray);

    String json = jsonObject.toString();
    Log.d("JSON", json);
}

Incase if you  need to Parse the JSON response, have a look at Moshi and GSON libraries which make your day better. These libraries can Parse JAVA classes in to JSON.
I use [https://codebeautify.org/jsonviewer] to view or minify the json.

Good luck.


问:
how to check if a value exists in a dataframe
hi I am trying to get the column name of a dataframe which contains a specific word,

eg:
i have a dataframe,

```<code>NA              good    employee
Not available   best    employer
not required    well    manager
not eligible    super   reportee

my_word=["well"]
</code>```

how to check if "well" exists in a df and the column name which has "well"

thanks in Advance!

答:
Use DataFrame.isin for check all columns and DataFrame.any for check at least one True per row:

```<code>m = df.isin(my_word).any()
print (m)
0    False
1     True
2    False
dtype: bool
</code>```

And then get columns names by filtering:

```<code>cols = m.index[m].tolist()
print(cols)
[1]
</code>```

Data:

```<code>print (df)
               0      1         2
0            NaN   good  employee
1  Not available   best  employer
2   not required   well   manager
3   not eligible  super  reportee
</code>```

Detail:

```<code>print (df.isin(my_word))
       0      1      2
0  False  False  False
1  False  False  False
2  False   True  False
3  False  False  False

print (df.isin(my_word).any())
0    False
1     True
2    False
dtype: bool
</code>```

EDIT After converting  get nested lists, so flattening is necessary:

```<code>my_word=["well","manager"]

m = df.isin(my_word).any()
print (m)
0    False
1     True
2     True
dtype: bool

nested = df.loc[:,m].values.tolist()
flat_list = [item for sublist in nested for item in sublist]
print (flat_list)
['good', 'employee', 'best', 'employer', 'well', 'manager', 'super', 'reportee']
</code>```

Body:
hi I am trying to get the column name of a dataframe which contains a specific word,

eg:
i have a dataframe,

NA              good    employee
Not available   best    employer
not required    well    manager
not eligible    super   reportee

my_word=["well"]

how to check if "well" exists in a df and the column name which has "well"

thanks in Advance!

Body:
Use DataFrame.isin for check all columns and DataFrame.any for check at least one True per row:

m = df.isin(my_word).any()
print (m)
0    False
1     True
2    False
dtype: bool

And then get columns names by filtering:

cols = m.index[m].tolist()
print(cols)
[1]

Data:

print (df)
               0      1         2
0            NaN   good  employee
1  Not available   best  employer
2   not required   well   manager
3   not eligible  super  reportee

Detail:

print (df.isin(my_word))
       0      1      2
0  False  False  False
1  False  False  False
2  False   True  False
3  False  False  False

print (df.isin(my_word).any())
0    False
1     True
2    False
dtype: bool

EDIT After converting  get nested lists, so flattening is necessary:

my_word=["well","manager"]

m = df.isin(my_word).any()
print (m)
0    False
1     True
2     True
dtype: bool

nested = df.loc[:,m].values.tolist()
flat_list = [item for sublist in nested for item in sublist]
print (flat_list)
['good', 'employee', 'best', 'employer', 'well', 'manager', 'super', 'reportee']


问:
Custom design listview position error
custom design Listview Blog image

i want to create something like shown in the above image, where latest blog show up and other follow the alternate layout.

i have created the odd even follow loop, but its not working, when scrolling the listview it loads from first position,

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int layoutResource = 0; // determined by view type
    int viewType = getItemViewType(position);
    switch (viewType) {
        case 0:
            layoutResource = R.layout.news_row;
            break;

        case 0:
            layoutResource = R.layout.news_row_even;
            break;

        case 1:
            layoutResource = R.layout.news_row_odd;
    }
    if (convertView == null)
        convertView = inflater.inflate(layoutResource, null);

    TextView txtNewsTitle = (TextView) convertView.findViewById(R.id.news_title);
    txtNewsTitle.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));
    txtNewsTitle.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));

    TextView txtMessage = (TextView) convertView.findViewById(R.id.message);
    txtMessage.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtMessage.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    TextView txtAgo = (TextView) convertView.findViewById(R.id.ago);
    txtAgo.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtAgo.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    int MAX_WIDTH = Utils.getScreenWidth() / 2;
    int MAX_HEIGHT = MAX_WIDTH;

    final PNewsData news = (PNewsData) getItem(position);
    int n = 0;

    Log.e("position", String.valueOf(position));

    txtNewsTitle.setText(news.title);
    txtMessage.setText(news.description.substring(0, Math.min(news.description.length(), 120)) + "...");
    txtAgo.setText(news.added);

    if (news.images.get(0).path != null) {
        p.load(Config.APP_IMAGES_URL + news.images.get(0).path)
                .transform(new BitmapTransform(MAX_WIDTH, MAX_HEIGHT))
                .into(imgNewsPhoto);
    }

    return convertView;
}
</code>```

答:
Replace this:

```<code>if (convertView == null)
convertView = inflater.inflate(layoutResource, null);
</code>```

with:

```<code>if (convertView == null)
LayoutInflater inflater = getContext().getLayoutInflater();
convertView = inflater.inflate(layoutResource, null);
</code>```

Title: Custom design listview position error

Body:
custom design Listview Blog image

i want to create something like shown in the above image, where latest blog show up and other follow the alternate layout.

i have created the odd even follow loop, but its not working, when scrolling the listview it loads from first position,

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int layoutResource = 0; // determined by view type
    int viewType = getItemViewType(position);
    switch (viewType) {
        case 0:
            layoutResource = R.layout.news_row;
            break;

        case 0:
            layoutResource = R.layout.news_row_even;
            break;

        case 1:
            layoutResource = R.layout.news_row_odd;
    }
    if (convertView == null)
        convertView = inflater.inflate(layoutResource, null);

    TextView txtNewsTitle = (TextView) convertView.findViewById(R.id.news_title);
    txtNewsTitle.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));
    txtNewsTitle.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));

    TextView txtMessage = (TextView) convertView.findViewById(R.id.message);
    txtMessage.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtMessage.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    TextView txtAgo = (TextView) convertView.findViewById(R.id.ago);
    txtAgo.setTypeface(Utils.getTypeFace(Utils.Fonts.ROBOTO));
    txtAgo.startAnimation(AnimationUtils.loadAnimation(this.activity, R.anim.fade_in));

    int MAX_WIDTH = Utils.getScreenWidth() / 2;
    int MAX_HEIGHT = MAX_WIDTH;

    final PNewsData news = (PNewsData) getItem(position);
    int n = 0;

    Log.e("position", String.valueOf(position));

    txtNewsTitle.setText(news.title);
    txtMessage.setText(news.description.substring(0, Math.min(news.description.length(), 120)) + "...");
    txtAgo.setText(news.added);

    if (news.images.get(0).path != null) {
        p.load(Config.APP_IMAGES_URL + news.images.get(0).path)
                .transform(new BitmapTransform(MAX_WIDTH, MAX_HEIGHT))
                .into(imgNewsPhoto);
    }

    return convertView;
}

Body:
Replace this:

if (convertView == null)
convertView = inflater.inflate(layoutResource, null);

with:

if (convertView == null)
LayoutInflater inflater = getContext().getLayoutInflater();
convertView = inflater.inflate(layoutResource, null);


问:
SQL to SUM numbers WHEN ITEM number is the same
Trying to work on SUM SQL code to SUM SOH for all ITEM_PARENT numbers. SOH is the result I'm looking for and ITEM_PARENT and STOCK_ON_HAND is what I have.

```<code>CASE WHEN ITEM_PARENT = ITEM_PARENT THEN SUM(STOCK_ON_HAND) ELSE 'DN' END AS SOH_SUM,
</code>```

The code I have already done seems to be not working....

```<code>ITEM_PARENT STOCK_ON_HAND   SOH_SUM
123649336         1           11
123649336         1           11
123649336         1           11
123649336         5           11
123649336         2           11
123649336         1           11
123649328         1           15
123649328         1           15
123649328         2           15
123649328         1           15
123649328         2           15
123649328         1           15
123649328         1           15
123649328         3           15
123649328         3           15
124566152         3           19
124566152         1           19
124566152         3           19
124566152         3           19
124566152         2           19
124566152         7           19
</code>```

Anyone know what I'm missing there?

答:
It looks as though you trying to do some sort of conditional aggregation, but your expected output does not require this.  We can just do a select over the entire table and then use SUM as an analytic function to compute the SOH_SUM.

```<code>SELECT
    ITEM_PARENT, STOCK_ON_HAND,
    SUM(STOCK_ON_HAND) OVER (PARTITION BY ITEM_PARENT) SOH_SUM
FROM yourTable
ORDER BY ITEM_PARENT;
</code>```

Body:
Trying to work on SUM SQL code to SUM SOH for all ITEM_PARENT numbers. SOH is the result I'm looking for and ITEM_PARENT and STOCK_ON_HAND is what I have.

CASE WHEN ITEM_PARENT = ITEM_PARENT THEN SUM(STOCK_ON_HAND) ELSE 'DN' END AS SOH_SUM,

The code I have already done seems to be not working....

ITEM_PARENT STOCK_ON_HAND   SOH_SUM
123649336         1           11
123649336         1           11
123649336         1           11
123649336         5           11
123649336         2           11
123649336         1           11
123649328         1           15
123649328         1           15
123649328         2           15
123649328         1           15
123649328         2           15
123649328         1           15
123649328         1           15
123649328         3           15
123649328         3           15
124566152         3           19
124566152         1           19
124566152         3           19
124566152         3           19
124566152         2           19
124566152         7           19

Anyone know what I'm missing there?

Body:
It looks as though you trying to do some sort of conditional aggregation, but your expected output does not require this.  We can just do a select over the entire table and then use SUM as an analytic function to compute the SOH_SUM.

SELECT
    ITEM_PARENT, STOCK_ON_HAND,
    SUM(STOCK_ON_HAND) OVER (PARTITION BY ITEM_PARENT) SOH_SUM
FROM yourTable
ORDER BY ITEM_PARENT;


问:
Silverlight: Drag multiple rows from a datagrid
I am working on an app where the user needs to be able to drag items from a datagrid onto a button (this then fires some data updates). After some messing around, I have this working quite well. I have used the DataGridDragDropTarget controls from the toolkit for this.

I now need to allow the user drag multiple rows at once. While the datagrid allows me to select multiple rows, the DataGridDragDropTarget will only drag the first of the selections.

It looks like the DataGridDragDropTarget is not built for multiple dragging.

Would be grateful for any help on this one, this is the first time I have posted on SO - and hoping you guys can come through for me.

Thanks all.

答:
It will drag multiple rows for sure. I am sure you are doing same mistake as i did. I believe all your code are fine.

To drag multiple row click on one row press shift or ctrl to select multiple but "Note here: If you release your mouse click here before drag it will forget what are the multiple items it has selected", so just drag without leaving mouse on your last selected item.(So, I think it works that way without doing anything)

However I am also searching for someway to make it work like drag and drop as in desktop. ;-)

ContentLicense: CC BY-SA 2.5


问:
Balanced Data Distributor inserts data one at a time to destination but not parallelly
I have used SSIS Balance Data Distributor just to fill 50,000 Records from a OLEDB Source to OLEDB Destination,

When i don't Use SSIS BDD it takes 2 minutes 40 Secs when i use BDD it takes 1 minute 55 Secs which does not make that much difference.

I also find that the data does not load into destination Parallelly it is loading in first destination and later on it fills the next one. (One at a time) Can any of you please help how to fill them parallelly?

答:
Balanced Data Distribution is not a silver bullet for performance and runtime.  It is good when:

You have CPU-intensive transformations, and can benefit from parallel execution

Your destination supports concurrent insert

The first case is clear and it depends on your dataflow. As for the concurrent insert on OLE DB destination; the best results are on heap tables, or tables without a primary key/clustered index and other indexes as well. Or the clustered key has to defined on autoincremented surrogate key. On OLE DB Destination you might need to disable table lock; otherwise it could prevent insert from being parallel. But check for yourself, as written in Mark's answer - sometimes parallel insert works with table lock, but on a heap table or columnstore.

Other table types (with indexes, cluster or not) might escalate locks to table level or require index rebuilding, effectively disabling parallel insert. Delete or disable it.

So, you have to evaluate yourself weather the parallel execution justifies additional efforts in development and support.

ContentLicense: CC BY-SA 4.0


问:
Remove all
 If does not contain "test" in text
I am making a chrome extension for the first time and need a little help with my Javascript.

In my popup menu I want a few buttons. Once someone presses this button lets say button "test". I want it to remove every single
 whom does not contain the word "test".

I am making this because the filter functionality on this website I use a lot is very slow. This way I can filter faster myself by removing the rows instead of the program searching through all of them.

This is what I have so far:

var searchString = 'TEST';
$("#tbody tr td:contains('" + searchString + "')").each(function Tester() {
  if ($(this).text() != searchString) {
    $(this).parent().remove();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Remove all rows which don't contain:</p>
<button onclick="Tester()">TEST</button></code>```

答:
Try this

```<code>$("#tbody tr td").each( function () {
    if ( $(this).text().indexOf( searchString ) == -1 ) { //notice the use of indexOf
        $(this).parent().remove();//
    }
});
</code>```

Or you can check the row's text itself

```<code>$("#tbody tr").each( function () {
    if ( $(this).text().indexOf( searchString ) == -1 ) {
        $(this).remove();//
    }
});
</code>```

Title: Remove all <tr> If does not contain "test" in text

Body:
I am making a chrome extension for the first time and need a little help with my Javascript.

In my popup menu I want a few buttons. Once someone presses this button lets say button "test". I want it to remove every single
 whom does not contain the word "test".

I am making this because the filter functionality on this website I use a lot is very slow. This way I can filter faster myself by removing the rows instead of the program searching through all of them.

This is what I have so far:

var searchString = 'TEST';
$("#tbody tr td:contains('" + searchString + "')").each(function Tester() {
  if ($(this).text() != searchString) {
    $(this).parent().remove();
  }
});

Remove all rows which don't contain:

<button onclick="Tester()">TEST</button>

Body:
Try this

$("#tbody tr td").each( function () {
    if ( $(this).text().indexOf( searchString ) == -1 ) { //notice the use of indexOf
        $(this).parent().remove();//
    }
});

Or you can check the row's text itself

$("#tbody tr").each( function () {
    if ( $(this).text().indexOf( searchString ) == -1 ) {
        $(this).remove();//
    }
});


问:
magento 2 Check the status of indexing cron
I have magento2 website.I have crontab configured for running the daily crons.How i can verify the indexing cron is running daily.

Also how i can check the current running crons

Thanks in advance

答: You can watch result of cron work in db, table: cron_schedule.</p>


问:
Angular 4 - Adding router param before url
Just wondering whether there is a way to create a angular route with parameter before of in-between a url,

```<code>{path: ':param/test/list'} or {path: 'web/:param/list'}
</code>```

and reference it in routerLink directive,

```<code>[routerLink]="['test/list', paramValue]"
</code>```

Thee parameter value is always getting appended to the end of the url.

答:
I think this could help :) How to pass a parameter to routerLink that is somewhere inside the URL?

Always better to use router instead of [href]

Good luck

Body:
Just wondering whether there is a way to create a angular route with parameter before of in-between a url,

{path: ':param/test/list'} or {path: 'web/:param/list'}

and reference it in routerLink directive,

[routerLink]="['test/list', paramValue]"

Thee parameter value is always getting appended to the end of the url.


问:
How to compare stored date and time with SimpleDateFormat and display notification?
In my application I want to display the notification based on the time that user have already set and I am storing the Date and Time into local database.

I am getting the Date and Time from Local database and comparing with SimpleDateFormat and parsing with  Date like this

```<code>SimpleDateFormat yourDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = null;
     try {
          String date_time = "17-11-2017 15:10";
          date = yourDateFormat.parse(date_time);

     } catch (ParseException e) {
          Log.e(TAG, "Parsing date time failed", e);
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);

     Calendar current = Calendar.getInstance();
     if (calendar.compareTo(current) <= 0) {

        Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
     } else {
          AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
          PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
          alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent);

    }
</code>```

Some devices it is working fine like above 7.0 android version but below 7.0 versions it is showing java.lang.NullPointerException like this

```<code> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Date java.text.SimpleDateFormat.parse(java.lang.String)' on a null object reference
</code>```

and the error is showing here date = yourDateFormat.parse(date_time);.

Please help me out.

Thanks in Advance.

答:
That is lots of codes, you can simply set alarm with just few lines of codes. What you need to do is to get the date as a milliseconds DatePicker or other API, and configure your AlarmManager to fire when that time expires. Like this:

```<code>AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
          PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
          alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() +
        60000, alarmIntent);
</code>```

The above code will fire the BroadcastReceiver every 1 minute(60000milliseconds). Just replace the time with the user set date.

Body:
In my application I want to display the notification based on the time that user have already set and I am storing the Date and Time into local database.

I am getting the Date and Time from Local database and comparing with SimpleDateFormat and parsing with  Date like this

SimpleDateFormat yourDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = null;
     try {
          String date_time = "17-11-2017 15:10";
          date = yourDateFormat.parse(date_time);

     } catch (ParseException e) {
          Log.e(TAG, "Parsing date time failed", e);
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);

     Calendar current = Calendar.getInstance();
     if (calendar.compareTo(current) <= 0) {

        Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
     } else {
          AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
          PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
          alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent);

    }

Some devices it is working fine like above 7.0 android version but below 7.0 versions it is showing java.lang.NullPointerException like this

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Date java.text.SimpleDateFormat.parse(java.lang.String)' on a null object reference

and the error is showing here date = yourDateFormat.parse(date_time);.

Please help me out.

Thanks in Advance.

Body:
That is lots of codes, you can simply set alarm with just few lines of codes. What you need to do is to get the date as a milliseconds DatePicker or other API, and configure your AlarmManager to fire when that time expires. Like this:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
          PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
          alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() +
        60000, alarmIntent);

The above code will fire the BroadcastReceiver every 1 minute(60000milliseconds). Just replace the time with the user set date.


问:
Display all service names matching a string pattern
I'm trying to display the name (just the name) of all of the installed services that contain the string "SQL". For example, I want to see

SQLAgent$SQL2008_R2

SQLBrowser

SQLWriter

So I try this:

```<code>Get-WmiObject Win32_Service
</code>```

This displays all of the services, but as a list.

```<code>Exit Code : 0
Name      : ProtectedStorage
ProcessId : 664
StartMode : Manual
State     : Running
Status    : OK

Exit Code : 1077
Name      : QWAVE
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK
(etc...)
</code>```

This is good, but I just want to see the name. So I type:

```<code>Get-WmiObject Win32_Service | select-object Name
</code>```

And I get what I expect:

```<code>sppuinotfy
SQLAgent$SQL2008_RT
SQLBrowser
SQLWriter
SSDPSRV
(etc ..)
</code>```

All is good. I take the next step of filtering the names to only include SQL related ones:

```<code>Get-WmiObject Win32_Service | select-object Name | select-string -pattern 'SQL'
</code>```

And now it's confusing. Here is my output:

```<code>@{Name=BcmSqlStartupSvc}
@{Name=MSOLAP$SQL2008_R2}
@{Name=MSSQL$SQL2008_R2}
(etc ...)
</code>```

Why am I getting this output, instead of just the names?
What should I be typing to get just the names?

答:
You can use Get-Service instead of get-WMIObject and do it like this"</p>

```<code>get-service sql* | select -expand name
</code>```

Body:
I'm trying to display the name (just the name) of all of the installed services that contain the string "SQL". For example, I want to see

SQLAgent$SQL2008_R2

SQLBrowser

SQLWriter

So I try this:

Get-WmiObject Win32_Service

This displays all of the services, but as a list.

Exit Code : 0
Name      : ProtectedStorage
ProcessId : 664
StartMode : Manual
State     : Running
Status    : OK

Exit Code : 1077
Name      : QWAVE
ProcessId : 0
StartMode : Manual
State     : Stopped
Status    : OK
(etc...)

This is good, but I just want to see the name. So I type:

Get-WmiObject Win32_Service | select-object Name

And I get what I expect:

sppuinotfy
SQLAgent$SQL2008_RT
SQLBrowser
SQLWriter
SSDPSRV
(etc ..)

All is good. I take the next step of filtering the names to only include SQL related ones:

Get-WmiObject Win32_Service | select-object Name | select-string -pattern 'SQL'

And now it's confusing. Here is my output:

@{Name=BcmSqlStartupSvc}
@{Name=MSOLAP$SQL2008_R2}
@{Name=MSSQL$SQL2008_R2}
(etc ...)

Why am I getting this output, instead of just the names?
What should I be typing to get just the names?

Body:
You can use Get-Service instead of get-WMIObject and do it like this"

get-service sql* | select -expand name


问:
Changing position of an image depending on screen size
I'm involved in a project of setting up a responsive website and have encountered a problem with which I can't find the answer here or anywhere else:

When viewing a specific box with text and an image I want the image to be positioned differently when using desktop/tablet and smaller screens (i.e. smartphones). On desktop/tablet I want the image to have a fixed size and float right beside the text but under the headline, on smaller screens I want the image to be on top above the headline and the text and fill up the box with 100% size.

In fact, it might be easier to show it with some pictures:

How it looks like on desktop/tablet

How I want it to look like on smaller screens

The (undesired) result on smaller screens with the code I've done

As you can see I have not figured out how to do this, with the result the headline and text gets covered by the image, and it does not respect the boundaries of the box. This is the code I've tried:

The CSS for desktop/tablet:

```<code>div {position: relative;}

div img {
width: 200px;
float: right;
margin-left: 40px;
margin-bottom: 20px;}
</code>```

The CSS for smaller screens:

```<code>div {position: relative;}

div img {
position: absolute;
top: 20px;
width: 100%;
margin-bottom: 20px;}
</code>```

And the HTML for the div:

```<code><div>
<h2>Sed ut perspiciatis unde omnis iste</h2>
<img src="img/blossom.jpg">
Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.
</div>
</code>```

Some notes: colors, fonts etc. are declared in a global CSS but are not important to this problem. The desktop/tablet version is working fine, its when the screen gets smaller and the smartphone version loads the image doesn't work as it should. Without the image, the small version works fine.

But the big question here is: how do I move the image with CSS to come above all text, including the headline, when the small screen version loads. The image must respect the width of the box and the text to go under.

Believe me, I've tried out a lot of different approaches with no luck so far, and I'm stuck! Perhaps the solution is very obvious and simple but I can't figure it out. Sure hope someone knows what to do...?

答:
If you would give the width of the pixels it would do the trick. If you want to use it to make it responsive you need to use media queries, like here.

```<code>@media (min-height: 680px), screen and (orientation: portrait) {
div {position: relative;}

div img {
position: absolute;
top: 20px;
width: 200px;
margin-bottom: 20px;}
}
</code>```

Cause now you use use the complete width of the image, not the screen.

Body:
I'm involved in a project of setting up a responsive website and have encountered a problem with which I can't find the answer here or anywhere else:

When viewing a specific box with text and an image I want the image to be positioned differently when using desktop/tablet and smaller screens (i.e. smartphones). On desktop/tablet I want the image to have a fixed size and float right beside the text but under the headline, on smaller screens I want the image to be on top above the headline and the text and fill up the box with 100% size.

In fact, it might be easier to show it with some pictures:

How it looks like on desktop/tablet

How I want it to look like on smaller screens

The (undesired) result on smaller screens with the code I've done

As you can see I have not figured out how to do this, with the result the headline and text gets covered by the image, and it does not respect the boundaries of the box. This is the code I've tried:

The CSS for desktop/tablet:

div {position: relative;}

div img {
width: 200px;
float: right;
margin-left: 40px;
margin-bottom: 20px;}

The CSS for smaller screens:

div {position: relative;}

div img {
position: absolute;
top: 20px;
width: 100%;
margin-bottom: 20px;}

And the HTML for the div:

Sed ut perspiciatis unde omnis iste

Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.

Some notes: colors, fonts etc. are declared in a global CSS but are not important to this problem. The desktop/tablet version is working fine, its when the screen gets smaller and the smartphone version loads the image doesn't work as it should. Without the image, the small version works fine.

But the big question here is: how do I move the image with CSS to come above all text, including the headline, when the small screen version loads. The image must respect the width of the box and the text to go under.

Believe me, I've tried out a lot of different approaches with no luck so far, and I'm stuck! Perhaps the solution is very obvious and simple but I can't figure it out. Sure hope someone knows what to do...?

Body:
If you would give the width of the pixels it would do the trick. If you want to use it to make it responsive you need to use media queries, like here.

@media (min-height: 680px), screen and (orientation: portrait) {
div {position: relative;}

div img {
position: absolute;
top: 20px;
width: 200px;
margin-bottom: 20px;}
}

Cause now you use use the complete width of the image, not the screen.


问:
Calculating array number inputs in swift?
So this is how far I've gone with the code. Everything works OK yet I have not a clue how to proceed further. What I need to do right now is to do the calculation process and have it printed in the text field. I had the idea of having the math part in view controller class and working with string numbers, but I wanted to see if you can work with numbers in arrays.

This is the class for the operation:

```<code>import Foundation
import UIKit

class Calculation {

    var operation: String = ""
    var numbers: [Int] = []

    func operationInput() {

        switch operation {    // I still haven't figured out how to write the math part of it with array numbers.
        case "+":
            break
        case "-":
            break
        case "*":
            break
        case "/":
            break
        default:
            break
        }
    }
}
</code>```

And this is my main view controller:

```<code>    import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var resultLabel: UILabel!
    var numbers: String = ""
    var calculation = Calculation()
    var finalNumber: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func acPressed(_ sender: UIButton) {
        resultLabel.text = "0"
        numbers = ""
    }

    @IBAction func numberPressed(_ sender: UIButton) {

        let number = sender.titleLabel?.text
        numbers.append(number!)
        print(numbers)
        resultLabel.text = numbers

    }

    @IBAction func operationPressed(_ sender: UIButton) {

        let operationInput = sender.title(for: .normal)!
        calculation.numbers.append(Int(numbers)!)
        print(operationInput)
        print(calculation.numbers[0])
        numbers = ""
        resultLabel.text = calculation.operation
    }

    @IBAction func equationOperator(_ sender: UIButton) {

        let equation = sender.title(for: .normal)!
        if equation == "=" {
            finalNumber = Int(numbers)!
            resultLabel.text = "\(finalNumber)"
        }
    }

}
</code>```

答: or you can just use 2 different variables to make things simpler and 3rd one to store result in</p>

Body:
So this is how far I've gone with the code. Everything works OK yet I have not a clue how to proceed further. What I need to do right now is to do the calculation process and have it printed in the text field. I had the idea of having the math part in view controller class and working with string numbers, but I wanted to see if you can work with numbers in arrays.

This is the class for the operation:

import Foundation
import UIKit

class Calculation {

    var operation: String = ""
    var numbers: [Int] = []

    func operationInput() {

        switch operation {    // I still haven't figured out how to write the math part of it with array numbers.
        case "+":
            break
        case "-":
            break
        case "*":
            break
        case "/":
            break
        default:
            break
        }
    }
}

And this is my main view controller:

    import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var resultLabel: UILabel!
    var numbers: String = ""
    var calculation = Calculation()
    var finalNumber: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func acPressed(_ sender: UIButton) {
        resultLabel.text = "0"
        numbers = ""
    }

    @IBAction func numberPressed(_ sender: UIButton) {

        let number = sender.titleLabel?.text
        numbers.append(number!)
        print(numbers)
        resultLabel.text = numbers

    }

    @IBAction func operationPressed(_ sender: UIButton) {

        let operationInput = sender.title(for: .normal)!
        calculation.numbers.append(Int(numbers)!)
        print(operationInput)
        print(calculation.numbers[0])
        numbers = ""
        resultLabel.text = calculation.operation
    }

    @IBAction func equationOperator(_ sender: UIButton) {

        let equation = sender.title(for: .normal)!
        if equation == "=" {
            finalNumber = Int(numbers)!
            resultLabel.text = "\(finalNumber)"
        }
    }

}


问:
remove array object from nested array if element is undefined using javascript
Raw array

```<code>myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]
</code>```

Expected array,

```<code> myArr = [
        {name:'abcd',values:[{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129}},
        {name:'abcd',values:[{quarter: "Q4-2016", koordinaten: 19}]}
        ]
</code>```

i want to remove undefined element with index  in result array,

答:
You can use, underscore for such kind of tasks.

Compact method

myArr = [{
  name: 'abcd',
  values: [undefined, {
    quarter: "Q2-2016",
    koordinaten: 119
  }, {
    quarter: "Q3-2016",
    koordinaten: 129
  }, undefined]
}, {
  name: 'abcd',
  values: [undefined, undefined, {
    quarter: "Q4-2016",
    koordinaten: 19
  }, undefined]
}]

// Cleansed Array
myArr = myArr.map(function(arrItem) {
  arrItem.values = _.compact(arrItem.values);
  return arrItem
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script></code>```

Body:
Raw array

myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]

Expected array,

 myArr = [
        {name:'abcd',values:[{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129}},
        {name:'abcd',values:[{quarter: "Q4-2016", koordinaten: 19}]}
        ]

i want to remove undefined element with index  in result array,

Body:
You can use, underscore for such kind of tasks.

Compact method

myArr = [{
  name: 'abcd',
  values: [undefined, {
    quarter: "Q2-2016",
    koordinaten: 119
  }, {
    quarter: "Q3-2016",
    koordinaten: 129
  }, undefined]
}, {
  name: 'abcd',
  values: [undefined, undefined, {
    quarter: "Q4-2016",
    koordinaten: 19
  }, undefined]
}]

// Cleansed Array
myArr = myArr.map(function(arrItem) {
  arrItem.values = _.compact(arrItem.values);
  return arrItem
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


问:
Using str_replace to alter a field's display in a Drupal 7 view
I am using the Google Analytics module to retrieve the most popular articles on my site during the past day to populate a 'trending' block.

The problem is that the PageTitle field comes from the meta data and includes a pipe and the site name. I would like to strip that off the end of the string, but I can't figure out how to do it within the view using rewrite results.

I created a views-view-field--pageTitle.tpl.php file and edited it to this:

```<code><?php
$output = str_replace(" | My Site", "", $output);
print $output;
?>
</code>```

this doesn't seem to work...

答:
I think you have to modify metadata in template.php, so you can do this with :

```<code>THEMENAME_html_head_alter(&$head_elements) {
  // dump content of $head_elements and find your value to modify
}
</code>```

documentation : https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_html_head_alter/7.x

Also you can use metadata module to handle meta :
https://www.drupal.org/project/metatag

Hope it helps ;)

Body:
I am using the Google Analytics module to retrieve the most popular articles on my site during the past day to populate a 'trending' block.

The problem is that the PageTitle field comes from the meta data and includes a pipe and the site name. I would like to strip that off the end of the string, but I can't figure out how to do it within the view using rewrite results.

I created a views-view-field--pageTitle.tpl.php file and edited it to this:

<?php
$output = str_replace(" | My Site", "", $output);
print $output;
?>

this doesn't seem to work...

Body:
I think you have to modify metadata in template.php, so you can do this with :

THEMENAME_html_head_alter(&$head_elements) {
  // dump content of $head_elements and find your value to modify
}

documentation : https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_html_head_alter/7.x

Also you can use metadata module to handle meta :
https://www.drupal.org/project/metatag

Hope it helps ;)


问:
C - division doesnt work
I'm actually totally stuck I don't understand the behavior of this function:

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

typedef struct s_resolution
{
   int x;
   int y;
   float fx;
   float fy;
} t_resolution;

typedef struct s_pixel_info
{
    int tablen;
    t_resolution resolution;
    char name;
    int line;
    int pos_suite[6];
    int suite[6];
} t_pixel_info;

void get_proportion_ratio(t_pixel_info DataB, t_pixel_info pix_info,
                           t_resolution *proportion)
{
    proportion->fx = (float)(DataB.resolution.x / pix_info.resolution.x);
    //I also tried without the cast
    proportion->y = (int)(DataB.resolution.y / pix_info.resolution.y * 100);
    //if (proportion->y != 100)
    printf("%d | %d | %d\n",proportion->y, DataB.resolution.y, pix_info.resolution.y);
}

int main()
{
  t_pixel_info DataB;
  t_pixel_info pix_info;
  t_resolution proportion;

  DataB.resolution.x = 5;
  pix_info.resolution.x = 10;
  DataB.resolution.y = 5;
  pix_info.resolution.y = 10;
  get_proportion_ratio(DataB, pix_info, &proportion);

}
</code>```

DataB.resolution.y, pix_info.resolution.y and proportion->y are all Int type.

My problem is that I have this result:

```<code>0 | 5 | 10
</code>```

The operation only works when the result is 100... I must be missing something obvious but I've no idea what.

答:
All of your divisions are being done on integers.  Take this expression:

```<code>5 / 10 * 100
</code>```

This groups as:

```<code>(5 / 10) * 100
</code>```

This evaluates to 0:  5 / 10 is 0, and 0 * 100 is still 0.  Casting the result after the fact doesn't change it.

If you multiply by 100 before you divide, you will obtain two more digits of precision:

```<code>100 * 5 / 10
</code>```

This evaluates to 50:  100 * 5 is 500, and 500 / 10 is 50.

You could also perform the arithmetic in floating point, e.g.

```<code>(double) 5 / (double) 10 * (double) 100
</code>```

Or you could just cast the first operand and let the standard arithmetic conversions handle the rest; the result is equivalent:

```<code>(double) 5 / 10 * 100
</code>```

In either case, the result will be 50.0

Title: C - division doesnt work

Body:
I'm actually totally stuck I don't understand the behavior of this function:

#include <stdio.h>

typedef struct s_resolution
{
   int x;
   int y;
   float fx;
   float fy;
} t_resolution;

typedef struct s_pixel_info
{
    int tablen;
    t_resolution resolution;
    char name;
    int line;
    int pos_suite[6];
    int suite[6];
} t_pixel_info;

void get_proportion_ratio(t_pixel_info DataB, t_pixel_info pix_info,
                           t_resolution *proportion)
{
    proportion->fx = (float)(DataB.resolution.x / pix_info.resolution.x);
    //I also tried without the cast
    proportion->y = (int)(DataB.resolution.y / pix_info.resolution.y * 100);
    //if (proportion->y != 100)
    printf("%d | %d | %d\n",proportion->y, DataB.resolution.y, pix_info.resolution.y);
}

int main()
{
  t_pixel_info DataB;
  t_pixel_info pix_info;
  t_resolution proportion;

  DataB.resolution.x = 5;
  pix_info.resolution.x = 10;
  DataB.resolution.y = 5;
  pix_info.resolution.y = 10;
  get_proportion_ratio(DataB, pix_info, &proportion);

}

DataB.resolution.y, pix_info.resolution.y and proportion->y are all Int type.

My problem is that I have this result:

0 | 5 | 10

The operation only works when the result is 100... I must be missing something obvious but I've no idea what.

Body:
All of your divisions are being done on integers.  Take this expression:

5 / 10 * 100

This groups as:

(5 / 10) * 100

This evaluates to 0:  5 / 10 is 0, and 0 * 100 is still 0.  Casting the result after the fact doesn't change it.

If you multiply by 100 before you divide, you will obtain two more digits of precision:

100 * 5 / 10

This evaluates to 50:  100 * 5 is 500, and 500 / 10 is 50.

You could also perform the arithmetic in floating point, e.g.

(double) 5 / (double) 10 * (double) 100

Or you could just cast the first operand and let the standard arithmetic conversions handle the rest; the result is equivalent:

(double) 5 / 10 * 100

In either case, the result will be 50.0


问:
awk print all parts before a match
I have some text where I want to grab all the text up to the year, inclusive. I've tried starting with something like this

```<code>awk '/[1-2][0-9][0-9][0-9]/{print $1}'
</code>```

but that only prints the first "word" of the input

```<code>"Financial summary 1997 FINAL.doc" => "Financial"
"v4 Minutes 19950705" => "v4"
</code>```

What I want is "Financial summary 1997" and "v4 Minutes 1995". I've played around with $NF and various others with no success as yet I don't know how many words there are, or how many numbers there are, so I can't jut print $1 $2 $3. I don't have to use awk, but it would be useful since I am actually going to print the results out with some surrounding tags for output to an HTML file.

I can set a field separator to be "4 digits" but that discards the year

```<code> awk -F[1-2][0-9][0-9][0-9] '{print $1}
</code>```

EDIT:
This is what I ended up with and then came back to see a solution posted:

```<code>awk 'match($0,/.*(19|20)[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'
</code>```

Thanks all

答:
You can use this grep command:

```<code>grep -oE '[^"]* [1-2][0-9]{3}' file

Financial summary 1997
v4 Minutes 1995
</code>```

For awk, you can use gensub:

```<code>awk '{ print substr(gensub(/^(.* [1-2][0-9]{3}).*/, "\\1", "1"), 2) }' file

Financial summary 1997
v4 Minutes 1995
</code>```

Title: awk print all parts before a match

Body:
I have some text where I want to grab all the text up to the year, inclusive. I've tried starting with something like this

awk '/[1-2][0-9][0-9][0-9]/{print $1}'

but that only prints the first "word" of the input

"Financial summary 1997 FINAL.doc" => "Financial"
"v4 Minutes 19950705" => "v4"

What I want is "Financial summary 1997" and "v4 Minutes 1995". I've played around with $NF and various others with no success as yet I don't know how many words there are, or how many numbers there are, so I can't jut print $1 $2 $3. I don't have to use awk, but it would be useful since I am actually going to print the results out with some surrounding tags for output to an HTML file.

I can set a field separator to be "4 digits" but that discards the year

 awk -F[1-2][0-9][0-9][0-9] '{print $1}

EDIT:
This is what I ended up with and then came back to see a solution posted:

awk 'match($0,/.*(19|20)[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'

Thanks all

Body:
You can use this grep command:

grep -oE '[^"]* [1-2][0-9]{3}' file

Financial summary 1997
v4 Minutes 1995

For awk, you can use gensub:

awk '{ print substr(gensub(/^(.* [1-2][0-9]{3}).*/, "\\1", "1"), 2) }' file

Financial summary 1997
v4 Minutes 1995


问:
Are there any integration frameworks like smooks for .NET?
I'm doing a lot of work coding merging and data transformation in C#, and I'm just wondering if there are any good "helpers" for doing that instead of handcoding it all.
(that is, without going for a full integration platform like Biztalk)
I'm talking merging and mapping textfiles to produce XML, quite big files but only some very month.

In java, there are a bunch of small ESB's and other things like Smooks that would help, but are there anything like that for C# or is it easier to just go for LINQ?

Regards

答:
In order to perform ETL-like operations in C# code there is always Rhino ETL.

Github repository: https://github.com/ayende/rhino-etl


问:
AWS auto-scaling group AMI
I have four EC2(API server) instances running on AWS with ELB and I would like to apply auto-scaling group. From my understanding, I first should create an AMI of one of four EC2 instances that I am running and it auto scales from the AMI that I have created based on configuration. At this point, should I re-create the AMI whenever pushing new codes so that it scales up from a latest version of it?</p>

答:
You don't need to recreate the AMI each time you do code changes. In fact you can use AWS CodeDeploy with Autoscaling groups to have your latest code deployed each time a new EC2 instance is created.

It's explained here: https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-auto-scaling-group.html

Title: AWS auto-scaling group AMI


问:
Adding to vocab during Tensorflow seq2seq run
I am using the Tensorflow seq2seq tutorial to play with machine translation. Say I have trained the model for some time and determine that I want to supplement the original vocab with new words to enhance the quality of the model. Is there a way to pause training, add words to the vocabulary, and then resume training from the most recent checkpoint? I attempted to do so but when I began training again I got this error:

```<code>Traceback (most recent call last):
File "execute.py", line 405, in <module>
train()
File "execute.py", line 127, in train
model = create_model(sess, False)
File "execute.py", line 108, in create_model
model.saver.restore(session, ckpt.model_checkpoint_path)
File "/home/jrthom18/.local/lib/python2.7/site-    packages/tensorflow/python/training/saver.py", line 1388, in restore
{self.saver_def.filename_tensor_name: save_path})
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 766, in run
run_metadata_ptr)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 964, in _run
feed_dict_string, options, run_metadata)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1014, in _do_run
target_list, options, run_metadata)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1034, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Assign   requires shapes of both tensors to match. lhs shape= [384633] rhs shape=   [384617]
 [[Node: save/Assign_82 = Assign[T=DT_FLOAT, _class=["loc:@proj_b"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/cpu:0"](proj_b, save/RestoreV2_82)]]

Caused by op u'save/Assign_82', defined at:
File "execute.py", line 405, in <module>
train()
File "execute.py", line 127, in train
model = create_model(sess, False)
File "execute.py", line 99, in create_model
model = seq2seq_model.Seq2SeqModel( gConfig['enc_vocab_size'],  gConfig['dec_vocab_size'], _buckets, gConfig['layer_size'], gConfig['num_layers'], gConfig['max_gradient_norm'], gConfig['batch_size'], gConfig['learning_rate'], gConfig['learning_rate_decay_factor'], forward_only=forward_only)
File "/home/jrthom18/data/3x256_bs32/easy_seq2seq/seq2seq_model.py", line 166, in __init__
self.saver = tf.train.Saver(tf.global_variables(), keep_checkpoint_every_n_hours=2.0)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1000, in __init__
self.build()
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1030, in build
restore_sequentially=self._restore_sequentially)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 624, in build
restore_sequentially, reshape)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 373, in _AddRestoreOps
assign_ops.append(saveable.restore(tensors, shapes))
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 130, in restore
self.op.get_shape().is_fully_defined())
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/ops/gen_state_ops.py", line 47, in assign
use_locking=use_locking, name=name)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
op_def=op_def)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2240, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1128, in __init__
self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Assign requires shapes of both tensors to match. lhs shape= [384633] rhs shape= [384617]
 [[Node: save/Assign_82 = Assign[T=DT_FLOAT, _class=["loc:@proj_b"],   use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/cpu:0"](proj_b, save/RestoreV2_82)]]
</code>```

Obviously the new vocab is larger and so the tensor sizes do not match. Is there some way around this?

答: You can not update your vocab once its set but you can always use shared wordpiece model. It will help you to directly copy out of vocab words form source to target output.</p>

Body:
I am using the Tensorflow seq2seq tutorial to play with machine translation. Say I have trained the model for some time and determine that I want to supplement the original vocab with new words to enhance the quality of the model. Is there a way to pause training, add words to the vocabulary, and then resume training from the most recent checkpoint? I attempted to do so but when I began training again I got this error:

Traceback (most recent call last):
File "execute.py", line 405, in <module>
train()
File "execute.py", line 127, in train
model = create_model(sess, False)
File "execute.py", line 108, in create_model
model.saver.restore(session, ckpt.model_checkpoint_path)
File "/home/jrthom18/.local/lib/python2.7/site-    packages/tensorflow/python/training/saver.py", line 1388, in restore
{self.saver_def.filename_tensor_name: save_path})
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 766, in run
run_metadata_ptr)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 964, in _run
feed_dict_string, options, run_metadata)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1014, in _do_run
target_list, options, run_metadata)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1034, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Assign   requires shapes of both tensors to match. lhs shape= [384633] rhs shape=   [384617]
 [[Node: save/Assign_82 = Assign[T=DT_FLOAT, _class=["loc:@proj_b"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/cpu:0"](proj_b, save/RestoreV2_82)]]

Caused by op u'save/Assign_82', defined at:
File "execute.py", line 405, in <module>
train()
File "execute.py", line 127, in train
model = create_model(sess, False)
File "execute.py", line 99, in create_model
model = seq2seq_model.Seq2SeqModel( gConfig['enc_vocab_size'],  gConfig['dec_vocab_size'], _buckets, gConfig['layer_size'], gConfig['num_layers'], gConfig['max_gradient_norm'], gConfig['batch_size'], gConfig['learning_rate'], gConfig['learning_rate_decay_factor'], forward_only=forward_only)
File "/home/jrthom18/data/3x256_bs32/easy_seq2seq/seq2seq_model.py", line 166, in __init__
self.saver = tf.train.Saver(tf.global_variables(), keep_checkpoint_every_n_hours=2.0)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1000, in __init__
self.build()
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1030, in build
restore_sequentially=self._restore_sequentially)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 624, in build
restore_sequentially, reshape)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 373, in _AddRestoreOps
assign_ops.append(saveable.restore(tensors, shapes))
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 130, in restore
self.op.get_shape().is_fully_defined())
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/ops/gen_state_ops.py", line 47, in assign
use_locking=use_locking, name=name)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
op_def=op_def)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2240, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/jrthom18/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1128, in __init__
self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Assign requires shapes of both tensors to match. lhs shape= [384633] rhs shape= [384617]
 [[Node: save/Assign_82 = Assign[T=DT_FLOAT, _class=["loc:@proj_b"],   use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/cpu:0"](proj_b, save/RestoreV2_82)]]

Obviously the new vocab is larger and so the tensor sizes do not match. Is there some way around this?


问:
Get Twig to only show authorised parts of a page or menu
I am planning on converting a website to using MVC and php.
I am planning on using the Twig template engine so that I can remove all code from the page templates, but I have hit on a problem, and that is with my menu. I only want a certain level of user to access each menu item.

I have a function which I call which returns true if a level is allowed.
So for instance if you have a level of purchase you will be allowed to see Menu Item 1, but not allowed to see Menu Item 2. For instance Sales would not be able to see the first two menu items.

I know that you cannot call functions or classes in Twig.

eg (my function is in a class called logon, but that shouldn't matter)

```<code><?php if ($logon->user_access('purchase','accountant','poweruser')):?>
    Menu Item 1
<?php endif;?>

 <?php if ($logon->user_access('accountant','poweruser')):?>
    Menu Item 2
 <?php endif;?>

  <?php if ($logon->user_access('sales')):?>
    Menu Item 2
 <?php endif;?>
</code>```

The question is how do I make a template in twig with this functionality without using php?
I am totally new to using a template engine.

edit...
@Yoshi

Ok I include twig in my index.php with

```<code>require_once dirname(__DIR__).'/vendor/Twig/vendor/autoload.php';
</code>```

Then whenever I want to render the page I call a function from my core/view

```<code>public static function renderTwig($template,$args =[])
{
    static $twig = null;

    if($twig === null){
        $loader = new \Twig_Loader_Filesystem('../App/Views');
        $twig = new \Twig_Environment($loader);
        echo $twig->render($template, $args);
    }
}
</code>```

Then in my controller I call

```<code>View::renderTwig('Home/index.html',[
            'css'=> $css,
            'name' => 'Dave',
            'colours' => ['red','green','blue']
        ]);
</code>```

I set this all up from a tutorial I have been following called "Create php mvc project from scratch".

PS. I suppose in my renderTwig function I could send in variables which are used on every page and add it to the arg array for the page. That way I wouldn't need to add authentication to every page.

Edit:
I am making a small amendment here. Even though Yoshi's answer is correct. I had a small problem which I have now solved, and I thought I would share this.
In the twig template I am using it like this

```<code>{% if user_access('sales','purchase') %}Do something{% endif %}
</code>```

The problem is that I don't know the number of items that are coming in so I need to use args, and this caused me a small problem, as the following line sent the string to my function, but only one item.

```<code>return $this->logon->user_access($roles);
</code>```

The problem with func_get_args is that you cannot pass it to another function. It can only be read in the function that you send it to. So my small amendment was this.

```<code>return $this->logon->user_access($args = func_get_args());
</code>```

Now the problem here is that it sends an array instead, but my php routines were set up to use args, and I wanted to use the same function in php that I used in twig. So what I did was to check if an array came in, I just looped through the array, but if a non array came in I checked the args. eg

```<code>public function user_access($levels)
{
    $bool=false;
    if(is_array($levels)):
        foreach($levels as $item):
            if($this->userlevel($item)==true $bool=true;
        endforeach;
    else:
        foreach(func_get_args() as $arg):
            if($this->userlevel($arg)==true $bool=true;
        endforeach;
    endif;
    return $bool;
}
</code>```

So thankyou Yoshi

答:
Here are some ways to add the function (or the object) to your views.

Disclaimer: I think it's really bad practice to setup the twig
  environment inside a static method of View. I'm just going along
  with it, so to not over complicate things here. But if you're interested
  in how to do it better. Read up on dependency
  injection.

```<code><?php

require_once dirname(__DIR__).'/vendor/Twig/vendor/autoload.php';

// only as an example example
class AccessChecker
{
    public function user_access(...$levels)
    {
        return true;
    }
}

class YourTwigExtension extends \Twig_Extension
{
    /**
     * @var AccessChecker
     */
    private $logon;

    /**
     * @param AccessChecker $logon
     */
    public function __construct(AccessChecker $logon)
    {
        $this->logon = $logon;
    }

    /**
     * @inheritdoc
     */
    public function getFunctions()
    {
        return [
            new Twig_Function('user_access', [$this, 'checkUserAccess']),
        ];
    }

    /**
     * @param array ...$roles
     *
     * @return mixed
     */
    public function checkUserAccess(...$roles)
    {
        return $this->logon->user_access(...$roles);
    }
}

class View
{
    public static function renderTwig($template, $args =[])
    {
        static $twig = null;

        if($twig === null) {
            $loader = new \Twig_Loader_Filesystem('../App/Views');
            $twig = new \Twig_Environment($loader);

            // the extras:
            $logon = new AccessChecker();

            // with globals:
            $twig->addGlobal('logon', $logon);

            /*
             * {% if logon.user_access('purchase','accountant','poweruser') %}
             *   ...
             * {% endif %}
             */

            // with functions:
            $twig->addFunction(new Twig_Function('user_access', [$logon, 'user_access']));

            /*
             * {% if user_access('purchase','accountant','poweruser') %}
             *   ...
             * {% endif %}
             */

            // with an extension
            $twig->addExtension(new YourTwigExtension($logon));

            /*
             * {% if checkUserAccess('purchase','accountant','poweruser') %}
             *   ...
             * {% endif %}
             */
        }

        echo $twig->render($template, $args);
    }
}
</code>```

Note: You obviously only need to choose one method of adding the functionality. I'd suggest to go for the extension. This way, later additions can happen in the same place, without a need to change the wiring up code.

Body:
I am planning on converting a website to using MVC and php.
I am planning on using the Twig template engine so that I can remove all code from the page templates, but I have hit on a problem, and that is with my menu. I only want a certain level of user to access each menu item.

I have a function which I call which returns true if a level is allowed.
So for instance if you have a level of purchase you will be allowed to see Menu Item 1, but not allowed to see Menu Item 2. For instance Sales would not be able to see the first two menu items.

I know that you cannot call functions or classes in Twig.

eg (my function is in a class called logon, but that shouldn't matter)

<?php if ($logon->user_access('purchase','accountant','poweruser')):?>
    Menu Item 1
<?php endif;?>

 <?php if ($logon->user_access('accountant','poweruser')):?>
    Menu Item 2
 <?php endif;?>

  <?php if ($logon->user_access('sales')):?>
    Menu Item 2
 <?php endif;?>

The question is how do I make a template in twig with this functionality without using php?
I am totally new to using a template engine.

edit...
@Yoshi

Ok I include twig in my index.php with

require_once dirname(__DIR__).'/vendor/Twig/vendor/autoload.php';

Then whenever I want to render the page I call a function from my core/view

public static function renderTwig($template,$args =[])
{
    static $twig = null;

    if($twig === null){
        $loader = new \Twig_Loader_Filesystem('../App/Views');
        $twig = new \Twig_Environment($loader);
        echo $twig->render($template, $args);
    }
}

Then in my controller I call

View::renderTwig('Home/index.html',[
            'css'=> $css,
            'name' => 'Dave',
            'colours' => ['red','green','blue']
        ]);

I set this all up from a tutorial I have been following called "Create php mvc project from scratch".

PS. I suppose in my renderTwig function I could send in variables which are used on every page and add it to the arg array for the page. That way I wouldn't need to add authentication to every page.

Edit:
I am making a small amendment here. Even though Yoshi's answer is correct. I had a small problem which I have now solved, and I thought I would share this.
In the twig template I am using it like this

{% if user_access('sales','purchase') %}Do something{% endif %}

The problem is that I don't know the number of items that are coming in so I need to use args, and this caused me a small problem, as the following line sent the string to my function, but only one item.

return $this->logon->user_access($roles);

The problem with func_get_args is that you cannot pass it to another function. It can only be read in the function that you send it to. So my small amendment was this.

return $this->logon->user_access($args = func_get_args());

Now the problem here is that it sends an array instead, but my php routines were set up to use args, and I wanted to use the same function in php that I used in twig. So what I did was to check if an array came in, I just looped through the array, but if a non array came in I checked the args. eg

public function user_access($levels)
{
    $bool=false;
    if(is_array($levels)):
        foreach($levels as $item):
            if($this->userlevel($item)==true $bool=true;
        endforeach;
    else:
        foreach(func_get_args() as $arg):
            if($this->userlevel($arg)==true $bool=true;
        endforeach;
    endif;
    return $bool;
}

So thankyou Yoshi

Body:
Here are some ways to add the function (or the object) to your views.

Disclaimer: I think it's really bad practice to setup the twig
  environment inside a static method of View. I'm just going along
  with it, so to not over complicate things here. But if you're interested
  in how to do it better. Read up on dependency
  injection.

<?php

require_once dirname(__DIR__).'/vendor/Twig/vendor/autoload.php';

// only as an example example
class AccessChecker
{
    public function user_access(...$levels)
    {
        return true;
    }
}

class YourTwigExtension extends \Twig_Extension
{
    /**
     * @var AccessChecker
     */
    private $logon;

    /**
     * @param AccessChecker $logon
     */
    public function __construct(AccessChecker $logon)
    {
        $this->logon = $logon;
    }

    /**
     * @inheritdoc
     */
    public function getFunctions()
    {
        return [
            new Twig_Function('user_access', [$this, 'checkUserAccess']),
        ];
    }

    /**
     * @param array ...$roles
     *
     * @return mixed
     */
    public function checkUserAccess(...$roles)
    {
        return $this->logon->user_access(...$roles);
    }
}

class View
{
    public static function renderTwig($template, $args =[])
    {
        static $twig = null;

        if($twig === null) {
            $loader = new \Twig_Loader_Filesystem('../App/Views');
            $twig = new \Twig_Environment($loader);

            // the extras:
            $logon = new AccessChecker();

            // with globals:
            $twig->addGlobal('logon', $logon);

            /*
             * {% if logon.user_access('purchase','accountant','poweruser') %}
             *   ...
             * {% endif %}
             */

            // with functions:
            $twig->addFunction(new Twig_Function('user_access', [$logon, 'user_access']));

            /*
             * {% if user_access('purchase','accountant','poweruser') %}
             *   ...
             * {% endif %}
             */

            // with an extension
            $twig->addExtension(new YourTwigExtension($logon));

            /*
             * {% if checkUserAccess('purchase','accountant','poweruser') %}
             *   ...
             * {% endif %}
             */
        }

        echo $twig->render($template, $args);
    }
}

Note: You obviously only need to choose one method of adding the functionality. I'd suggest to go for the extension. This way, later additions can happen in the same place, without a need to change the wiring up code.


问:
Unable to determine Hadoop version information
I have installed hadoop in ubuntu and its running fine.

```<code>ubuntu:/home/hduser/hive-0.10.0-cdh4.3.1$ jps
2702 DataNode
3101 ResourceManager
4879 Jps
2948 SecondaryNameNode
3306 NodeManager
</code>```

hadoop_version=Hadoop 2.0.0-cdh4.3.0

Then i installed hive(hiv version-hive-0.10.0) from apache tarballs and I tried running bin/hive. But I am getting below error:

Unable to determine Hadoop version information.
hadoop version returned:

```<code>/home/hduser/hadoop/etc/hadoop /usr/lib/jvm/jdk1.6.0_45/
Hadoop 2.0.0-cdh4.3.0
Subversion file:///var/lib/jenkins/workspace/CDH4.3.0-Packaging-Hadoop/build/cdh4/hadoop/2.0.0-cdh4.3.0/source/hadoop-common-project/hadoop-common -r 48a9315b342ca16de92fcc5be95ae3650629155a
Compiled by jenkins on Mon May 27 19:06:57 PDT 2013
From source with checksum a4218d77f9b12df4e3e49ef96f9d357d
This command was run using /home/hduser/hadoop/share/hadoop/common/hadoop-common-2.0.0-cdh4.3.0.jar
</code>```

I tried it to resolve through my scripting knowledge but can't. When I stretched my effort I found that it is failing in below line:

```<code>if [[ "$HADOOP_VERSION" =~ $hadoop_version_re ]]; then
</code>```

and I tried to echo HADOOP_VERSION it returned nothing and HADOOP_VERSION is defined as

```<code>HADOOP_VERSION=$($HADOOP version | awk '{if (NR == 1) {print $2;}}');
</code>```

and $HADOOP version yields me

```<code> /home/hduser/hadoop/etc/hadoop
 /usr/lib/jvm/jdk1.6.0_45/
 Hadoop 2.0.0-cdh4.3.0
 Subversion file:///var/lib/jenkins/workspace/CDH4.3.0-Packaging-Hadoop/build/cdh4/hadoop/2.0.0-cdh4.3.0/source/hadoop-common-project/hadoop-common -r 48a9315b342ca16de92fcc5be95ae3650629155a
 Compiled by jenkins on Mon May 27 19:06:57 PDT 2013
 From source with checksum a4218d77f9b12df4e3e49ef96f9d357d
 This command was run using /home/hduser/hadoop/share/hadoop/common/hadoop-common-2.0.0-cdh4.3.0.jar
</code>```

I am struck this for a week now. Please help me out. Thanks.

答: If u have set export HADOOP_VERSION=2.0.0-cdh4.3.0 or your version num in the .bashrc file, comment it or put an # in front like #export HADOOP_VERSION=2.0.0-cdh4.3.0 and then run hive, you will be able to solve the issue.

Body:
I have installed hadoop in ubuntu and its running fine.

ubuntu:/home/hduser/hive-0.10.0-cdh4.3.1$ jps
2702 DataNode
3101 ResourceManager
4879 Jps
2948 SecondaryNameNode
3306 NodeManager

hadoop_version=Hadoop 2.0.0-cdh4.3.0

Then i installed hive(hiv version-hive-0.10.0) from apache tarballs and I tried running bin/hive. But I am getting below error:

Unable to determine Hadoop version information.
hadoop version returned:

/home/hduser/hadoop/etc/hadoop /usr/lib/jvm/jdk1.6.0_45/
Hadoop 2.0.0-cdh4.3.0
Subversion file:///var/lib/jenkins/workspace/CDH4.3.0-Packaging-Hadoop/build/cdh4/hadoop/2.0.0-cdh4.3.0/source/hadoop-common-project/hadoop-common -r 48a9315b342ca16de92fcc5be95ae3650629155a
Compiled by jenkins on Mon May 27 19:06:57 PDT 2013
From source with checksum a4218d77f9b12df4e3e49ef96f9d357d
This command was run using /home/hduser/hadoop/share/hadoop/common/hadoop-common-2.0.0-cdh4.3.0.jar

I tried it to resolve through my scripting knowledge but can't. When I stretched my effort I found that it is failing in below line:

if [[ "$HADOOP_VERSION" =~ $hadoop_version_re ]]; then

and I tried to echo HADOOP_VERSION it returned nothing and HADOOP_VERSION is defined as

HADOOP_VERSION=$($HADOOP version | awk '{if (NR == 1) {print $2;}}');

and $HADOOP version yields me

 /home/hduser/hadoop/etc/hadoop
 /usr/lib/jvm/jdk1.6.0_45/
 Hadoop 2.0.0-cdh4.3.0
 Subversion file:///var/lib/jenkins/workspace/CDH4.3.0-Packaging-Hadoop/build/cdh4/hadoop/2.0.0-cdh4.3.0/source/hadoop-common-project/hadoop-common -r 48a9315b342ca16de92fcc5be95ae3650629155a
 Compiled by jenkins on Mon May 27 19:06:57 PDT 2013
 From source with checksum a4218d77f9b12df4e3e49ef96f9d357d
 This command was run using /home/hduser/hadoop/share/hadoop/common/hadoop-common-2.0.0-cdh4.3.0.jar

I am struck this for a week now. Please help me out. Thanks.


问:
Push ant generated artifact to archiva repository through jenkins
I am new to Jenkins and ant. I have a ant and maven project. The ant build file is used to generate custom jar file. I need to automate the process of uploading this jar file to Archiva repository. Please help.</p>

答: You can run Ant build files from Maven using the Maven-Antrun-Plugin. I had a similar problem and used the Maven-Antrun-Plugin to generate the jar and then the deploy:deploy-file goal to push it to Nexus. Archiva will probably work in the same way.


问:
Java File.delete() does not delete all files
I have the following Java code which iterates through all the files in a directory and deletes them.

```<code>for(File file : tmpDir.listFiles())
{
    file.delete();
}
</code>```

It does however not delete all files. Some, usually 20-30, out of a couple of thousand, are left behind when I do this. Is it possible to fix this, or have I stumbled upon some Java voodoo that is best left alone?

答:
Make sure that you don't have any open stream like BufferedReader/Writer, FileReader/Writer etc. First close them, then you should be able to delete the file.
One more point, E.g. if you open a BufferedReader via another reader like FileReader, you must close both of the readers seperately.

So instead of this:

```<code>BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)););
</code>```

do this:

```<code>BufferedReader bufferedReader = null;
FileReader fileReader = null;

try{
    fileReader = new FileReader(readFile);
    bufferedReader = new BufferedReader(fileReader);

}catch{...}

...

try {
    fileReader.close();
    bufferedReader .close();
    readFile.delete();
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Body:
I have the following Java code which iterates through all the files in a directory and deletes them.

for(File file : tmpDir.listFiles())
{
    file.delete();
}

It does however not delete all files. Some, usually 20-30, out of a couple of thousand, are left behind when I do this. Is it possible to fix this, or have I stumbled upon some Java voodoo that is best left alone?

Body:
Make sure that you don't have any open stream like BufferedReader/Writer, FileReader/Writer etc. First close them, then you should be able to delete the file.
One more point, E.g. if you open a BufferedReader via another reader like FileReader, you must close both of the readers seperately.

So instead of this:

BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)););

do this:

BufferedReader bufferedReader = null;
FileReader fileReader = null;

try{
    fileReader = new FileReader(readFile);
    bufferedReader = new BufferedReader(fileReader);

}catch{...}

...

try {
    fileReader.close();
    bufferedReader .close();
    readFile.delete();
} catch (IOException e) {
    e.printStackTrace();
}


问:
two-way handshake and three-way handshake
I was reading a book about computer network written by Tanenbaum specifically about handshaking. In there he explains two-way handshake is not enough, considering this case:

A wants to transfer money to B, so A sends a SYN to B, and then B sends an ACK to A. Connection is established and then A can send his money and then drop the connection after it's done. If there is a delayed duplicate SYN from A to B, B will send its ACK again and A will be transferring its money again.

That is one of the weakness of two-way handshake based on the book written by Tanenbaum if I understands it right. The book says three-way handshake can solve this problem.

With a delayed duplicate SYN from A, B sends an ACK and SYN which get rejected by A. This is where I don't get it, it's as if "Hey B why do you send me a SYN and ACK? Oh I know, this is from a delayed SYN, I should just drop it.". Why not, in two-way handshake, A doesn't know that the ACK is made by a delayed duplicate SYN?

Thanks.

答:
The three-way handshake is necessary because both parties need to synchronize their segment sequence numbers used during their transmission.

So, they(in turn) send a SYN segment with a sequence number set to a value n, which then is acknowledged by the other party via a ACK segment with a sequence number set to n+1.

Suppose that client does not send ACK(case of 2 way handshake). Now there might exist a case where seq number of client is not synchronized, but the server will assume that it is synchronized. This could cause a problem.


问:
Reading files from SFTP with file name filter on poll basis in mule
I am using groovy script with file name filter to read file from SFTP location on Poll basis using below code

```<code> <poll doc:name="Poll">
            <schedulers:cron-scheduler expression="${payment.schedule}"/>
            <scripting:transformer doc:name="Groovy">
                <scripting:script engine="Groovy">
                    <scripting:text><![CDATA[
            def endpointBuilder = muleContext.endpointFactory.getEndpointBuilder(
                    "sftp://${sftp.user}:${sftp.password}@${sftp.host}:${sftp.port}/${sftp.root.path}")
                    endpointBuilder.addMessageProcessor(new org.mule.routing.MessageFilter(new org.mule.transport.file.filters.FilenameWildcardFilter('payment_*')))
                    def inboundEndpoint = endpointBuilder.buildInboundEndpoint()
                    inboundEndpoint.request(3000L) ;
                    ]]></scripting:text>
                </scripting:script>
            </scripting:transformer>
</poll>
</code>```

Issue which I am facing here is that, Its reading only one file on each poll schedule.
However, my expectation is, it should read all the file which satisfies the condition of filter from SFTP location on each poll schedule.

How can I achieve this?
Thanks.

答:
You may want to use the SFTP Inbound Endpoint with file:filename-wildcard-filter instead of relying on a Groovy script wrapped in a poll. Such as:

```<code><sftp:inbound-endpoint host="${sftp.host}" port="${sftp.port}" path="/home/test/sftp-files" user="${sftp.user}" password="${sftp.password}">
    <file:filename-wildcard-filter pattern="payment_*"/>
</sftp:inbound-endpoint>
</code>```

See the related example in SFTP documentation.

Body:
I am using groovy script with file name filter to read file from SFTP location on Poll basis using below code

 <poll doc:name="Poll">
            <schedulers:cron-scheduler expression="${payment.schedule}"/>

                </scripting:script>
            </scripting:transformer>
</poll>

Issue which I am facing here is that, Its reading only one file on each poll schedule.
However, my expectation is, it should read all the file which satisfies the condition of filter from SFTP location on each poll schedule.

How can I achieve this?
Thanks.

Body:
You may want to use the SFTP Inbound Endpoint with file:filename-wildcard-filter instead of relying on a Groovy script wrapped in a poll. Such as:

<sftp:inbound-endpoint host="${sftp.host}" port="${sftp.port}" path="/home/test/sftp-files" user="${sftp.user}" password="${sftp.password}">
    <file:filename-wildcard-filter pattern="payment_*"/>
</sftp:inbound-endpoint>

See the related example in SFTP documentation.


问:
Eliminate flash of unstyled content
How do I stop the flash of unstyled content (FOUC) on a web page?</p>

答:
An other quick fix which also works in Firefox Quantum is an empty
```

Title: Eliminate flash of unstyled content

Body:
An other quick fix which also works in Firefox Quantum is an empty <script> tag in the <head>. This however, penalizes your pagespeed insights and overall load time.

I had 100% success with it. I think it's also the main reason, why above solutions with other JS in the  works.

<script type="text/javascript">

</script>


问:
How to fix ionic 2 Apple Mach-O Linker error?
I'm building an ionic 2 app, and I can build the app with ionic build ios and I get no erros, but on xcode when I build my application I get the following error.

Apple Mach-O Linker (id) Error
Linker command failed with exit code 1 (use -v to see invocation).

How can I fix this?

Here is my system information

Cordova CLI: 6.5.0

Ionic Framework Version: 2.3.0

Ionic CLI Version: 2.2.2

Ionic App Lib Version: 2.2.1

Ionic App Scripts Version: 1.1.4

ios-deploy version: 1.9.0

OS: macOS Sierra

Node Version: v6.9.4

Xcode Version: Xcode 8.3 Build version 8E162

答:
Had the same issue, spent almost a day trying to figure out what was causing it. For me the following solved it. Everything was working fine on ios@4.3.1, but on 4.5.3, I got this annoying error.

Check if this plugin "cordova-plugin-console" is there in the plugins folder. If it is there, remove it. Then it started building without any errors.

ionic cordova plugin remove cordova-plugin-console


问:
Python, Anaconda 3 - How to Install PRAW (Windows 10)
I am attempting to build a reddit bot using python, which I have just started learning 10 hours ago.

I am mainly a Java user, but I have also worked with C Sharp, MATLAB, SQL and the like. I would love to work on this project in Java, but as I understand it PRAW is the easiest wrapper to use for reddit.

I am using the IDE Spyder (From Anaconda 3), and am building this little bot on Windows 10. I have come across many "tutorials" that give an install command such as "pip install praw". What they don't say is WHERE to enter this command! I've tried my CMD, IPython, and Powershell.

Do I have to download pip and praw separately? Are those libraries included in Anaconda? I would greatly appreciate any clarification!

答:
you need to export anaconda path to environmental variables.so pip is available from command line.
then u can install from windows cmd C:>pip install praw.

Updated
  u need to append PATH of windows environmental variables, u can google it how to append PATH if in doubt..
  just search environmental variables in win 10, result will pop, enter it,
  just append user or system variable's PATH with anaconda installation directory, like in picture..
  & u are good to go..

  FYI:My anaconda is installed in %localappdata%\Continuum


问:
Magento how to display country flag in currency drop down?

I am trying to add all country flag in currency change dropdown in magento?
how may i do this in magento 1.4.2 ?

答:
Currency selector with flag in magento

You need to prepare a flag list (images).

Upload flag list to root/media/flag directory

Rename flags to currency’s code (EX: US Dollar -> usd-flag.jpg, Euro -> eur-flag.jpg, Hong Kong Dollar -> hkd-flag.jpg...)

In the template file: app/design/frontend/default/your_theme/template/directory/currency.phtml (or app/design/frontend/base/default/template/directory/currency.phtml), change code to:

```<code><?php foreach ($this->getCurrencies() as $_code => $_name): ?>
       <a href="<?php echo $this->getSwitchCurrencyUrl($_code) ?>" onclick="setLocation(this.value);">
        <img src="<?php echo Mage::getBaseUrl('media').'flag/'.$_code.'.jpg'; ?>" title="<?php echo $_name ?> - <?php echo $_code ?>" alt="<?php echo $_name ?> - <?php echo $_code ?>" width="20" height="20" />
        </a>
<?php endforeach; ?>
</code>```

Body:
Currency selector with flag in magento

You need to prepare a flag list (images).

Upload flag list to root/media/flag directory

Rename flags to currency’s code (EX: US Dollar -> usd-flag.jpg, Euro -> eur-flag.jpg, Hong Kong Dollar -> hkd-flag.jpg...)

In the template file: app/design/frontend/default/your_theme/template/directory/currency.phtml (or app/design/frontend/base/default/template/directory/currency.phtml), change code to:

<?php foreach ($this->getCurrencies() as $_code => $_name): ?>
       <a href="<?php echo $this->getSwitchCurrencyUrl($_code) ?>" onclick="setLocation(this.value);">
        <img src="<?php echo Mage::getBaseUrl('media').'flag/'.$_code.'.jpg'; ?>" title="<?php echo $_name ?> - <?php echo $_code ?>" alt="<?php echo $_name ?> - <?php echo $_code ?>" width="20" height="20" />
        </a>
<?php endforeach; ?>


问:
Installing PhantomJS on Mac
I'm trying to install PhantomJS on my Mac (Yosemite).

I did the following:

```<code>npm install phantomjs
</code>```

Then I did:

```<code>npm install phantomjs-prebuilt
</code>```

Both of which appear in my node_modules. But when I try to run phantomjs --versionI get

```<code>   -bash: phantomjs: command not found
</code>```

Also tried installing the binary from the downloads website, but nothing. What am I missing? End goal is to use casperjs but currently casper is asking

```<code>Fatal: [Errno 2] No such file or directory; did you install phantomjs?
</code>```

I thought I did....?

答:
Shouldn't you be installing phantomjs globally?

npm install -g phantomjs

Since you are installing it locally, the command -

phantomjs -v

would not work everywhere.

You can check the difference between local install and global install here: https://docs.npmjs.com/cli/install

Title: Installing PhantomJS on Mac

Body:
I'm trying to install PhantomJS on my Mac (Yosemite).

I did the following:

npm install phantomjs

Then I did:

npm install phantomjs-prebuilt

Both of which appear in my node_modules. But when I try to run phantomjs --versionI get

   -bash: phantomjs: command not found

Also tried installing the binary from the downloads website, but nothing. What am I missing? End goal is to use casperjs but currently casper is asking

Fatal: [Errno 2] No such file or directory; did you install phantomjs?

I thought I did....?