问:
Remove UIViewcontroller from Presentmodelview stack
i want to remove UIViewcontroller from a stack of present model view

i have below scene

```<code>UIViewcontrollerA
UIViewcontrollerB
UIViewcontrollerA
UIViewcontrolleC
UIViewcontrolleA
UIViewcontrolleA
</code>```

i want to remove all UIViewcontrolleA from this presented view controllers.

How do i get these?
so the output will be

```<code> UIViewcontrollerB
 UIViewcontrolleC
</code>```

i can easily do it in navigation controller ,similarly need in presentmodelcontroller.

```<code>NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
[allViewControllers removeObjectAtIndex:0];
[allViewControllers removeObjectAtIndex:1];

[self.navigationController setViewControllers:allViewControllers animated:YES];
</code>```

答:
dismissViewControllerAnimated:completion: when invoked on a vc will remove it and anything presented above it.

```<code>A->B->C->D->E
</code>```

So to dismiss, say D and E in the above stack, just invoke dismiss on C.  To restore D and E, present them again without animation.  You'll need to keep track of this A,B,C... array yourself.

Also note that the fact that you see so little support for this in the SDK is evidence that the idea isn't encouraged.

Body:
i want to remove UIViewcontroller from a stack of present model view

i have below scene

UIViewcontrollerA
UIViewcontrollerB
UIViewcontrollerA
UIViewcontrolleC
UIViewcontrolleA
UIViewcontrolleA

i want to remove all UIViewcontrolleA from this presented view controllers.

How do i get these?
so the output will be

 UIViewcontrollerB
 UIViewcontrolleC

i can easily do it in navigation controller ,similarly need in presentmodelcontroller.

NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
[allViewControllers removeObjectAtIndex:0];
[allViewControllers removeObjectAtIndex:1];

[self.navigationController setViewControllers:allViewControllers animated:YES];

Body:
dismissViewControllerAnimated:completion: when invoked on a vc will remove it and anything presented above it.

A->B->C->D->E

So to dismiss, say D and E in the above stack, just invoke dismiss on C.  To restore D and E, present them again without animation.  You'll need to keep track of this A,B,C... array yourself.

Also note that the fact that you see so little support for this in the SDK is evidence that the idea isn't encouraged.


来源: stackexchange

问:
drop down using ajax and css
I make a list and make it hyperlink using @Ajax.ActinLink so that on click nested list can be opened using Partial View. When I click on the first list option partial view is displayed but when I click on the second list option, partial view is not opened Here is my code:

```<code><ul id="menu">
           <h3>Categories</h3>
            @foreach (company company in @Model)
            {
              <li>
                   @Ajax.ActionLink(company.COMPANY_NAME, "All", new AjaxOptions()
                   {
                      HttpMethod = "GET",
                      UpdateTargetId = "yr",
                      InsertionMode = InsertionMode.Replace
                   })
                <ul class="sub-menu">
                    <li id="yr"></li>
                </ul>
              </li>
            }
</ul>
</code>```

here 2016 and 2017 comes from the partial view but it does not display when i click on the BMW

答:
I see that you're using C# razor syntax, I'm going to infer you're using some form of ASP.NET and creating an application in that manner. They're much better ways to make this call than using AJAX. AJAX is outdated and isn't the best implementation to use when you're working with C# razor syntax. I would make the HTTP GET request call to your controller using JS or angularJS. Take a look at this example of loading comments in a web page using an HTTP GET request below.

```<code>    <script type="text/javascript">

    // Http GET Request to load the comments at each page refresh.
    var app = angular.module('myArticleViewer', []);
    app.controller('myArticleController', function ($scope, $http, $timeout) {
        try {
            $http({
                method: "GET",
                url: "/Documentation/Comments/@Model.ArticlesViewModelID"
            }).then(function mySucces(response) {

                $scope.data = response.data;
            });
        } catch (e) {
            alert("Error: Bad Request");
        }

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

You're going to make the HTTP GET request to a controller action, in the corresponding controller responsible for the page. Then you're going to return a list of hyperlinked URLs as the value for the controller action you're making the HTTP GET request to. Then, using angularJS and ngDirectives, you're going to write HTML code for a dropdown box and iterate through the data returned from the angularJS HTTP GET request call. This will provide you with the result you seek.

ContentLicense: CC BY-SA 3.0

Title: drop down using ajax and css

Body:
I make a list and make it hyperlink using @Ajax.ActinLink so that on click nested list can be opened using Partial View. When I click on the first list option partial view is displayed but when I click on the second list option, partial view is not opened Here is my code:

Categories

            @foreach (company company in @Model)
            {

                   @Ajax.ActionLink(company.COMPANY_NAME, "All", new AjaxOptions()
                   {
                      HttpMethod = "GET",
                      UpdateTargetId = "yr",
                      InsertionMode = InsertionMode.Replace
                   })

            }

here 2016 and 2017 comes from the partial view but it does not display when i click on the BMW

Body:
I see that you're using C# razor syntax, I'm going to infer you're using some form of ASP.NET and creating an application in that manner. They're much better ways to make this call than using AJAX. AJAX is outdated and isn't the best implementation to use when you're working with C# razor syntax. I would make the HTTP GET request call to your controller using JS or angularJS. Take a look at this example of loading comments in a web page using an HTTP GET request below.

    <script type="text/javascript">

    // Http GET Request to load the comments at each page refresh.
    var app = angular.module('myArticleViewer', []);
    app.controller('myArticleController', function ($scope, $http, $timeout) {
        try {
            $http({
                method: "GET",
                url: "/Documentation/Comments/@Model.ArticlesViewModelID"
            }).then(function mySucces(response) {

                $scope.data = response.data;
            });
        } catch (e) {
            alert("Error: Bad Request");
        }

    });
    </script>

You're going to make the HTTP GET request to a controller action, in the corresponding controller responsible for the page. Then you're going to return a list of hyperlinked URLs as the value for the controller action you're making the HTTP GET request to. Then, using angularJS and ngDirectives, you're going to write HTML code for a dropdown box and iterate through the data returned from the angularJS HTTP GET request call. This will provide you with the result you seek.


问:
anaconda ImportError: No module named numpy after pip uninstall
I am using a ipython conda python 2.7 virtual environment.

After a suggestion of a probable conflict between conda numpy and pip numpy, i uninstalled the "pip numpy" using pip uninstall numpy.

When I try importing numpy, i now get the following error :

ImportError: No module named numpy

If i execute conda list in my environment, i get

```<code>... [list of other packages]
numpy                     1.11.3                   py27_0
...
</code>```

which seems to indicate that conda numpy package is still installed. I also can't install numpy using conda install, which says that 'All requested packages already installed.'

a print sys.path will result in

```<code>'', '/home/<user>/anaconda3/envs/py27/lib/python27.zip', '/home/<user>/anaconda3/envs/py27/lib/python2.7', '/home/<user>/anaconda3/envs/py27/lib/python2.7/plat-linux2', '/home/<user>/anaconda3/envs/py27/lib/python2.7/lib-tk', '/home/<user>/anaconda3/envs/py27/lib/python2.7/lib-old', '/home/<user>/anaconda3/envs/py27/lib/python2.7/lib-dynload', '/home/<user>/anaconda3/envs/py27/lib/python2.7/site-packages', '/home/<user>/anaconda3/envs/py27/lib/python2.7/site-packages/Sphinx-1.5.1-py2.7.egg', '/home/<user>/anaconda3/envs/py27/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg'
</code>```

Can anyone explain me why i cant use the numpy package listed in the conda packages ?

Thank you !

答:
If you are using 64-bit python3 conda then numpy package is installed default for python3, since you are using python2 you have to do the following steps:

first open anaconda prompt
then type conda info --envs .
It displays the environments installed and the
environment adjacent to which * is found is the default environment.
Activate the desired environment by typing
activate environmentname.
After that type comment

```<code>conda install numpy.
</code>```

Body:
I am using a ipython conda python 2.7 virtual environment.

After a suggestion of a probable conflict between conda numpy and pip numpy, i uninstalled the "pip numpy" using pip uninstall numpy.

When I try importing numpy, i now get the following error :

ImportError: No module named numpy

If i execute conda list in my environment, i get

... [list of other packages]
numpy                     1.11.3                   py27_0
...

which seems to indicate that conda numpy package is still installed. I also can't install numpy using conda install, which says that 'All requested packages already installed.'

a print sys.path will result in

'', '/home/<user>/anaconda3/envs/py27/lib/python27.zip', '/home/<user>/anaconda3/envs/py27/lib/python2.7', '/home/<user>/anaconda3/envs/py27/lib/python2.7/plat-linux2', '/home/<user>/anaconda3/envs/py27/lib/python2.7/lib-tk', '/home/<user>/anaconda3/envs/py27/lib/python2.7/lib-old', '/home/<user>/anaconda3/envs/py27/lib/python2.7/lib-dynload', '/home/<user>/anaconda3/envs/py27/lib/python2.7/site-packages', '/home/<user>/anaconda3/envs/py27/lib/python2.7/site-packages/Sphinx-1.5.1-py2.7.egg', '/home/<user>/anaconda3/envs/py27/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg'

Can anyone explain me why i cant use the numpy package listed in the conda packages ?

Thank you !

Body:
If you are using 64-bit python3 conda then numpy package is installed default for python3, since you are using python2 you have to do the following steps:

first open anaconda prompt
then type conda info --envs .
It displays the environments installed and the
environment adjacent to which * is found is the default environment.
Activate the desired environment by typing
activate environmentname.
After that type comment

conda install numpy.


问:
Vegalite daily line chart wobble
I've run into an issue with vegalite whereby charts exhibit a 'wobbling line' when the line should be straight, and dates are not equally spaced.

Can anyone verify that this is a bug, or am I making a mistake in my spec?
.

I have found that this issue becomes more severe when you increase the number of data points.

To replicate this issue, paste the following spec into the vega lite editor:

```<code>{
  "description": "",
  "data": {
    "values": [
      {
        "date": "2017-01-23",
        "value": 100
      },
      {
        "date": "2017-01-24",
        "value": 200
      },
      {
        "date": "2017-01-25",
        "value": 300
      },
      {
        "date": "2017-01-26",
        "value": 400
      },
      {
        "date": "2017-01-27",
        "value": 500
      },
      {
        "date": "2017-01-28",
        "value": 600
      },
      {
        "date": "2017-01-29",
        "value": 700
      },
      {
        "date": "2017-01-30",
        "value": 800
      },
      {
        "date": "2017-01-31",
        "value": 900
      },
      {
        "date": "2017-02-01",
        "value": 1000
      },
      {
        "date": "2017-02-02",
        "value": 1100
      },
      {
        "date": "2017-02-03",
        "value": 1200
      },
      {
        "date": "2017-02-04",
        "value": 1300
      },
      {
        "date": "2017-02-05",
        "value": 1400
      },
      {
        "date": "2017-02-06",
        "value": 1500
      },
      {
        "date": "2017-02-07",
        "value": 1600
      }
    ]
  },
  "mark": "line",
  "encoding": {
    "x": {
      "field": "date",
      "type": "temporal"
    },
    "y": {
      "field": "value"
    }
  },
  "config": [],
  "embed": {
    "renderer": "canvas",
    "actions": {
      "export": false,
      "source": false,
      "editor": false
    }
  }
}
</code>```

Edit:  Followup - experimenting in Altair, it seems like the date aspect of this is irrelevant.  You get the same problem with both of the following code blocks:

```<code>import pandas as pd
import numpy as np
from altair import *

s1 = pd.date_range(start="2017-01-23", end="2020-02-07")
s2  = np.arange(1,len(s1)+1)*100
df = pd.DataFrame({"date":s1, "value":s2})

Chart(df).mark_line(
).encode(
    x='date',
    y='value'
)
</code>```

and

```<code>import pandas as pd
import numpy as np
from altair import *

s1 = np.arange(1,1000,1)
s2  = np.arange(1,len(s1)+1)*100
df = pd.DataFrame({"x":s1, "value":s2})

Chart(df).mark_line(
).encode(
    x='x',
    y='value'
)
</code>```

Conversely the following produced a smooth plot (pandas and matplotlib):

```<code>%matplotlib inline
df.plot('date', 'value')
</code>```

答:
The wiggle is caused by an effect of rounding error during the calculation of the pixel coordinates relevant to the data values.

Looking at the vega code produced by vega-lite, one can see the "round": true entries for the defined scales. Changing this to false solves the problem on my screen, and making vega-lite do that, is also possible by adding:

```<code>"config": {"scale": {"round" : false}},
</code>```

instead of the

```<code>"config": [],
</code>```

line in the vega-lite spec.

Title: Vegalite daily line chart wobble

Body:
I've run into an issue with vegalite whereby charts exhibit a 'wobbling line' when the line should be straight, and dates are not equally spaced.

Can anyone verify that this is a bug, or am I making a mistake in my spec?
.

I have found that this issue becomes more severe when you increase the number of data points.

To replicate this issue, paste the following spec into the vega lite editor:

{
  "description": "",
  "data": {
    "values": [
      {
        "date": "2017-01-23",
        "value": 100
      },
      {
        "date": "2017-01-24",
        "value": 200
      },
      {
        "date": "2017-01-25",
        "value": 300
      },
      {
        "date": "2017-01-26",
        "value": 400
      },
      {
        "date": "2017-01-27",
        "value": 500
      },
      {
        "date": "2017-01-28",
        "value": 600
      },
      {
        "date": "2017-01-29",
        "value": 700
      },
      {
        "date": "2017-01-30",
        "value": 800
      },
      {
        "date": "2017-01-31",
        "value": 900
      },
      {
        "date": "2017-02-01",
        "value": 1000
      },
      {
        "date": "2017-02-02",
        "value": 1100
      },
      {
        "date": "2017-02-03",
        "value": 1200
      },
      {
        "date": "2017-02-04",
        "value": 1300
      },
      {
        "date": "2017-02-05",
        "value": 1400
      },
      {
        "date": "2017-02-06",
        "value": 1500
      },
      {
        "date": "2017-02-07",
        "value": 1600
      }
    ]
  },
  "mark": "line",
  "encoding": {
    "x": {
      "field": "date",
      "type": "temporal"
    },
    "y": {
      "field": "value"
    }
  },
  "config": [],
  "embed": {
    "renderer": "canvas",
    "actions": {
      "export": false,
      "source": false,
      "editor": false
    }
  }
}

Edit:  Followup - experimenting in Altair, it seems like the date aspect of this is irrelevant.  You get the same problem with both of the following code blocks:

import pandas as pd
import numpy as np
from altair import *

s1 = pd.date_range(start="2017-01-23", end="2020-02-07")
s2  = np.arange(1,len(s1)+1)*100
df = pd.DataFrame({"date":s1, "value":s2})

Chart(df).mark_line(
).encode(
    x='date',
    y='value'
)

and

import pandas as pd
import numpy as np
from altair import *

s1 = np.arange(1,1000,1)
s2  = np.arange(1,len(s1)+1)*100
df = pd.DataFrame({"x":s1, "value":s2})

Chart(df).mark_line(
).encode(
    x='x',
    y='value'
)

Conversely the following produced a smooth plot (pandas and matplotlib):

%matplotlib inline
df.plot('date', 'value')

Body:
The wiggle is caused by an effect of rounding error during the calculation of the pixel coordinates relevant to the data values.

Looking at the vega code produced by vega-lite, one can see the "round": true entries for the defined scales. Changing this to false solves the problem on my screen, and making vega-lite do that, is also possible by adding:

"config": {"scale": {"round" : false}},

instead of the

"config": [],

line in the vega-lite spec.


问:
Group pandas DataFrame by columns and produce lists out of groups of columns
Assuming we have the following input DataFrame:

```<code>In [80]: %paste
data = {
 'Item_2_id': {0: 24, 1: 41, 2: 34},
 'Item_2_quantity': {0: 4, 1: 1, 2: 4},
 'Item_3_id': {0: 16, 1: 33, 2: 8},
 'Item_3_quantity': {0: 1, 1: 1, 2: 2},
 'customer_name': {0: 'John', 1: 'Paul', 2: 'Andrew'},
 'item_1_id': {0: 4, 1: 8, 2: 1},
 'item_1_quantity': {0: 1, 1: 3, 2: 1},
 'order_id': {0: 1, 1: 2, 2: 3}
}
cols = 'order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity'.split()

df = pd.DataFrame(data)[cols]

df
## -- End pasted text --
Out[80]:
   order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity
0         1          John          4                1         24                4         16                1
1         2          Paul          8                3         41                1         33                1
2         3        Andrew          1                1         34                4          8                2
</code>```

How can we group all id and quantity columns, so that we will get the following desired DataFrame:

```<code>In [85]: result
Out[85]:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]
</code>```

My attempts:

```<code>In [191]: id_vars = ['order_id','customer_name']

In [192]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: x.tolist())
Out[192]:
                                                 id                                       quantity
order_id customer_name
1        John           (i, t, e, m, _, 1, _, i, d)  (i, t, e, m, _, 1, _, q, u, a, n, t, i, t, y)
2        Paul           (I, t, e, m, _, 2, _, i, d)  (I, t, e, m, _, 2, _, q, u, a, n, t, i, t, y)
3        Andrew         (I, t, e, m, _, 3, _, i, d)  (I, t, e, m, _, 3, _, q, u, a, n, t, i, t, y)
</code>```

if i just print it - it works properly:

```<code>In [193]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: print(x.tolist()))
[4, 24, 16]
[8, 41, 33]
[1, 34, 8]
[1, 4, 1]
[3, 1, 1]
[1, 4, 2]
Out[193]:
                          id quantity
order_id customer_name
1        John           None     None
2        Paul           None     None
3        Andrew         None     None
</code>```

PS actually I came to that problem when I was trying to answer another question and i found another solution, but I feel like there must be much more elegant solution, which is using something like:

```<code>df.groupby(..., axis=1).agg(...)
</code>```

or

```<code>df.groupby(..., axis=1).apply(...)
</code>```

答:
Not as good as @MaxU:</p>

```<code>id_cols = [col for col in list(df) if 'id' in col and col not in 'order_id']
quant_cols = [col for col in list(df) if 'quantity' in col]

df2 = df[['order_id', 'customer_name']].copy()
df2['quantity'] = list(df[quant_cols].values)
df2['id'] = list(df[id_cols].values)

df2:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]
</code>```

Body:
Assuming we have the following input DataFrame:

In [80]: %paste
data = {
 'Item_2_id': {0: 24, 1: 41, 2: 34},
 'Item_2_quantity': {0: 4, 1: 1, 2: 4},
 'Item_3_id': {0: 16, 1: 33, 2: 8},
 'Item_3_quantity': {0: 1, 1: 1, 2: 2},
 'customer_name': {0: 'John', 1: 'Paul', 2: 'Andrew'},
 'item_1_id': {0: 4, 1: 8, 2: 1},
 'item_1_quantity': {0: 1, 1: 3, 2: 1},
 'order_id': {0: 1, 1: 2, 2: 3}
}
cols = 'order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity'.split()

df = pd.DataFrame(data)[cols]

df
## -- End pasted text --
Out[80]:
   order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity
0         1          John          4                1         24                4         16                1
1         2          Paul          8                3         41                1         33                1
2         3        Andrew          1                1         34                4          8                2

How can we group all id and quantity columns, so that we will get the following desired DataFrame:

In [85]: result
Out[85]:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]

My attempts:

In [191]: id_vars = ['order_id','customer_name']

In [192]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: x.tolist())
Out[192]:
                                                 id                                       quantity
order_id customer_name
1        John           (i, t, e, m, _, 1, _, i, d)  (i, t, e, m, _, 1, _, q, u, a, n, t, i, t, y)
2        Paul           (I, t, e, m, _, 2, _, i, d)  (I, t, e, m, _, 2, _, q, u, a, n, t, i, t, y)
3        Andrew         (I, t, e, m, _, 3, _, i, d)  (I, t, e, m, _, 3, _, q, u, a, n, t, i, t, y)

if i just print it - it works properly:

In [193]: df.set_index(id_vars) \
            .groupby(lambda x: x.split('_')[-1], axis=1) \
            .agg(lambda x: print(x.tolist()))
[4, 24, 16]
[8, 41, 33]
[1, 34, 8]
[1, 4, 1]
[3, 1, 1]
[1, 4, 2]
Out[193]:
                          id quantity
order_id customer_name
1        John           None     None
2        Paul           None     None
3        Andrew         None     None

PS actually I came to that problem when I was trying to answer another question and i found another solution, but I feel like there must be much more elegant solution, which is using something like:

df.groupby(..., axis=1).agg(...)

or

df.groupby(..., axis=1).apply(...)

Body:
Not as good as @MaxU:

id_cols = [col for col in list(df) if 'id' in col and col not in 'order_id']
quant_cols = [col for col in list(df) if 'quantity' in col]

df2 = df[['order_id', 'customer_name']].copy()
df2['quantity'] = list(df[quant_cols].values)
df2['id'] = list(df[id_cols].values)

df2:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]


问:
How can i convert linux "date +%s" output to a more readable format in bash script
Here is the script:

```<code>
#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

</code>
```

so i want to convert $startTime into a UTC format

答:
Got perl?</p>

```<code>human_time=$(perl -e 'print scalar gmtime(shift)' $startTime)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is the script:

#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

so i want to convert $startTime into a UTC format

Body:
Got perl?

human_time=$(perl -e 'print scalar gmtime(shift)' $startTime)


问:
Apache Spark: Hangs on Broadcast
I'm having a hard time debugging my Spark 1.6.2 application on Yarn. It is running in client-mode. Essentially it is locking up without crashing and the logs in the console are as shown below when it locks up.

```<code>17/03/31 20:12:02 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh007.prod.phx3.gdg:47579 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on p3plcdsh011.prod.phx3.gdg:63228 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_4_piece0 in memory on p3plcdsh015.prod.phx3.gdg:9377 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_4_piece0 in memory on p3plcdsh015.prod.phx3.gdg:61897 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh002.prod.phx3.gdg:23170 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on p3plcdsh016.prod.phx3.gdg:16649 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh003.prod.phx3.gdg:55147 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_4_piece0 in memory on p3plcdsh008.prod.phx3.gdg:7619 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh003.prod.phx3.gdg:40830 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh011.prod.phx3.gdg:20056 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh008.prod.phx3.gdg:47385 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh003.prod.phx3.gdg:2063 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh011.prod.phx3.gdg:63228 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh008.prod.phx3.gdg:64036 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh016.prod.phx3.gdg:16649 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh013.prod.phx3.gdg:31979 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh013.prod.phx3.gdg:18407 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh004.prod.phx3.gdg:45536 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh008.prod.phx3.gdg:50826 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:06 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh015.prod.phx3.gdg:36247 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:06 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh015.prod.phx3.gdg:22848 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:06 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh015.prod.phx3.gdg:9377 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:06 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh015.prod.phx3.gdg:61897 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:07 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh008.prod.phx3.gdg:7619 (size: 26.7 KB, free: 511.1 MB)
</code>```

In the Spark UI, the lockup occurs at either a map or filter function.

Has anyone see this occur before or knows how to debug the situation?

It looks like it might be due to a memory issue or space issue, but there's no clear indication that it is. I can try and bump the memory up and see if that it helps, but does anyone have a tip to debug?

Thank you

答:
Merely being serializable isn't enough. The problem could be a lot of things: your serialization mechanism (Java serialization is bad; Kryo is much better; and so on), your machine memory, making sure you use the broadcast value and not the wrapped value, etc.

There is also the Spark configuration spark.sql.autoBroadcastJoinThreshold:

"Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join. By setting this value to -1 broadcasting can be disabled. Note that currently statistics are only supported for Hive Metastore tables where the command ANALYZE TABLE  COMPUTE STATISTICS noscan has been run."

The default is 10MB serialized.

Finally, if you remove that default limitation and you have plenty of memory, you still prefer the size to be less than your largest RDD/DataFrame, which you can check with SizeEstimator:

```<code>import org.apache.spark.util.SizeEstimator._

logInfo(estimate(rdd))
</code>```

In the end, if worse comes to worst, I would look into doing lookups from a lightning-fast cache datastore in your transformations rather than broadcasting this file.

Title: Apache Spark: Hangs on Broadcast

Body:
I'm having a hard time debugging my Spark 1.6.2 application on Yarn. It is running in client-mode. Essentially it is locking up without crashing and the logs in the console are as shown below when it locks up.

17/03/31 20:12:02 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh007.prod.phx3.gdg:47579 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on p3plcdsh011.prod.phx3.gdg:63228 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_4_piece0 in memory on p3plcdsh015.prod.phx3.gdg:9377 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_4_piece0 in memory on p3plcdsh015.prod.phx3.gdg:61897 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh002.prod.phx3.gdg:23170 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:03 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on p3plcdsh016.prod.phx3.gdg:16649 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh003.prod.phx3.gdg:55147 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_4_piece0 in memory on p3plcdsh008.prod.phx3.gdg:7619 (size: 5.4 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh003.prod.phx3.gdg:40830 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh011.prod.phx3.gdg:20056 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh008.prod.phx3.gdg:47385 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh003.prod.phx3.gdg:2063 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh011.prod.phx3.gdg:63228 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:04 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh008.prod.phx3.gdg:64036 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh016.prod.phx3.gdg:16649 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh013.prod.phx3.gdg:31979 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh013.prod.phx3.gdg:18407 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh004.prod.phx3.gdg:45536 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:05 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh008.prod.phx3.gdg:50826 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:06 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh015.prod.phx3.gdg:36247 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:06 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh015.prod.phx3.gdg:22848 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:06 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh015.prod.phx3.gdg:9377 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:06 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh015.prod.phx3.gdg:61897 (size: 26.7 KB, free: 511.1 MB)
    17/03/31 20:12:07 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on p3plcdsh008.prod.phx3.gdg:7619 (size: 26.7 KB, free: 511.1 MB)

In the Spark UI, the lockup occurs at either a map or filter function.

Has anyone see this occur before or knows how to debug the situation?

It looks like it might be due to a memory issue or space issue, but there's no clear indication that it is. I can try and bump the memory up and see if that it helps, but does anyone have a tip to debug?

Thank you

Body:
Merely being serializable isn't enough. The problem could be a lot of things: your serialization mechanism (Java serialization is bad; Kryo is much better; and so on), your machine memory, making sure you use the broadcast value and not the wrapped value, etc.

There is also the Spark configuration spark.sql.autoBroadcastJoinThreshold:

"Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join. By setting this value to -1 broadcasting can be disabled. Note that currently statistics are only supported for Hive Metastore tables where the command ANALYZE TABLE  COMPUTE STATISTICS noscan has been run."

The default is 10MB serialized.

Finally, if you remove that default limitation and you have plenty of memory, you still prefer the size to be less than your largest RDD/DataFrame, which you can check with SizeEstimator:

import org.apache.spark.util.SizeEstimator._

logInfo(estimate(rdd))

In the end, if worse comes to worst, I would look into doing lookups from a lightning-fast cache datastore in your transformations rather than broadcasting this file.


问:
This is regarding C# interfaces
What is this piece of code printing "Hi there" as output? And which of the interface's method is getting executed? Please help me understand it's output..</p>

```<code>interface I1
    {
        void display();
    }

    interface I2
    {
        void display();
    }

    class A : I1, I2
    {
        public void display()
        {
            Console.WriteLine("Hi there");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.display();
            Console.ReadLine();
        }
    }
</code>```

答:
Interfaces do not "execute" they represent a contract that ensures that your object will behave in the same way the Interface advertises.

So in this case.. the class A is able to satisfy both interfaces it implements with a single method since both Interfaces require the same method signature.  Hence, A is an I1 and an I2 ...

```<code>A a = new A();

I1 i1 = (I1)a;
i1.display();

I2 i2 = (I2)a;
i2.display();
</code>```

Both of these display method invocations still call the one implementation.

Title: This is regarding C# interfaces

Body:
What is this piece of code printing "Hi there" as output? And which of the interface's method is getting executed? Please help me understand it's output..

interface I1
    {
        void display();
    }

    interface I2
    {
        void display();
    }

    class A : I1, I2
    {
        public void display()
        {
            Console.WriteLine("Hi there");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.display();
            Console.ReadLine();
        }
    }

Body:
Interfaces do not "execute" they represent a contract that ensures that your object will behave in the same way the Interface advertises.

So in this case.. the class A is able to satisfy both interfaces it implements with a single method since both Interfaces require the same method signature.  Hence, A is an I1 and an I2 ...

A a = new A();

I1 i1 = (I1)a;
i1.display();

I2 i2 = (I2)a;
i2.display();

Both of these display method invocations still call the one implementation.


问:
Read Excel file and see if any of the words match my dictionary in Python
So what I want to do is for my program to read my Excel file in the form of CSV. In the CSV there is a column filled with sentences, I want to check if any of the words in the sentences match my keys in Python, and then print the values one column to the right of the original column if it matches. Can this be done?
So far I have only came up with this:

```<code>import pandas as pd
my_dict = pd.read_excel('mydict.xlsx', index_col=0).to_dict()
project = pd.read_csv('project1.csv',sep=",",usecols=(3,))

for line in project:
    if key in my_dict.items():
        #print value one column to the right of original column
</code>```

Example row from csv:

Hey you 'avin a giggl' thr m8?

Example dict:

'avin = Having

giggl' = Giggle

thr = There

m8 = Mate

答:
Split your line into words

Loop the words

if word in my_dict:
       print(key ,my_dict[key])

Come back and Flag your Question as answered if this is working for you or comment why not.

Body:
So what I want to do is for my program to read my Excel file in the form of CSV. In the CSV there is a column filled with sentences, I want to check if any of the words in the sentences match my keys in Python, and then print the values one column to the right of the original column if it matches. Can this be done?
So far I have only came up with this:

import pandas as pd
my_dict = pd.read_excel('mydict.xlsx', index_col=0).to_dict()
project = pd.read_csv('project1.csv',sep=",",usecols=(3,))

for line in project:
    if key in my_dict.items():
        #print value one column to the right of original column

Example row from csv:

Hey you 'avin a giggl' thr m8?

Example dict:

'avin = Having

giggl' = Giggle

thr = There

m8 = Mate


问:
Java Android - Encrypt/Decrypt file contents
So at the moment I'm trying to write some encrypted text to a file and then be able to read that back in, decrypt it and display it to the user. I'm currently using AES-256 with PBKDF2 password derivation as I'd like to be able to use a user's password to encrypt/decrypt the files. The files are simple text files. The code I am currently using to encrypt some text and save it to a file is below. As far as I can tell, from having a look using adb, this works correctly.

```<code>FileOutputStream out = new FileOutputStream(mypath);
String defaultMessage = "Empty File";
int iterationCount = 1000;
int keyLength = 256;
int saltLength = keyLength / 8;
SecureRandom randomGenerator = new SecureRandom();
byte[] salt = new byte[saltLength];
randomGenerator.nextBytes(salt);
KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, iterationCount, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
randomGenerator.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
byte[] ciphertext = cipher.doFinal(defaultMessage.getBytes("UTF-8"));
String finalMessage = ciphertext.toString() + "]" + iv.toString() + "]" + salt.toString();
out.write(finalMessage.getBytes());
out.close();
</code>```

P.S The above is within a Try/Except.

The code below is what I'm currently trying to use to read in the file and then decrypt it, however, when I try to display the decrypted contents via the test view at the end, it does not show up.

```<code>FileInputStream fileInputStream = new FileInputStream(mypath);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((fileContents = bufferedReader.readLine()) != null) {
    stringBuffer.append(fileContents + "\n");
}
String fileContentsString = stringBuffer.toString();
String[] fileContentsList = fileContentsString.split("]");
byte[] cipherText = fileContentsList[0].getBytes();
Toast.makeText(getApplicationContext(), fileContentsList[0], Toast.LENGTH_LONG).show();
byte[] iv = fileContentsList[1].getBytes();
byte[] salt = fileContentsList[2].getBytes();
KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, 1000, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
byte[] plaintext = cipher.doFinal(cipherText);
String plainrStr = new String(plaintext , "UTF-8");
textEdit.setText(plainrStr);
</code>```

Hopefully someone can provide me with some assistance here. Again, the second code segment is within a Try/Except statement.

答:
How to write some encrypted text to a file and then be able to read that back in?

```<code>public static byte[] generateKey(String password) throws Exception
{
    byte[] keyStart = password.getBytes("UTF-8");

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    sr.setSeed(keyStart);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

    public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
    {

        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] encrypted = cipher.doFinal(fileData);

        return encrypted;
    }

    public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
    {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        byte[] decrypted = cipher.doFinal(fileData);

        return decrypted;
    }
</code>```

To save a encrypted file to sd do:

```<code>File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();
</code>```

To decode a file use:

```<code>byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);
</code>```

For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/

Body:
So at the moment I'm trying to write some encrypted text to a file and then be able to read that back in, decrypt it and display it to the user. I'm currently using AES-256 with PBKDF2 password derivation as I'd like to be able to use a user's password to encrypt/decrypt the files. The files are simple text files. The code I am currently using to encrypt some text and save it to a file is below. As far as I can tell, from having a look using adb, this works correctly.

FileOutputStream out = new FileOutputStream(mypath);
String defaultMessage = "Empty File";
int iterationCount = 1000;
int keyLength = 256;
int saltLength = keyLength / 8;
SecureRandom randomGenerator = new SecureRandom();
byte[] salt = new byte[saltLength];
randomGenerator.nextBytes(salt);
KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, iterationCount, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
randomGenerator.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
byte[] ciphertext = cipher.doFinal(defaultMessage.getBytes("UTF-8"));
String finalMessage = ciphertext.toString() + "]" + iv.toString() + "]" + salt.toString();
out.write(finalMessage.getBytes());
out.close();

P.S The above is within a Try/Except.

The code below is what I'm currently trying to use to read in the file and then decrypt it, however, when I try to display the decrypted contents via the test view at the end, it does not show up.

FileInputStream fileInputStream = new FileInputStream(mypath);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((fileContents = bufferedReader.readLine()) != null) {
    stringBuffer.append(fileContents + "\n");
}
String fileContentsString = stringBuffer.toString();
String[] fileContentsList = fileContentsString.split("]");
byte[] cipherText = fileContentsList[0].getBytes();
Toast.makeText(getApplicationContext(), fileContentsList[0], Toast.LENGTH_LONG).show();
byte[] iv = fileContentsList[1].getBytes();
byte[] salt = fileContentsList[2].getBytes();
KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, 1000, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
byte[] plaintext = cipher.doFinal(cipherText);
String plainrStr = new String(plaintext , "UTF-8");
textEdit.setText(plainrStr);

Hopefully someone can provide me with some assistance here. Again, the second code segment is within a Try/Except statement.

Body:
How to write some encrypted text to a file and then be able to read that back in?

public static byte[] generateKey(String password) throws Exception
{
    byte[] keyStart = password.getBytes("UTF-8");

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    sr.setSeed(keyStart);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

    public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
    {

        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] encrypted = cipher.doFinal(fileData);

        return encrypted;
    }

    public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
    {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        byte[] decrypted = cipher.doFinal(fileData);

        return decrypted;
    }

To save a encrypted file to sd do:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();

To decode a file use:

byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);

For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/


问:
CSS: background-image rotate without transform: rotate()
I rotated the block that is given a background-image, I need the image not to be rotated but the block that is given the image to be rotated.

page link
What must I do?

Thank you.

CSS:

```<code>   .bg {
        background-image: url("http://bagrattam.com/sss/website/images/other/paint.png");
        background-repeat: no-repeat;
        background-size: cover;
        position: absolute;
        top: -50%;
        left: -10%;
        right: -10%;
        height: 170%;
        z-index: -1;
        transform: rotate(-10deg);
    }
</code>```

答:
To do that, remove the rotation from the CSS of the .bg class and increase its height from 170% to 225%:

```<code>.bg {
    background-image: url(http://bagrattam.com/website/images/other/paint.png);
    background-repeat: no-repeat;
    background-size: cover;
    position: absolute;
    top: -50%;
    left: -10%;
    right: -10%;
    height: 225%;
    z-index: -1;
    transform: rotate(0deg);
}
</code>```

Then use the :after pseudo class to add a rotated overlay over the image which adds the skew effect:

```<code>.bg:after {
    content: "";
    font-size: 200px;
    background: #ffffff;
    display: block;
    position: absolute;
    height: 500px;
    left: 0;
    right: 0;
    bottom: -350px;
    transform: rotate(-8deg);
}
</code>```

Here's what it looks like now:

Hope this helps :)

Body:
I rotated the block that is given a background-image, I need the image not to be rotated but the block that is given the image to be rotated.

page link
What must I do?

Thank you.

CSS:

   .bg {
        background-image: url("http://bagrattam.com/sss/website/images/other/paint.png");
        background-repeat: no-repeat;
        background-size: cover;
        position: absolute;
        top: -50%;
        left: -10%;
        right: -10%;
        height: 170%;
        z-index: -1;
        transform: rotate(-10deg);
    }

Body:
To do that, remove the rotation from the CSS of the .bg class and increase its height from 170% to 225%:

.bg {
    background-image: url(http://bagrattam.com/website/images/other/paint.png);
    background-repeat: no-repeat;
    background-size: cover;
    position: absolute;
    top: -50%;
    left: -10%;
    right: -10%;
    height: 225%;
    z-index: -1;
    transform: rotate(0deg);
}

Then use the :after pseudo class to add a rotated overlay over the image which adds the skew effect:

.bg:after {
    content: "";
    font-size: 200px;
    background: #ffffff;
    display: block;
    position: absolute;
    height: 500px;
    left: 0;
    right: 0;
    bottom: -350px;
    transform: rotate(-8deg);
}

Here's what it looks like now:

Hope this helps :)

ContentLicense: CC BY-SA 4.0


问:
What is the $_REQUEST precedence?

PHP Superglobal variables

PHP has global variables which can be accessed within any scope of your script. Three of these variables ($_GET, $_POST, $_COOKIE) are stored within a fourth variable ($_REQUEST).

$_GET

An associative array of variables passed to the current script via the URL parameters.

Consider the following example in which a URL is sent and accessed.

http://www.example.com/myPage.php?myVar=myVal
```

<pre class="lang-php prettyprint-override"><code>echo $_GET["myVar"]; // returns "myVal"
</code>```

$_POST

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

An example of this being used is as follows.

<form action="somePage.php" method="POST">
    <input type="text" name="myVar" value="myVal" />
    <input type="submit" name="submit" value="Submit" />
</form>
```

<pre class="lang-php prettyprint-override"><code>echo $_POST["myVar"]; // returns "myVal"
</code>```

$_COOKIE

An associative array of variables passed to the current script via HTTP Cookies

setcookie("myVar", "myVal", time() + 3600);
echo $_COOKIE["myVar"]; // returns "myVal"
```

<h2><code>$_REQUEST</code></h2>

<blockquote>
  <p>An associative array that by default contains the contents of <code>$_GET</code>, <code>$_POST</code> and <code>$_COOKIE</code>.</p>
</blockquote>

<hr>

<h1>Here's the thing</h1>

<p><code>$_REQUEST</code> contains all three in one array and is accessed via <code>$_REQUEST["myVar"]</code>.</p>

<h2>A random scenario</h2>

<p>Let's assume, for whatever reason, that I use the same name for my <code>$_GET</code>, <code>$_POST</code>, and <code>$_COOKIE</code>.</p>

<p>What would the precedence be for what is stored in <code>$_REQUEST</code>.</p>

<p>Assuming I set a sent data through the URL, posted through the form and, set a cookie with the same name as each other (a bizarre scenario, I know).<br>
Lets say I used the name "example".</p>

<p>What would be the output of the following output?</p>

<pre class="lang-php prettyprint-override"><code>     if ($_REQUEST["example"] == $_GET["example"])    echo "GET";
else if ($_REQUEST["example"] == $_POST["example"])   echo "POST";
else if ($_REQUEST["example"] == $_COOKIE["example"]) echo "COOKIE";
</code>```

tl;dr

If $_GET, $_POST, and $_COOKIE all have a value stored with the same name; which one will $_REQUEST store under said name?

答:
You have a line in the php.ini file that describe variables_order. for example:

```<code>variables_order = "GPC"
</code>```

G is Get, P is Post and C is cookie.
In this case at the first Get variables is set to $_REQUEST, next Post variables is set to it and at the last Cookie variables is set to it. So priority is for cookie, then for Post and then for Get.

You can change the priority as you want by changing the value of variables_order in php.ini file.

P.S: You can write G,P,C,S and E in value of variables_order. S is for Session and E is for Environment variables.

P.S: In PHP 5.3 introduced request_order directive in php.ini file that set the order of setting variables directly in $_REQUEST array.

Title: What is the $_REQUEST precedence?

Body:
PHP Superglobal variables

PHP has global variables which can be accessed within any scope of your script. Three of these variables ($_GET, $_POST, $_COOKIE) are stored within a fourth variable ($_REQUEST).

$_GET

An associative array of variables passed to the current script via the URL parameters.

Consider the following example in which a URL is sent and accessed.

http://www.example.com/myPage.php?myVar=myVal

echo $_GET["myVar"]; // returns "myVal"

$_POST

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

An example of this being used is as follows.

<form action="somePage.php" method="POST">
    <input type="text" name="myVar" value="myVal" />
    <input type="submit" name="submit" value="Submit" />
</form>

echo $_POST["myVar"]; // returns "myVal"

$_COOKIE

An associative array of variables passed to the current script via HTTP Cookies

setcookie("myVar", "myVal", time() + 3600);
echo $_COOKIE["myVar"]; // returns "myVal"

$_REQUEST

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

Here's the thing

$_REQUEST contains all three in one array and is accessed via $_REQUEST["myVar"].

A random scenario

Let's assume, for whatever reason, that I use the same name for my $_GET, $_POST, and $_COOKIE.

What would the precedence be for what is stored in $_REQUEST.

Assuming I set a sent data through the URL, posted through the form and, set a cookie with the same name as each other (a bizarre scenario, I know).

Lets say I used the name "example".

What would be the output of the following output?

     if ($_REQUEST["example"] == $_GET["example"])    echo "GET";
else if ($_REQUEST["example"] == $_POST["example"])   echo "POST";
else if ($_REQUEST["example"] == $_COOKIE["example"]) echo "COOKIE";

tl;dr

If $_GET, $_POST, and $_COOKIE all have a value stored with the same name; which one will $_REQUEST store under said name?

Body:
You have a line in the php.ini file that describe variables_order. for example:

variables_order = "GPC"

G is Get, P is Post and C is cookie.
In this case at the first Get variables is set to $_REQUEST, next Post variables is set to it and at the last Cookie variables is set to it. So priority is for cookie, then for Post and then for Get.

You can change the priority as you want by changing the value of variables_order in php.ini file.

P.S: You can write G,P,C,S and E in value of variables_order. S is for Session and E is for Environment variables.

P.S: In PHP 5.3 introduced request_order directive in php.ini file that set the order of setting variables directly in $_REQUEST array.


问:
Cannot overwrite the direct attr in html with css
I am working on a big project to improve it as like any other existing project I have some limitation which I need to find a workaround for it though that might not be the best option. I have some texts in the database and some of them contains image tags such as

```<code><img src="http://www.cbc.ca/kidscbc2/content/the_feed/_848/april_fool_848.jpg" width="20" height="8"  />
</code>```

Now the problem is that these images have width and  height attributes which I do not need them at all and I need to use my own styling. I know there are different ways to fix such as cleaning the db text or parse the text and clean it before wrapping it to html but these are not doable for me right now based on some limitation I have. So I need to do this in a css:

just to give you a simple version of what I want here is a simple code:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<style>
img {
width: 100% !important;
height: 100% !important;
  }
 </style>
 </head>
 <body>

 <div style="width: 200px; height: 300px;background-color: yellow;">

    <img
src="http://www.cbc.ca/kidscbc2/content/the_feed/_848/april_fool_848.jpg"
        width="20" height="8" />

 </div>
</code>```

As you see I even added style to img with !important to overwrite the styles.
However still the direct attr take effect. Any idea?

答:
It works here - you just had some space in your image src address: (and the closing body  and html tags were missing).

img {
  width: 100% !important;
  height: 100% !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="ISO-8859-1">
  <title>Insert title here</title>

</head>

<body>

  <div style="width: 200px; height: 300px;background-color: yellow;">

    <img src="https://s3.amazonaws.com/telegraph_journal/story-pictures/100141831/leadlandscape/20170303_083808_1.jpg" width="20" height="8" />

  </div>
</body>

</html></code>```

Body:
I am working on a big project to improve it as like any other existing project I have some limitation which I need to find a workaround for it though that might not be the best option. I have some texts in the database and some of them contains image tags such as

Now the problem is that these images have width and  height attributes which I do not need them at all and I need to use my own styling. I know there are different ways to fix such as cleaning the db text or parse the text and clean it before wrapping it to html but these are not doable for me right now based on some limitation I have. So I need to do this in a css:

just to give you a simple version of what I want here is a simple code:

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

As you see I even added style to img with !important to overwrite the styles.
However still the direct attr take effect. Any idea?

Body:
It works here - you just had some space in your image src address: (and the closing body  and html tags were missing).

img {
  width: 100% !important;
  height: 100% !important;
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="ISO-8859-1">
  <title>Insert title here</title>

</head>

<body>

  <div style="width: 200px; height: 300px;background-color: yellow;">

    <img src="https://s3.amazonaws.com/telegraph_journal/story-pictures/100141831/leadlandscape/20170303_083808_1.jpg" width="20" height="8" />

  </div>
</body>

</html>


问:
Get groups from Active Directory using C#
I am having issues getting the groups from Active Directory via System.DirectoryServices

Originally I started my application on a computer that was registered on the domain, but as it was a live domain I did not want to do any writes to AD what so ever, so I set up a machine with Windows XP as the host operating system, and installed windows server 2003 on a VM.

I've added another Ethernet port in the machine and set up a switch, the 1 Ethernet port is dedicated to the VM and the other port is used for the host.

After configuring the IP addresses to get them communicating I transferred my application onto the host machine and fired it up, but I was getting an DirectoryServicesCOMException.

With the message that the user name and password was invalid :( just to check that it was not active directory I created a 3rd virtual machine and installed Windows XP, which i added to the domain with the credentials tested in the APP, works a treat.

So I thought it must be because the machine where the application is running is not part of the domain.

Heres the block of code that was causing the issue:

```<code>public CredentialValidation(String Domain, String Username, String Password, Boolean Secure)
{
     //Validate the Domain!
     try
     {
         PrincipalContext Context = new PrincipalContext(ContextType.Domain, Domain); //Throws Exception
         _IsValidDomain = true;

         //Test the user login
         _IsValidLogin = Context.ValidateCredentials(Username, Password);

         //Check the Group Admin is within this user
         //******HERE
         var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);

         foreach(Principal Result in Results)
         {
             if (Result.SamAccountName == "Domain Admins")
             {
                 _IsAdminGroup = true;
                 break;
             }
         }
         Results.Dispose();
         Context.Dispose();
     }
     catch (PrincipalServerDownException)
     {
         _IsValidDomain = false;
     }
 }
</code>```

The information in the login dialogue is being entered like so:

```<code>Domain: test.internal
Username: testaccount
Password: Password01
</code>```

Hope someone can shed some light in this error.

Update:

After checking the Security Logs on the server i can see that my log in attempts was successful, but this is down to:

```<code>_IsValidLogin = Context.ValidateCredentials(Username, Password);
</code>```

The line after where im checking the groups is causing the error, so the main issue is that the lines of code below are not working correctly from a machine thats not joined to the network:

```<code>var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);
</code>```

答:
According to your code snippet, you're failing when you attempt to create the PrincipalContext, before calling ValidateCredentials. At that point the thread running your code is still working under either a local identity (if you're in a web process) or the identity you signed onto your machine with (for a windows process). Either of these won't exist on the test.internal domain.

You might want to try the overload of PrincipalContext that includes the username and password in the constructor. See http://msdn.microsoft.com/en-us/library/bb341016.aspx

Body:
I am having issues getting the groups from Active Directory via System.DirectoryServices

Originally I started my application on a computer that was registered on the domain, but as it was a live domain I did not want to do any writes to AD what so ever, so I set up a machine with Windows XP as the host operating system, and installed windows server 2003 on a VM.

I've added another Ethernet port in the machine and set up a switch, the 1 Ethernet port is dedicated to the VM and the other port is used for the host.

After configuring the IP addresses to get them communicating I transferred my application onto the host machine and fired it up, but I was getting an DirectoryServicesCOMException.

With the message that the user name and password was invalid :( just to check that it was not active directory I created a 3rd virtual machine and installed Windows XP, which i added to the domain with the credentials tested in the APP, works a treat.

So I thought it must be because the machine where the application is running is not part of the domain.

Heres the block of code that was causing the issue:

public CredentialValidation(String Domain, String Username, String Password, Boolean Secure)
{
     //Validate the Domain!
     try
     {
         PrincipalContext Context = new PrincipalContext(ContextType.Domain, Domain); //Throws Exception
         _IsValidDomain = true;

         //Test the user login
         _IsValidLogin = Context.ValidateCredentials(Username, Password);

         //Check the Group Admin is within this user
         //******HERE
         var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);

         foreach(Principal Result in Results)
         {
             if (Result.SamAccountName == "Domain Admins")
             {
                 _IsAdminGroup = true;
                 break;
             }
         }
         Results.Dispose();
         Context.Dispose();
     }
     catch (PrincipalServerDownException)
     {
         _IsValidDomain = false;
     }
 }

The information in the login dialogue is being entered like so:

Domain: test.internal
Username: testaccount
Password: Password01

Hope someone can shed some light in this error.

Update:

After checking the Security Logs on the server i can see that my log in attempts was successful, but this is down to:

_IsValidLogin = Context.ValidateCredentials(Username, Password);

The line after where im checking the groups is causing the error, so the main issue is that the lines of code below are not working correctly from a machine thats not joined to the network:

var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);


问:
Is there any way I can change only a specific directory color in linux?
I only need to set a color that will only effect a particular directory not globally.  </p>

答:
If you are using Bash in a terminal that supports colors and would like to change the default color for text output to the terminal (not specifically the output of ls) while inside this directory, there is one thing you could do.

The PROMPT_COMMAND variable can be set to execute a command just before printing the prompt.  You could use that to check for the current directory and change the terminal color (for instance by assigning the PS1 variable with a prompt that contains non-displayable special codes for selecting a color or echoing said special codes).

PROMPT_COMMAND is documented in the Bash manual: https://www.gnu.org/software/bash/manual/bashref.html

As for how to assign colors, you should look that up if interested.

This solution may not be what you are looking for, will probably have side effects, and generally speaking, I am not sure it will be that useful changing terminal colors depending on the current directory.  The usual solution is to have a prompt that shows the current directory path (or at least the last portion of the path).

I use something similar to the above to change text color depending on which machine I am executing Bash on, as I use ssh a lot from one machine to another over several terminal windows, and color (on a black background) is a good way to remember what machine any given window is connected to.


问:
Undefined variable during mysql to mysqli conversion
I am in the process of converting my old PHP from mysql to mysqli and am running into this error during my conversion. The code worked without throwing errors under mysql but for some reason I get the 'Undefined variable: prevcat in /xx/xx/xx/xx/xx/xx/vluchtbijtoestel.php on line 102' error now. I've tried adding $prevcat = $cat to the variables list but that then breaks the code.

My code:

```<code><?php
define('DB_SERVER', "xxx");
define('DB_USER', "xxx");
define('DB_PASSWORD', "xxx");
define('DB_TABLE', "xxx");

// Define your colors for the alternating rows
$color1 = "#F0F8FF";
$color2 = "#FFFFFF";
$row_count = 0;

// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
    trigger_error('Database connection failed: '  . mysqli_connect_error(), E_USER_ERROR);
}

$query = "
    SELECT vg.gegevenID, lvm.luchtvaartmaatschappij, lvm.sm_logo, vg.vertrekdatum2, vg.vertrekluchthaven, vg.aankomstluchthaven, vg.toestel, vg.inschrijvingnmr, vlg.vliegtuignaam, vg.vluchtnmr, t.toestel AS toestelnaam, lh.luchthavencode, lh.luchthavennaam, lh.countryflag, lh2.luchthavencode AS aankomstluchthavencode, lh2.countryflag AS countryflagaankomst, vlg.erlr, vlg.firstflight, DATEDIFF(vlg.firstflight,vg.vertrekdatum2) Age1, lh2.luchthavennaam AS aankomstnaam, CONCAT(t.toestel,' ', vlg.erlr) as toestelmeterlr

    FROM (tbl_vliegtuiggegevens vlg

    INNER JOIN (tbl_luchtvaartmaatschappij lvm INNER JOIN tbl_vluchtgegevens vg ON lvm.luchtvaartmaatschappijID = vg.luchtvaartmaatschappij) ON (vlg.inschrijvingnmr = vg.inschrijvingnmr) AND (vlg.lvmID = lvm.luchtvaartmaatschappijID)) INNER JOIN tbl_toestel t ON vg.toestel = t.toestelID

    LEFT JOIN tbl_luchthaven lh
    ON vg.vertrekluchthaven = lh.luchthavenID

    LEFT JOIN tbl_luchthaven lh2
    ON vg.aankomstluchthaven = lh2.luchthavenID

    GROUP BY  lvm.luchtvaartmaatschappij, toestelmeterlr, vg.inschrijvingnmr, vg.vertrekdatum2

    ORDER BY lvm.luchtvaartmaatschappij, toestelmeterlr, vg.vertrekdatum2 DESC, vg.inschrijvingnmr; ";

$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

echo "
<table width='100%' border='0'>
  <tr>
    <td colspan='3'><strong>Luchtvaartmaatschappij</strong></td>
    <td width='17%'> </td>
    <td width='12%'> </td>
    <td width='19%'> </td>
    <td width='28%'> </td>
  </tr>
  <tr>
    <td width='2%'> </td>
    <td colspan='3'><strong>Toestel</strong></td>
    <td> </td>
    <td> </td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td width='3%'> </td>
    <td width='19%'><strong>vertrekdatum</strong></td>
    <td><strong>vliegroute</strong></td>
    <td><strong>registratie</strong></td>
    <td><strong>vliegtuignaam</strong></td>
    <td><strong>vliegtuig leeftijd op reisdatum</strong></td>
  </tr>
</table>
";

if($result) {
    while($row = mysqli_fetch_assoc($result)) {

    $row_color = ($row_count % 2) ? $color1 : $color2;
    $date1 = date_create($row['firstflight']);
    $date2 = date_create($row['vertrekdatum2']);
    $interval = date_diff($date1, $date2);
    $cat = $row['luchtvaartmaatschappij'];
    $subcat = $row['toestelmeterlr'];
    $item = $row['inschrijvingnmr'];

    if($cat != $prevcat){

echo "  <table width='100%' border='0'>";
echo "  <tr>";
echo "    <td><br /><hr></td>";
echo "  </tr>";
echo "  <tr>";
echo "    <td><strong><span class='style4'><img src='http://globe-trekking.com/vg/img/logos/sm/".$row['sm_logo']."'>     " .$cat. "</strong></span>         <br /></td>";
echo "  </tr>";
echo "</table>";
        echo '<span style="color: #0A0094; font-size: 16px;">      '. $subcat.'</span><br />';//if the category has changed, we also want to show the new subcat
    }elseif($subcat != $prevsubcat){
        echo '<br /><span style="color: #0A0094; font-size: 16px;">      ' .$subcat.'</span><br />';
    }
echo "  <table width='1093' border='0' cellspacing='0'>";
echo "  <tr>";
echo "    <td width='75'> </td>";
echo "    <td width='200' bgcolor='$row_color'>" .date("d-M-Y H:i", strtotime($row['vertrekdatum2']))."</td>";
echo "    <td width='70' bgcolor='$row_color'><img src='http://globe-trekking.com/vg/img/flags/".$row['countryflag']."'>   <abbr title=\"".htmlspecialchars($row['luchthavennaam'])."\">".$row['luchthavencode']."</abbr></td>";
echo "    <td width='70' bgcolor='$row_color'>   naar   </td>";
echo "    <td width='130' bgcolor='$row_color'><img src='http://globe-trekking.com/vg/img/flags/".$row['countryflagaankomst']."'>   <abbr title=\"".htmlspecialchars($row['aankomstnaam'])."\">".$row['aankomstluchthavencode']."</abbr></td>";
echo "    <td width='150' bgcolor='$row_color'>".$row['inschrijvingnmr']."</td>";
echo "    <td width='250' bgcolor='$row_color'>".$row['vliegtuignaam'] ."</td>";
echo "    <td width='250' bgcolor='$row_color'>" . $interval->y . " jaar en " . $interval->m." maanden </td>";
echo "  </tr>";
echo "</table>";
    $prevcat = $cat;
    $prevsubcat = $subcat;
      // Add 1 to the row count
$row_count++;
}
}
mysqli_close($mysqli);

?>
</code>```

答:
Put

$prevcat = '';
  $prevsubcat = '';

Juste before "While" expression

Regards

Body:
I am in the process of converting my old PHP from mysql to mysqli and am running into this error during my conversion. The code worked without throwing errors under mysql but for some reason I get the 'Undefined variable: prevcat in /xx/xx/xx/xx/xx/xx/vluchtbijtoestel.php on line 102' error now. I've tried adding $prevcat = $cat to the variables list but that then breaks the code.

My code:

<?php
define('DB_SERVER', "xxx");
define('DB_USER', "xxx");
define('DB_PASSWORD', "xxx");
define('DB_TABLE', "xxx");

// Define your colors for the alternating rows
$color1 = "#F0F8FF";
$color2 = "#FFFFFF";
$row_count = 0;

// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
    trigger_error('Database connection failed: '  . mysqli_connect_error(), E_USER_ERROR);
}

$query = "
    SELECT vg.gegevenID, lvm.luchtvaartmaatschappij, lvm.sm_logo, vg.vertrekdatum2, vg.vertrekluchthaven, vg.aankomstluchthaven, vg.toestel, vg.inschrijvingnmr, vlg.vliegtuignaam, vg.vluchtnmr, t.toestel AS toestelnaam, lh.luchthavencode, lh.luchthavennaam, lh.countryflag, lh2.luchthavencode AS aankomstluchthavencode, lh2.countryflag AS countryflagaankomst, vlg.erlr, vlg.firstflight, DATEDIFF(vlg.firstflight,vg.vertrekdatum2) Age1, lh2.luchthavennaam AS aankomstnaam, CONCAT(t.toestel,' ', vlg.erlr) as toestelmeterlr

    FROM (tbl_vliegtuiggegevens vlg

    INNER JOIN (tbl_luchtvaartmaatschappij lvm INNER JOIN tbl_vluchtgegevens vg ON lvm.luchtvaartmaatschappijID = vg.luchtvaartmaatschappij) ON (vlg.inschrijvingnmr = vg.inschrijvingnmr) AND (vlg.lvmID = lvm.luchtvaartmaatschappijID)) INNER JOIN tbl_toestel t ON vg.toestel = t.toestelID

    LEFT JOIN tbl_luchthaven lh
    ON vg.vertrekluchthaven = lh.luchthavenID

    LEFT JOIN tbl_luchthaven lh2
    ON vg.aankomstluchthaven = lh2.luchthavenID

    GROUP BY  lvm.luchtvaartmaatschappij, toestelmeterlr, vg.inschrijvingnmr, vg.vertrekdatum2

    ORDER BY lvm.luchtvaartmaatschappij, toestelmeterlr, vg.vertrekdatum2 DESC, vg.inschrijvingnmr; ";

$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);

echo "

    Luchtvaartmaatschappij

    Toestel

    vertrekdatum
    vliegroute
    registratie
    vliegtuignaam
    vliegtuig leeftijd op reisdatum

";

if($result) {
    while($row = mysqli_fetch_assoc($result)) {

    $row_color = ($row_count % 2) ? $color1 : $color2;
    $date1 = date_create($row['firstflight']);
    $date2 = date_create($row['vertrekdatum2']);
    $interval = date_diff($date1, $date2);
    $cat = $row['luchtvaartmaatschappij'];
    $subcat = $row['toestelmeterlr'];
    $item = $row['inschrijvingnmr'];

    if($cat != $prevcat){

echo "
";
echo "
";
echo "

	";
echo "
";
echo "
";
echo "         " .$cat. "
	";
echo "
";
echo "
";
        echo '      '. $subcat.'
';//if the category has changed, we also want to show the new subcat
    }elseif($subcat != $prevsubcat){
        echo '
      ' .$subcat.'
';
    }
echo "
";
echo "
";
echo "     	";
echo "    " .date("d-M-Y H:i", strtotime($row['vertrekdatum2']))."	";
echo "       ".$row['luchthavencode']."	";
echo "       naar   	";
echo "       ".$row['aankomstluchthavencode']."	";
echo "    ".$row['inschrijvingnmr']."	";
echo "    ".$row['vliegtuignaam'] ."	";
echo "    " . $interval->y . " jaar en " . $interval->m." maanden 	";
echo "
";
echo "
";
    $prevcat = $cat;
    $prevsubcat = $subcat;
      // Add 1 to the row count
$row_count++;
}
}
mysqli_close($mysqli);

?>


问:
OpenLayers: How to re-align mouse coordinates and vector layers after fluid css rendering of map div
My OpenLayers application includes several vector layers that interact with mouse movements.  Everything was working as expected until I made one change to my css file.  In my html, I defined a div:

```<code><div id="main_map" class="map"></div>
</code>```

My original/working css file includes:

```<code>#main_map {
 position: absolute;
 left: 200px;
 top: 0px;
 height: 600px;
 width: 1000px;
}
</code>```

To give the map div a fluid width, I changed the css file to:

```<code>#main_map {
 position: absolute;
 left: 200px;
 top: 0px;
 height: 600px;
 width: calc(100% - 487px);
}
</code>```

Now when the map displays, there is some misalignment between the vector layers and the mouse coordinates, so my mouse-hover functions do not work correctly.  If I change the size of the browser window just slightly, a redraw or refresh of the map div is invoked which makes this misalignment problem disappear.  I visibly notice a slight shifting of vector elements on the map upon slightly resizing the browser window.

The following are my OpenLayer code snippets they may be relevant to this problem...first establish a map:

```<code>  var map = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    target: 'main_map',
    controls: ol.control.defaults({
      attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
        collapsible: true
      })
    })
  });
</code>```

Next, I construct several vector layers (details not shown here) and group a few of them as:

```<code>  var vector_layer_all = new ol.layer.Group({ layers: [vector_layer,vector_layer2] });
</code>```

Next, I set my zoom extent based on selected vector layer content:

```<code>  var extent = ol.extent.createEmpty();
  vector_layer_all.getLayers().forEach(function(layer) {
    ol.extent.extend(extent, layer.getSource().getExtent());
  });
  map.getView().fit(extent, map.getSize());
</code>```

Finally, I display some text data in a text box div named map_location_info based on the position of the mouse over some vector layers on the map:

```<code>  var displayFeatureInfo = function(pixel) {
    var features = [];
    map.forEachFeatureAtPixel(pixel, function(feature,layer) {
      features.push(feature);
    }, null, function(layer) {
      return (layer === vector_layer | layer === vector_layer2 | layer === vector_layer3);
    });
    if (features.length > 0) {
      var info = [];
      var i, ii;
      for (i = 0, ii = features.length; i < ii; ++i) {
        info.push(features[i].get('Name'));
        info.push(features[i].get('Status'));
      }
      document.getElementById('map_location_info').innerHTML = info.join(', ') || '(unknown)';
    } else {
      document.getElementById('map_location_info').innerHTML = ' ';
    }
  };
  map.on('pointermove', function(evt) {
    if (evt.dragging) {
      return;
    }
    var pixel = map.getEventPixel(evt.originalEvent);
    displayFeatureInfo(pixel);
  });
</code>```

Somehow I need to force a redraw or refresh to some OpenLayers component just after the initial rendering of the map and vector layers.  At what point in the code/process should I redraw/refresh and which OpenLayers component should this refresh/redraw be applied to?  Any suggestions would be appreciated.

Edit: In thinking about this further...the OpenLayers script is positioned inside the hmtl content section of a JQuery tab. The problem might be coming from the way JQuery renders its tab content.

答: I was able to resolve the issue by moving the OpenLayers script block from inside a JQueryUI tab content space to the $(document).ready(function() { }); script block at the bottom of my html template (and below a bunch of script using the DataTables library within that script block).  So, all that remains in the JQueryUI tab content spaces are divs with no inline scripts.  I did not attempt to trace out the css propagation so I really don't know exactly what was causing my problem.  With several high level js libraries (JQuery, JQueryUI, DataTables, OpenLayers - which includes Google Closure and more) playing together in the same space I need to be careful about the order in which things are getting done.  So, my problem was not an OpenLayers problem, but rather a code organization and ordering problem.  This problem/solution reminds me of some good advice I didn't take from my earlier days of learning javascript.

Body:
My OpenLayers application includes several vector layers that interact with mouse movements.  Everything was working as expected until I made one change to my css file.  In my html, I defined a div:

My original/working css file includes:

#main_map {
 position: absolute;
 left: 200px;
 top: 0px;
 height: 600px;
 width: 1000px;
}

To give the map div a fluid width, I changed the css file to:

#main_map {
 position: absolute;
 left: 200px;
 top: 0px;
 height: 600px;
 width: calc(100% - 487px);
}

Now when the map displays, there is some misalignment between the vector layers and the mouse coordinates, so my mouse-hover functions do not work correctly.  If I change the size of the browser window just slightly, a redraw or refresh of the map div is invoked which makes this misalignment problem disappear.  I visibly notice a slight shifting of vector elements on the map upon slightly resizing the browser window.

The following are my OpenLayer code snippets they may be relevant to this problem...first establish a map:

  var map = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    target: 'main_map',
    controls: ol.control.defaults({
      attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
        collapsible: true
      })
    })
  });

Next, I construct several vector layers (details not shown here) and group a few of them as:

  var vector_layer_all = new ol.layer.Group({ layers: [vector_layer,vector_layer2] });

Next, I set my zoom extent based on selected vector layer content:

  var extent = ol.extent.createEmpty();
  vector_layer_all.getLayers().forEach(function(layer) {
    ol.extent.extend(extent, layer.getSource().getExtent());
  });
  map.getView().fit(extent, map.getSize());

Finally, I display some text data in a text box div named map_location_info based on the position of the mouse over some vector layers on the map:

  var displayFeatureInfo = function(pixel) {
    var features = [];
    map.forEachFeatureAtPixel(pixel, function(feature,layer) {
      features.push(feature);
    }, null, function(layer) {
      return (layer === vector_layer | layer === vector_layer2 | layer === vector_layer3);
    });
    if (features.length > 0) {
      var info = [];
      var i, ii;
      for (i = 0, ii = features.length; i < ii; ++i) {
        info.push(features[i].get('Name'));
        info.push(features[i].get('Status'));
      }
      document.getElementById('map_location_info').innerHTML = info.join(', ') || '(unknown)';
    } else {
      document.getElementById('map_location_info').innerHTML = ' ';
    }
  };
  map.on('pointermove', function(evt) {
    if (evt.dragging) {
      return;
    }
    var pixel = map.getEventPixel(evt.originalEvent);
    displayFeatureInfo(pixel);
  });

Somehow I need to force a redraw or refresh to some OpenLayers component just after the initial rendering of the map and vector layers.  At what point in the code/process should I redraw/refresh and which OpenLayers component should this refresh/redraw be applied to?  Any suggestions would be appreciated.

Edit: In thinking about this further...the OpenLayers script is positioned inside the hmtl content section of a JQuery tab. The problem might be coming from the way JQuery renders its tab content.


问:
DOS batch: force echo of single statement?
In my DOS batch file, I use the "@" symbol to suppress the echo of that statement before execution when echo is ON.

How should I force the echo of a statement when echo is OFF (I'm hoping for another single character, but all answers welcome)?

答: It seems to me that there is no way to do it. You can wrap commands you need to be echoed between echo on and @echo off but this is ugly, I think. Another option is to keep echo on and use @ for every command you don't want to echo and keeping echo-ables without @.


问:
Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?
I have a batch file that executes three Maven commands, one after the other. Each command can be successfully executed in the script - by itself!. But when I add all three commands to the same file, only the first one executes before the script exits. Any idea why?

```<code>mvn install:install-file -DgroupId=gdata -DartifactId=base -Dversion=1.0 -Dfile=gdata-base-1.0.jar  -Dpackaging=jar -DgeneratePom=true
mvn install:install-file -DgroupId=gdata -DartifactId=blogger -Dversion=2.0 -Dfile=gdata-blogger-2.0.jar  -Dpackaging=jar -DgeneratePom=true
mvn install:install-file -DgroupId=gdata -DartifactId=blogger-meta -Dversion=2.0 -Dfile=gdata-blogger-meta-2.0.jar  -Dpackaging=jar -DgeneratePom=true
</code>```

Also, if I copy all three commands and paste them into a command shell (cmd.exe), they execute one after the other with no problem. So this is apparently some issue with the dos batch file.

答:
Having call helps. However today it didn't.

This is how I solved it:

Bat file contents (if you want to stop batch when one of cmds errors)

```<code>cmd1 && ^
cmd2 && ^
cmd3 && ^
cmd4
</code>```

Bat file contents (if you want to continue batch when one of cmds errors)

```<code>cmd1 & ^
cmd2 & ^
cmd3 & ^
cmd4
</code>```

Body:
I have a batch file that executes three Maven commands, one after the other. Each command can be successfully executed in the script - by itself!. But when I add all three commands to the same file, only the first one executes before the script exits. Any idea why?

mvn install:install-file -DgroupId=gdata -DartifactId=base -Dversion=1.0 -Dfile=gdata-base-1.0.jar  -Dpackaging=jar -DgeneratePom=true
mvn install:install-file -DgroupId=gdata -DartifactId=blogger -Dversion=2.0 -Dfile=gdata-blogger-2.0.jar  -Dpackaging=jar -DgeneratePom=true
mvn install:install-file -DgroupId=gdata -DartifactId=blogger-meta -Dversion=2.0 -Dfile=gdata-blogger-meta-2.0.jar  -Dpackaging=jar -DgeneratePom=true

Also, if I copy all three commands and paste them into a command shell (cmd.exe), they execute one after the other with no problem. So this is apparently some issue with the dos batch file.

Body:
Having call helps. However today it didn't.

This is how I solved it:

Bat file contents (if you want to stop batch when one of cmds errors)

cmd1 && ^
cmd2 && ^
cmd3 && ^
cmd4

Bat file contents (if you want to continue batch when one of cmds errors)

cmd1 & ^
cmd2 & ^
cmd3 & ^
cmd4