问:
Problems with session ids on parallel threads
So I am trying to use multiprocessing to iterate concurrently through files in separate folders. I have a function that calls the parallel process:

```<code>from multiprocessing.dummy import Pool

lsFolders = ['Folder1', 'Folder2']

pool = Pool( processes = 6 )

iterateThroughFiles = IterateThroughFiles() # instantiated by call to pool.map()

pool.map( iterateThroughFiles.runProcess, lsFolders )
</code>```

Then I have the implementation of the IterateThroughFiles-class:

```<code>class IterateThroughFiles( object ):

  def runProcess( self, folder ):
      self.sessionId = uuid.uuid4()
      print( self.sessionId )             # Prints a correct sessionId
      logAtLevel( "INFO", "Session ID of: "
                         + str( self.sessionId )
                         + " has been generated for folder: "
                         + folder
                           )

      print( self.sessionId )             # Prints only the second generated
      #                                   # session id for both threads
      print( folder )                     # Prints the correct folder
</code>```

When I generate the sessionId and print it directly after, the sessionId is correct, additionally the logAtLevel() wrapper function logs the correct value of the sessionId.

The next print statement, though, prints only the second session id and apparently the first sessionId is forgotten in the thread.

Does anyone know why this is happening? I thought when running in parallel each thread was distinct in terms of the objects it created and its memory? Is this incorrect? Does this have something to with the uuid generator?

答:
pool.map(iterateThroughFiles.runProcess, lsFolders)

In this line you are calling runProcess many times on a single instance of the class IterateThroughFiles. If you are thinking of each instance as a session, you need to instantiate a new object for each folder in lsFolders.

```<code>from multiprocessing.dummy import Pool

lsFolders = ['Folder1', 'Folder2']

pool = Pool(processes=6)

def worker(folder):
    p = IterateThroughFiles()
    p.runProcess(folder)

pool.map(worker, lsFolders)
</code>```

This way, the worker function creates a NEW instance of IterateThroughFiles for each folder, and that way in the runProcess function, self refers to that individual instance, rather than re-using the same instance for each folder.

Body:
So I am trying to use multiprocessing to iterate concurrently through files in separate folders. I have a function that calls the parallel process:

from multiprocessing.dummy import Pool

lsFolders = ['Folder1', 'Folder2']

pool = Pool( processes = 6 )

iterateThroughFiles = IterateThroughFiles() # instantiated by call to pool.map()

pool.map( iterateThroughFiles.runProcess, lsFolders )

Then I have the implementation of the IterateThroughFiles-class:

class IterateThroughFiles( object ):

  def runProcess( self, folder ):
      self.sessionId = uuid.uuid4()
      print( self.sessionId )             # Prints a correct sessionId
      logAtLevel( "INFO", "Session ID of: "
                         + str( self.sessionId )
                         + " has been generated for folder: "
                         + folder
                           )

      print( self.sessionId )             # Prints only the second generated
      #                                   # session id for both threads
      print( folder )                     # Prints the correct folder

When I generate the sessionId and print it directly after, the sessionId is correct, additionally the logAtLevel() wrapper function logs the correct value of the sessionId.

The next print statement, though, prints only the second session id and apparently the first sessionId is forgotten in the thread.

Does anyone know why this is happening? I thought when running in parallel each thread was distinct in terms of the objects it created and its memory? Is this incorrect? Does this have something to with the uuid generator?

Body:
pool.map(iterateThroughFiles.runProcess, lsFolders)

In this line you are calling runProcess many times on a single instance of the class IterateThroughFiles. If you are thinking of each instance as a session, you need to instantiate a new object for each folder in lsFolders.

from multiprocessing.dummy import Pool

lsFolders = ['Folder1', 'Folder2']

pool = Pool(processes=6)

def worker(folder):
    p = IterateThroughFiles()
    p.runProcess(folder)

pool.map(worker, lsFolders)

This way, the worker function creates a NEW instance of IterateThroughFiles for each folder, and that way in the runProcess function, self refers to that individual instance, rather than re-using the same instance for each folder.


来源: stackexchange

问:
starting with react example, in constructors this.method = this.method.bind(this) , why?
I'm starting with react and the first thing I did is to go to the main page where I see some examples, e.g.:

```<code>class MarkdownEditor extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = { value: 'Type some *markdown* here!' };
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  getRawMarkup() {
    const md = new Remarkable();
    return { __html: md.render(this.state.value) };
  }

  render() {
    return (
      <div className="MarkdownEditor">
        <h3>Input</h3>
        <textarea
          onChange={this.handleChange}
          defaultValue={this.state.value}
        />
        <h3>Output</h3>
        <div
          className="content"
          dangerouslySetInnerHTML={this.getRawMarkup()}
        />
      </div>
    );
  }
}

ReactDOM.render(<MarkdownEditor />, mountNode);
</code>```

...
I see that in the constructor is done:

```<code>this.handleChange = this.handleChange.bind(this);
</code>```

What is the reason behind that? Talking with colleagues they think some possible reasons like something special behind the render() method, or something related with non supported feature of ES6.

Do someone have a specific explainment to that?

In a first look, it seems unnecessary for me as shown in this simple example:

```<code>class A {
  constructor(){
      this.a = 1;
  }
  do(){
      console.log('A', this.a);
 }
}

class B extends A {
  constructor(){
    super();
    this.a = 2;
  }

 do(){
      console.log('B', this.a);
  }
}
console.log ((new B()).do())
</code>```

答:
This code on JSX onChange={this.handleChange} is equivalent to dom.addEventListener('click', this.handleChange).

The class function this.handleChange is equivalent to A.prototype.handleChange. Which means that the prototype of A is not a instance of A.

So you need to bind this to handleChange within the scope of the instance of A.

this is depends on receiver's scope by default. See this example:

```<code>class A {
  f() {
    console.log(this);
  }
  getF() {
    return this.f;
  }
}

const a = new A();
a.f(); // A{}

const f = a.getF();
f(); // undefined
</code>```

In React, lifecycle events, like componentWillMount, are called as function of the specific instance instance.componentWillMount().

ContentLicense: CC BY-SA 3.0

Body:
I'm starting with react and the first thing I did is to go to the main page where I see some examples, e.g.:

class MarkdownEditor extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = { value: 'Type some *markdown* here!' };
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  getRawMarkup() {
    const md = new Remarkable();
    return { __html: md.render(this.state.value) };
  }

  render() {
    return (

Input

        <textarea
          onChange={this.handleChange}
          defaultValue={this.state.value}
        />

Output

    );
  }
}

ReactDOM.render(<MarkdownEditor />, mountNode);

...
I see that in the constructor is done:

this.handleChange = this.handleChange.bind(this);

What is the reason behind that? Talking with colleagues they think some possible reasons like something special behind the render() method, or something related with non supported feature of ES6.

Do someone have a specific explainment to that?

In a first look, it seems unnecessary for me as shown in this simple example:

class A {
  constructor(){
      this.a = 1;
  }
  do(){
      console.log('A', this.a);
 }
}

class B extends A {
  constructor(){
    super();
    this.a = 2;
  }

 do(){
      console.log('B', this.a);
  }
}
console.log ((new B()).do())

Body:
This code on JSX onChange={this.handleChange} is equivalent to dom.addEventListener('click', this.handleChange).

The class function this.handleChange is equivalent to A.prototype.handleChange. Which means that the prototype of A is not a instance of A.

So you need to bind this to handleChange within the scope of the instance of A.

this is depends on receiver's scope by default. See this example:

class A {
  f() {
    console.log(this);
  }
  getF() {
    return this.f;
  }
}

const a = new A();
a.f(); // A{}

const f = a.getF();
f(); // undefined

In React, lifecycle events, like componentWillMount, are called as function of the specific instance instance.componentWillMount().


问:
UActorComponent derived class in plugin is not reacting for function calls
So I have a little problem with creating project plugin in Unreal Engine for (4.15). So let's break it down.
1.I've created MyClass that is derived from UActor Component and has also this line:

```<code>UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
</code>```

2.I've added that component to my GameMode.
3.Then I'm trying to call any function from inside the class by Get GameMode then casting to MyGameMode and getting MyClassComponent.
4.When I'm trying to call function nothing happens at all.

I was trying to debug it but it never goes in function body but prints before function and after works perfectly fine. I also must say that when functions are compiled straight into project they work 100% fine!

This is sample of how do I declare my functions:

```<code>UFUNCTION(BlueprintCallable, Category = "MyClass|Test")
        void TestFunction();

void UMyClass::TestFunction()
{
    GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, "hello there");
}
</code>```

If there is any more information required that I'm not aware of please let me know.

MyClass declaration

```<code>UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class UMyClass : public UActorComponent
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "MyClass|Test")
void TestFunction();
};
</code>```

答:
Any classes that need to be consumed publicly need to have their symbols exported.

In UE plugins this is achieved with the YOURPLUGIN_API specifier, where YOURPLUGIN is the name of the plugin.

This in turn is defined as __declspec(dllexport) when exporting and __declspec(dllimport) when consuming the plugin.

So your class definition should look like:

```<code>UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class MYPLUGIN_API UMyClass : public UActorComponent
{
    ...
}
</code>```

Body:
So I have a little problem with creating project plugin in Unreal Engine for (4.15). So let's break it down.
1.I've created MyClass that is derived from UActor Component and has also this line:

UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))

2.I've added that component to my GameMode.
3.Then I'm trying to call any function from inside the class by Get GameMode then casting to MyGameMode and getting MyClassComponent.
4.When I'm trying to call function nothing happens at all.

I was trying to debug it but it never goes in function body but prints before function and after works perfectly fine. I also must say that when functions are compiled straight into project they work 100% fine!

This is sample of how do I declare my functions:

UFUNCTION(BlueprintCallable, Category = "MyClass|Test")
        void TestFunction();

void UMyClass::TestFunction()
{
    GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, "hello there");
}

If there is any more information required that I'm not aware of please let me know.

MyClass declaration

UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class UMyClass : public UActorComponent
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "MyClass|Test")
void TestFunction();
};

Body:
Any classes that need to be consumed publicly need to have their symbols exported.

In UE plugins this is achieved with the YOURPLUGIN_API specifier, where YOURPLUGIN is the name of the plugin.

This in turn is defined as __declspec(dllexport) when exporting and __declspec(dllimport) when consuming the plugin.

So your class definition should look like:

UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class MYPLUGIN_API UMyClass : public UActorComponent
{
    ...
}


问:
How to implement sift algorithm in 3 dimension using opencv and c++?
I am confused about how to implement sift algorithm in 3-dimension using opencv and c++. I understand the 3D sift algorithm principle from some papers but I don't have a clear mind on implementation. There are some open source code which is written in matlab, I want to implement the algorithm using c++ and opencv but have no idea on delcaring the data structure.

3D sift algorithm can be simply described as following steps:

(1) Build the scale space and generate the DOG(Difference of Gaussian).

(2) Detect the extrema and filter some inappropriate keypoints.

(3) Assign the keypoints orientation in 3D.

(4) Generate the keypoint descriptor in 3D.

Assume that the 3D input data is ready and can be stored in a 3D array(e.g. double*** data).

My first try is to declare the 3D matrix(3D Volume) by the following (the data in 3D array can be copied to the Mat):

```<code>int sizes[] = {x ,y, z};
Mat *Img = new Mat(3, sizes, CV_8U, Scalar(0));// using namespace cv
</code>```

Then I encounter some problems in step1 of the algorithm:

(1) Is there a way to declare a 3D volume using something like typedef, since the scale space contains different sizes of the 3D volume. The size array should not be constant.

(2) I cannot find ways to resize the 3D volume or do the Gaussian filter for 3D volume. Is it a reasonable approach to decompose the 3D volume into 2D slices and do the resize or Gaussian filter on each slices? Or is there any function can be directly applied on 3D volume?

Constructing the appropriate data structure should be the key of the algorithm and I don't have a clear mind on how to use opencv.

Thanks for help!

答:
(1) Is there a way to declare a 3D volume using something like typedef, since the scale space contains different sizes of the 3D volume. The size array should not be constant.

No, OpenCV is primarily aimed at 2D Images (think standard image formats such as .png, video feeds etc)

(2) I cannot find ways to resize the 3D volume or do the Gaussian filter for 3D volume. Is it a reasonable approach to decompose the 3D volume into 2D slices and do the resize or Gaussian filter on each slices? Or is there any function can be directly applied on 3D volume?

The only thing you can really do with OpenCV is have a stack of 2D sizes, all of a different size if you wanted. If you have a vector or sometype with a set of Mats then you could alter those mats to fit your purpose (you could even change the size of particular mats)

That being said it really sounds like what you are trying to do is probably out of the scope of OpenCV. For reference you can see OpenCVs implementation of SIFT here

Body:
I am confused about how to implement sift algorithm in 3-dimension using opencv and c++. I understand the 3D sift algorithm principle from some papers but I don't have a clear mind on implementation. There are some open source code which is written in matlab, I want to implement the algorithm using c++ and opencv but have no idea on delcaring the data structure.

3D sift algorithm can be simply described as following steps:

(1) Build the scale space and generate the DOG(Difference of Gaussian).

(2) Detect the extrema and filter some inappropriate keypoints.

(3) Assign the keypoints orientation in 3D.

(4) Generate the keypoint descriptor in 3D.

Assume that the 3D input data is ready and can be stored in a 3D array(e.g. double*** data).

My first try is to declare the 3D matrix(3D Volume) by the following (the data in 3D array can be copied to the Mat):

int sizes[] = {x ,y, z};
Mat *Img = new Mat(3, sizes, CV_8U, Scalar(0));// using namespace cv

Then I encounter some problems in step1 of the algorithm:

(1) Is there a way to declare a 3D volume using something like typedef, since the scale space contains different sizes of the 3D volume. The size array should not be constant.

(2) I cannot find ways to resize the 3D volume or do the Gaussian filter for 3D volume. Is it a reasonable approach to decompose the 3D volume into 2D slices and do the resize or Gaussian filter on each slices? Or is there any function can be directly applied on 3D volume?

Constructing the appropriate data structure should be the key of the algorithm and I don't have a clear mind on how to use opencv.

Thanks for help!


问:
How to run the same query on all tables in Access Database?
All tables have the same structure the same column names.

Here is a code:

UPDATE Table1
INNER JOIN TableX ON Table1.Column1= TableX.Column1
SET Table1.Column2 = TableX.Column2

But I would like to run this code on all tables: Table2, Table3, Table4....Table30

答:
Perhaps consider UNION ALL

```<code>SELECT ColumnName_X
FROM table1
WHERE .....
UNION ALL
SELECT ColumnName_X
FROM table2
WHERE .....
</code>```

As per my comment, your requirement is not clear.

Body:
Perhaps consider UNION ALL

SELECT ColumnName_X
FROM table1
WHERE .....
UNION ALL
SELECT ColumnName_X
FROM table2
WHERE .....

As per my comment, your requirement is not clear.


问:
why is laravel running a select query while am inserting
I'm trying to insert data into my database but I kept on getting this error since I Dropped a table called categories with which has an eloquent relationship with another table

The funny thing is Laravel is running a select query from a dropped table while my code is an insert query..

```<code>{
"message": "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'train.categories' doesn't exist (SQL: select count(*) as aggregate from `categories` where `name` = Oil Drilling)",
"exception": "Illuminate\\Database\\QueryException",
"file": "C:\\xampp\\htdocs\\enter code heretrain\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
"line": 664,
"trace": [
    {
        "file": "C:\\xampp\\htdocs\\train\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
        "line": 624,
        "function": "runQueryCallback",
        "class": "Illuminate\\Database\\Connection",
        "type": "->"
    },
    {
        "file": "C:\\xampp\\htdocs\\train\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
        "line": 333,
        "function": "run",
        "class": "Illuminate\\Database\\Connection",
        "type": "->"
    },

]
</code>```

}

This my insert code

```<code> public function store(Request $request)
{
     $request->validate([
        'name' => 'required|string|max:250|unique:categories',
        'image' => 'required|image',
        'price' => 'required',
        'duration' => 'required',
        'description' => 'required',
        'url' => 'string'
    ]);
    if ( $request->hasFile('image') ) {

        $ext = $request->image->extension();
        $iconName =  str_slug('storage/'.$request->name).'.'.$ext;
        $request->image->storeAs('public',$iconName);

        DB::table('courses')->insert(
            [
                'name' => $request->name,
                'image' => $iconName,
                'url' => $request->url,
                'price' => $request->price,
                'duration' => $request->duration,
                'description' => $request->description
            ]
        );
        return response()->json([
            'success'=>true,
            'image' => $iconName
        ]);
    }
    return response()->json(['error' => false]);
}
</code>```

答:
Check the unique:categories on the below line

name' => 'required|string|max:250|unique:categories

U may know what it is... But let me explain
The unique will check for the given name already exist in categories table. Bit u dont have that table. So it will give u that error

Body:
I'm trying to insert data into my database but I kept on getting this error since I Dropped a table called categories with which has an eloquent relationship with another table

The funny thing is Laravel is running a select query from a dropped table while my code is an insert query..

{
"message": "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'train.categories' doesn't exist (SQL: select count(*) as aggregate from `categories` where `name` = Oil Drilling)",
"exception": "Illuminate\\Database\\QueryException",
"file": "C:\\xampp\\htdocs\\enter code heretrain\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
"line": 664,
"trace": [
    {
        "file": "C:\\xampp\\htdocs\\train\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
        "line": 624,
        "function": "runQueryCallback",
        "class": "Illuminate\\Database\\Connection",
        "type": "->"
    },
    {
        "file": "C:\\xampp\\htdocs\\train\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php",
        "line": 333,
        "function": "run",
        "class": "Illuminate\\Database\\Connection",
        "type": "->"
    },

]

}

This my insert code

 public function store(Request $request)
{
     $request->validate([
        'name' => 'required|string|max:250|unique:categories',
        'image' => 'required|image',
        'price' => 'required',
        'duration' => 'required',
        'description' => 'required',
        'url' => 'string'
    ]);
    if ( $request->hasFile('image') ) {

        $ext = $request->image->extension();
        $iconName =  str_slug('storage/'.$request->name).'.'.$ext;
        $request->image->storeAs('public',$iconName);

        DB::table('courses')->insert(
            [
                'name' => $request->name,
                'image' => $iconName,
                'url' => $request->url,
                'price' => $request->price,
                'duration' => $request->duration,
                'description' => $request->description
            ]
        );
        return response()->json([
            'success'=>true,
            'image' => $iconName
        ]);
    }
    return response()->json(['error' => false]);
}


问:
how to correctly handle csv.reader headers
When reading csv files, sometimes the first row (or more than one) are headers that we don't want to include in our data.

If I don't need the data from the headers I just use next before declaring the reader (if more than one row is used for headers I can call next multiple times):

```<code>with open('myfile.csv', 'rb') as f:
    next(f)                         #skip first row
    reader = csv.reader(f)
    for row in reader:
        #process my data
</code>```

Sometimes however I don't want to include the headers in my data but still need their values. In that case I transform the csv.reader into a list and handle the headers separately.

```<code>with open('myfile.csv', 'rb') as f:
    reader = list(csv.reader(f))

    my_header = reader.pop(0)   #remove header

    for row in reader:
        #process my data
</code>```

This works and I'm happy about it. But I'm not sure if it's the "best practice" way of using csv.reader and there are other ways worth exploring.

答:
A simple way to use your csv file organized with a header line and then the values: csv + DictReader
ex:

```<code>with open ('myfile.csv', 'r') as csv_file:
csv_reader = csv.DictReader (csv_file)
     for row in csv_reader:
         print (row.get ('column1')) # print the value of column1 without title
</code>```

With this method, you can ignore your header line and precisely target the data you need, and your code will be cleaner.
Give me a return, see you later.

Body:
When reading csv files, sometimes the first row (or more than one) are headers that we don't want to include in our data.

If I don't need the data from the headers I just use next before declaring the reader (if more than one row is used for headers I can call next multiple times):

with open('myfile.csv', 'rb') as f:
    next(f)                         #skip first row
    reader = csv.reader(f)
    for row in reader:
        #process my data

Sometimes however I don't want to include the headers in my data but still need their values. In that case I transform the csv.reader into a list and handle the headers separately.

with open('myfile.csv', 'rb') as f:
    reader = list(csv.reader(f))

    my_header = reader.pop(0)   #remove header

    for row in reader:
        #process my data

This works and I'm happy about it. But I'm not sure if it's the "best practice" way of using csv.reader and there are other ways worth exploring.

Body:
A simple way to use your csv file organized with a header line and then the values: csv + DictReader
ex:

with open ('myfile.csv', 'r') as csv_file:
csv_reader = csv.DictReader (csv_file)
     for row in csv_reader:
         print (row.get ('column1')) # print the value of column1 without title

With this method, you can ignore your header line and precisely target the data you need, and your code will be cleaner.
Give me a return, see you later.


问:
using imwrite on a labeled image on matlab
I have an image that is result of labeling and applying boundaries. Each object is labeled with a number, then its boundary is defined.

The code I used is the following:

```<code>% bwboundaries() returns a cell array, where each cell contains the
% row/column coordinates for an object in the image.
% Plot the borders of all the coins on the original grayscale image
% using the coordinates returned by bwboundaries.

figure(2);
imshow(bwImage);
[r, c, p] = size(bwImage);
hold on
title('Outlines, from bwboundaries()', 'FontSize', fontSize);
axis image;
% Make sure image is not artificially stretched because of
% screen's aspect ratio.
hold on;
boundaries = bwboundaries(bw5);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), 'g', 'LineWidth', 2);
end
hold off;
</code>```

Now, I want to save the grayscale image AND the boundaries+labels applied above them in a variable, so that I can then do the following:

```<code>imwrite(A,'contours.jpg');
</code>```

and save the image to do image post processing with GUI. It seemed really easy but every time I try it saves only the labels or only the boundaries on the grayscale image. I need both of them, as in the image I uploaded above. Thanks.

EDIT: As an alternative I could directly upload the image in a GUI interface but still, the problem of saving the correct image in a variable still remains.

答:
You can use export_fig or saveas.

You can find many examples on the links, but the simplest command you can try is:

```<code>saveas(gcf,'filename.png')
</code>```

Body:
I have an image that is result of labeling and applying boundaries. Each object is labeled with a number, then its boundary is defined.

The code I used is the following:

% bwboundaries() returns a cell array, where each cell contains the
% row/column coordinates for an object in the image.
% Plot the borders of all the coins on the original grayscale image
% using the coordinates returned by bwboundaries.

figure(2);
imshow(bwImage);
[r, c, p] = size(bwImage);
hold on
title('Outlines, from bwboundaries()', 'FontSize', fontSize);
axis image;
% Make sure image is not artificially stretched because of
% screen's aspect ratio.
hold on;
boundaries = bwboundaries(bw5);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), 'g', 'LineWidth', 2);
end
hold off;

Now, I want to save the grayscale image AND the boundaries+labels applied above them in a variable, so that I can then do the following:

imwrite(A,'contours.jpg');

and save the image to do image post processing with GUI. It seemed really easy but every time I try it saves only the labels or only the boundaries on the grayscale image. I need both of them, as in the image I uploaded above. Thanks.

EDIT: As an alternative I could directly upload the image in a GUI interface but still, the problem of saving the correct image in a variable still remains.

Body:
You can use export_fig or saveas.

You can find many examples on the links, but the simplest command you can try is:

saveas(gcf,'filename.png')


问:
Basic Python: How do I normalize a data series?
I have a dataframe with 5 columns indexed by date.  I would like to normalize these data series by the first item in their lists.

```<code>                A   B   C   D   E
    1/1/2017    3   4   1   2   3
    1/2/2017    7   4   4   3   3
    1/3/2017    2   5   5   4   3
    1/4/2017    2   5   3   6   3
    1/5/2017    2   2   2   6   6
</code>```

for example, in column A, i would like to divided everything by 3, the first item on the list.  Same for column B to E.

thanks for your help!

Body:
I have a dataframe with 5 columns indexed by date.  I would like to normalize these data series by the first item in their lists.

                A   B   C   D   E
    1/1/2017    3   4   1   2   3
    1/2/2017    7   4   4   3   3
    1/3/2017    2   5   5   4   3
    1/4/2017    2   5   3   6   3
    1/5/2017    2   2   2   6   6

for example, in column A, i would like to divided everything by 3, the first item on the list.  Same for column B to E.

thanks for your help!

Body:
By using div

df.div(df.iloc[0,:],1)
Out[496]:
                 A     B    C    D    E
1/1/2017  1.000000  1.00  1.0  1.0  1.0
1/2/2017  2.333333  1.00  4.0  1.5  1.0
1/3/2017  0.666667  1.25  5.0  2.0  1.0
1/4/2017  0.666667  1.25  3.0  3.0  1.0
1/5/2017  0.666667  0.50  2.0  3.0  2.0


问:
warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777
Every time I run this command rails server:

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

I searched for a solution here and they said to type: chmod go-w /usr/local/bin

But I get this error:

chmod: Unable to change file mode on /usr/local/bin: Operation not permitted

I am using OS X by the way.

答:
I'm also having the exact same problem with both /usr/local/bin and /etc/sudoers on OSX Snow lepard.Even when i logged in as admin and tried to change the permissions via the terminal, it still says "Operation not permitted". And i did the following to get the permission of these folders.

From the terminal, I accessed /etc/sudoers file and using pico editor i added the following code:
username    ALL=(ALL) ALL
Replace "username" with your MAC OS account name

ContentLicense: CC BY-SA 2.5


Title: Basic Python: How do I normalize a data series?

Body:
In [100]: df.div(df.iloc[0])
Out[100]:
                 A     B    C    D    E
1/1/2017  1.000000  1.00  1.0  1.0  1.0
1/2/2017  2.333333  1.00  4.0  1.5  1.0
1/3/2017  0.666667  1.25  5.0  2.0  1.0
1/4/2017  0.666667  1.25  3.0  3.0  1.0
1/5/2017  0.666667  0.50  2.0  3.0  2.0

or

In [101]: df / df.iloc[0]
Out[101]:
                 A     B    C    D    E
1/1/2017  1.000000  1.00  1.0  1.0  1.0
1/2/2017  2.333333  1.00  4.0  1.5  1.0
1/3/2017  0.666667  1.25  5.0  2.0  1.0
1/4/2017  0.666667  1.25  3.0  3.0  1.0
1/5/2017  0.666667  0.50  2.0  3.0  2.0


问:
How to build full go program binary with gccgo?
I have noticed that when using go build the binary result can be in excess of 2MB; but using gccgo the binary is less than 35k.

The other issue that I noticed when using gccgo is that the produced binary isn't runnable on another linux box (missing libgo.so I believe) but the go build binary runs just fine (so I imagine its because the binary includes all that is necessary to run?); is there a way to do this with gccgo?

答:
With go 1.8 or above, if go is built with CGO_ENABLED=1 (default to 1), a native compilation links dynamically. Check this variable by running go env CGO_ENABLED.
You can switch to link statically by set the environment variable CGO_ENABLED to 0 when running go build.

```<code>CGO_ENABLED=0 go build
</code>```

BTW, cross compiling uses static linkage automatically.

Body:
With go 1.8 or above, if go is built with CGO_ENABLED=1 (default to 1), a native compilation links dynamically. Check this variable by running go env CGO_ENABLED.
You can switch to link statically by set the environment variable CGO_ENABLED to 0 when running go build.

CGO_ENABLED=0 go build

BTW, cross compiling uses static linkage automatically.


问:
PostgresSql + Nodejs (ClaudiaJS) : How to cast array of string to array of timestamp
I am writing API which insert into a table with multiple rows, I am using UNNEST to make it work.

What I have done:

in js file:

```<code>api.post(PREFIX + '/class/insert', function (request) {

    var db = pgp(dbconnect);

    //Params
    var data = request.body; //should be an array

    var classes = [];
    var starts = [];
    var ends = [];

    for (var i = 0; i < data.length; i++) {
        classes.push(data[i].class_id);
        starts.push(data[i].timestamp_start);
        ends.push(data[i].timestamp_end);
    }

    const PQ = require('pg-promise').ParameterizedQuery;

    var sql =
    "INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
    "VALUES(  "+
        "UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + ")"

    const final_sql = new PQ(sql);

    return db.any(final_sql)
        .then(function (data) {
            pgp.end();

            return 'successful';
        })
        .catch(function (error) {
            console.log("Error: " + error);
            pgp.end();
        });
}
</code>```

Request body

```<code>[{
    "class_id":"1",
    "timestamp_start":"2017-11-14 14:01:23.634437+00",
    "timestamp_end":"2017-11-14 15:20:23.634437+00"
}, {
    "class_id":"2",
    "timestamp_start":"2017-11-14 15:01:23.634437+00",
    "timestamp_end": "2017-11-14 16:20:23.634437+00"
}]
</code>```

When I run api in postman, I get the error is:

column "timestamp_start" is of type timestamp with time zone but
  expression is of type text

Issue is obviously from ARRAY of string that I used in sql, my question is how to create ARRAY of timestamp for UNNEST, or any suggestion are appreciated.

Thanks

答:
Many thanks to @JustMe,

It worked after casting array

```<code>var sql =
    "INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
    "VALUES(  "+
        "UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "::timestamp[]), " +
        "UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + "::timestamp[])"
</code>```

Body:
I am writing API which insert into a table with multiple rows, I am using UNNEST to make it work.

What I have done:

in js file:

api.post(PREFIX + '/class/insert', function (request) {

    var db = pgp(dbconnect);

    //Params
    var data = request.body; //should be an array

    var classes = [];
    var starts = [];
    var ends = [];

    for (var i = 0; i < data.length; i++) {
        classes.push(data[i].class_id);
        starts.push(data[i].timestamp_start);
        ends.push(data[i].timestamp_end);
    }

    const PQ = require('pg-promise').ParameterizedQuery;

    var sql =
    "INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
    "VALUES(  "+
        "UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + ")"

    const final_sql = new PQ(sql);

    return db.any(final_sql)
        .then(function (data) {
            pgp.end();

            return 'successful';
        })
        .catch(function (error) {
            console.log("Error: " + error);
            pgp.end();
        });
}

Request body

[{
    "class_id":"1",
    "timestamp_start":"2017-11-14 14:01:23.634437+00",
    "timestamp_end":"2017-11-14 15:20:23.634437+00"
}, {
    "class_id":"2",
    "timestamp_start":"2017-11-14 15:01:23.634437+00",
    "timestamp_end": "2017-11-14 16:20:23.634437+00"
}]

When I run api in postman, I get the error is:

column "timestamp_start" is of type timestamp with time zone but
  expression is of type text

Issue is obviously from ARRAY of string that I used in sql, my question is how to create ARRAY of timestamp for UNNEST, or any suggestion are appreciated.

Thanks

Body:
Many thanks to @JustMe,

It worked after casting array

var sql =
    "INSERT INTO sa1.class(class_id, timestamp_start, timestamp_end) " +
    "VALUES(  "+
        "UNNEST(ARRAY" + JSON.stringify(classes).replace(/"/g, "'") + "), " +
        "UNNEST(ARRAY" + JSON.stringify(starts).replace(/"/g, "'") + "::timestamp[]), " +
        "UNNEST(ARRAY" + JSON.stringify(ends).replace(/"/g, "'") + "::timestamp[])"


问:
gwt widget - mutually-exclusive toggle button
I want a hybrid of a ToggleButton and RadioButton.
I want the "mutually-exclusive" part of RadioButton, and the gui look and behavior of ToggleButton(up and down states).
Does one already exist?</p>

答:
I've  adapted kirushik's solution and created a simple "ToggleButtonPanel" widget that takes an arbitrary number of ToggleButtons (and possibly any other widgets you'd like to add) and a panel of your choosing (defaults to VerticalPanel) and makes the buttons mutually exclusive.

What's nice about this is that the panel itself fires ClickEvents when the buttons are clicked. This way, you can add a single ClickHandler to the ToggleGroupPanel and then determine which button was clicked using event.getSource()

```<code>import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ToggleButtonPanel extends Composite implements HasWidgets, HasClickHandlers{

    public ToggleButtonPanel() {
        this(new VerticalPanel());
    }

    public ToggleButtonPanel(Panel panel){
        this.panel = panel;
        initWidget(panel);
    }

    @Override
    public void add(Widget w) {
        if(w instanceof ToggleButton){
            ToggleButton button = (ToggleButton) w;
            button.addClickHandler(handler);
        }
        panel.add(w);
    }

    @Override
    public void clear() {
        panel.clear();
    }

    @Override
    public Iterator<Widget> iterator() {
        return panel.iterator();
    }

    @Override
    public boolean remove(Widget w) {
        return panel.remove(w);
    }

    @Override
    public void setWidth(String width) {
        panel.setWidth(width);
    };

    @Override
    public void setHeight(String height) {
        panel.setHeight(height);
    }

    private final Panel panel;
    private ClickHandler handler = new ClickHandler(){
        @Override
        public void onClick(ClickEvent event) {
            Iterator<Widget> itr = panel.iterator();
            while(itr.hasNext()){
                Widget w = itr.next();
                if(w instanceof ToggleButton){
                    ToggleButton button = (ToggleButton) w;
                    button.setDown(false);
                    if(event.getSource().equals(button)) {
                        button.setDown(true);
                    }
                }
            }

            for(ClickHandler h : handlers){
                h.onClick(event);
            }
        }
    };

    private List<ClickHandler> handlers = new ArrayList<ClickHandler>();
    @Override
    public HandlerRegistration addClickHandler(final ClickHandler handler) {
        handlers.add(handler);
        return new HandlerRegistration() {

            @Override
            public void removeHandler() {
                handlers.remove(handler);
            }
        };
    }

}
</code>```

Body:
I've  adapted kirushik's solution and created a simple "ToggleButtonPanel" widget that takes an arbitrary number of ToggleButtons (and possibly any other widgets you'd like to add) and a panel of your choosing (defaults to VerticalPanel) and makes the buttons mutually exclusive.

What's nice about this is that the panel itself fires ClickEvents when the buttons are clicked. This way, you can add a single ClickHandler to the ToggleGroupPanel and then determine which button was clicked using event.getSource()

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ToggleButtonPanel extends Composite implements HasWidgets, HasClickHandlers{

    public ToggleButtonPanel() {
        this(new VerticalPanel());
    }

    public ToggleButtonPanel(Panel panel){
        this.panel = panel;
        initWidget(panel);
    }

    @Override
    public void add(Widget w) {
        if(w instanceof ToggleButton){
            ToggleButton button = (ToggleButton) w;
            button.addClickHandler(handler);
        }
        panel.add(w);
    }

    @Override
    public void clear() {
        panel.clear();
    }

    @Override
    public Iterator<Widget> iterator() {
        return panel.iterator();
    }

    @Override
    public boolean remove(Widget w) {
        return panel.remove(w);
    }

    @Override
    public void setWidth(String width) {
        panel.setWidth(width);
    };

    @Override
    public void setHeight(String height) {
        panel.setHeight(height);
    }

    private final Panel panel;
    private ClickHandler handler = new ClickHandler(){
        @Override
        public void onClick(ClickEvent event) {
            Iterator<Widget> itr = panel.iterator();
            while(itr.hasNext()){
                Widget w = itr.next();
                if(w instanceof ToggleButton){
                    ToggleButton button = (ToggleButton) w;
                    button.setDown(false);
                    if(event.getSource().equals(button)) {
                        button.setDown(true);
                    }
                }
            }

            for(ClickHandler h : handlers){
                h.onClick(event);
            }
        }
    };

    private List<ClickHandler> handlers = new ArrayList<ClickHandler>();
    @Override
    public HandlerRegistration addClickHandler(final ClickHandler handler) {
        handlers.add(handler);
        return new HandlerRegistration() {

            @Override
            public void removeHandler() {
                handlers.remove(handler);
            }
        };
    }

}


问:
xml getting the last row value while transforming to xslt
I have a scenario where I want the  value of the last row of the < function > tag in the target html files  ( passstatus,failstatus,errorstatus ) etc. I have tried like this using the last() method to get that, but  its not working for me , Please help me resolve the issue.Thanks for help.

This is my xml file

```<code><TestSuite>
    <TestCase>
        <name>checkLoginPage</name>
        <function>
            <method>test</method>
            <status>ERROR</status>
            <reason>Traceback (most recent call last):</reason>
            <passstatus>0</passstatus>
            <failstatus>0</failstatus>
            <errorstatus>1</errorstatus>
            <method>test1</method>
            <status>FAIL</status>
            <reason>Traceback (most recent call last):</reason>
            <passstatus>0</passstatus>
            <failstatus>1</failstatus>
            <errorstatus>1</errorstatus>
        </function>
    </TestCase>
</TestSuite>
</code>```

This is my xslt file

```<code><table border="1" id="result_table">
    <tr bgcolor="#777">
        <th align="left">TestFile/TestCase</th>
        <th align="left">Pass</th>
        <th align="left">Fail</th>
        <th align="left">Error</th>
    </tr>
    <xsl:for-each select="/*/function">
        <xsl:if test="status='FAIL'">
            <tr bgcolor="#6c6">
                <td>
                    <xsl:value-of select="name"/>.
                    <xsl:value-of select="method"/>
                </td>
                <td>
                    <xsl:value-of select="/*[last()]/passstatus"/>
                </td>
                <td>
                    <xsl:value-of select="failstatus"/>
                </td>
                <td>
                    <xsl:value-of select="errorstatus"/>
                </td>
            </tr>
        </xsl:if>
</code>```

This is the target file I expect from the transformation ,

```<code><html xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
   <head>
      <style>
  td {
    border: 1px solid #777;
    padding: 2px;

}

</style>
   </head>
   <body>
      <table border="1" id="result_table">
         <tr bgcolor="#777">
            <th align="left">TestFile/TestCase</th>
            <th align="left">Pass</th>
            <th align="left">Fail</th>
            <th align="left">Error</th>
         </tr>
         <tr bgcolor="#6c6">
            <td>checkLoginPage.test2</td>
            <td>2</td>
            <td>1</td>
            <td>0</td>
         </tr>

      </table>
   </body>
</html>
</code>```

答:
Since you have accepted my suggestion in comments to change the XML format, let's consider a restructured XML input of this form:

```<code><TestSuite>
  <TestCase>
    <name>checkLoginPage</name>
    <function>
      <method>test</method>
      <status>ERROR</status>
      <reason>Traceback (most recent call last):</reason>
      <passstatus>0</passstatus>
      <failstatus>0</failstatus>
      <errorstatus>1</errorstatus>
    </function>
    <function>
      <method>test1</method>
      <status>FAIL</status>
      <reason>Traceback (most recent call last):</reason>
      <passstatus>0</passstatus>
      <failstatus>1</failstatus>
      <errorstatus>1</errorstatus>
    </function>
  </TestCase>
</TestSuite>
</code>```

(I'd actually consider a different element name than "function" there, but the above is what was discussed in comments.)

The question, then, becomes how to select only the last (in document order) <function> element in each <TestCase> for transformation, but now that's simple: you can use a predicate involving the last() function, just as you initially tried to do.  For example,

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/">
    <table border="1" id="result_table">
      <tr bgcolor="#777">
        <th align="left">TestFile/TestCase</th>
        <th align="left">Pass</th>
        <th align="left">Fail</th>
        <th align="left">Error</th>
      </tr>
      <!-- here's the key XPath expression: -->
      <xsl:for-each select="/TestSuite/TestCase/function[last()]">
        <xsl:if test="status='FAIL'">
      <tr bgcolor="#6c6">
        <td><xsl:value-of select="ancestor::TestCase/name"/>.<xsl:value-of select="method"/></td>
        <td><xsl:value-of select="passstatus"/></td>
        <td><xsl:value-of select="failstatus"/></td>
        <td><xsl:value-of select="errorstatus"/></td>
      </tr>
        </xsl:if>
      </xsl:for-each>
    </table>
  </xsl:template>

</xsl:stylesheet>
</code>```

When applied to the restructured input (as presented in this answer) that produces

```<code><table border="1" id="result_table">
  <tr bgcolor="#777">
    <th align="left">TestFile/TestCase</th>
    <th align="left">Pass</th>
    <th align="left">Fail</th>
    <th align="left">Error</th>
  </tr>
  <tr bgcolor="#6c6">
    <td>checkLoginPage.test1</td>
    <td>0</td>
    <td>1</td>
    <td>1</td>
  </tr>
</table>
</code>```

, which seems to be the form you want.

Body:
I have a scenario where I want the  value of the last row of the < function > tag in the target html files  ( passstatus,failstatus,errorstatus ) etc. I have tried like this using the last() method to get that, but  its not working for me , Please help me resolve the issue.Thanks for help.

This is my xml file

<TestSuite>
    <TestCase>
        <name>checkLoginPage</name>
        <function>
            <method>test</method>
            <status>ERROR</status>
            <reason>Traceback (most recent call last):</reason>
            <passstatus>0</passstatus>
            <failstatus>0</failstatus>
            <errorstatus>1</errorstatus>
            <method>test1</method>
            <status>FAIL</status>
            <reason>Traceback (most recent call last):</reason>
            <passstatus>0</passstatus>
            <failstatus>1</failstatus>
            <errorstatus>1</errorstatus>
        </function>
    </TestCase>
</TestSuite>

This is my xslt file

        TestFile/TestCase
        Pass
        Fail
        Error

    <xsl:for-each select="/*/function">
        <xsl:if test="status='FAIL'">

                    <xsl:value-of select="name"/>.
                    <xsl:value-of select="method"/>

                    <xsl:value-of select="/*[last()]/passstatus"/>

                    <xsl:value-of select="failstatus"/>

                    <xsl:value-of select="errorstatus"/>

        </xsl:if>

This is the target file I expect from the transformation ,

            TestFile/TestCase
            Pass
            Fail
            Error

            checkLoginPage.test2
            2
            1
            0

Body:
Since you have accepted my suggestion in comments to change the XML format, let's consider a restructured XML input of this form:

<TestSuite>
  <TestCase>
    <name>checkLoginPage</name>
    <function>
      <method>test</method>
      <status>ERROR</status>
      <reason>Traceback (most recent call last):</reason>
      <passstatus>0</passstatus>
      <failstatus>0</failstatus>
      <errorstatus>1</errorstatus>
    </function>
    <function>
      <method>test1</method>
      <status>FAIL</status>
      <reason>Traceback (most recent call last):</reason>
      <passstatus>0</passstatus>
      <failstatus>1</failstatus>
      <errorstatus>1</errorstatus>
    </function>
  </TestCase>
</TestSuite>

(I'd actually consider a different element name than "function" there, but the above is what was discussed in comments.)

The question, then, becomes how to select only the last (in document order) <function> element in each <TestCase> for transformation, but now that's simple: you can use a predicate involving the last() function, just as you initially tried to do.  For example,

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/">
    <table border="1" id="result_table">
      <tr bgcolor="#777">
        <th align="left">TestFile/TestCase</th>
        <th align="left">Pass</th>
        <th align="left">Fail</th>
        <th align="left">Error</th>
      </tr>
      <!-- here's the key XPath expression: -->
      <xsl:for-each select="/TestSuite/TestCase/function[last()]">
        <xsl:if test="status='FAIL'">
      <tr bgcolor="#6c6">
        <td><xsl:value-of select="ancestor::TestCase/name"/>.<xsl:value-of select="method"/></td>
        <td><xsl:value-of select="passstatus"/></td>
        <td><xsl:value-of select="failstatus"/></td>
        <td><xsl:value-of select="errorstatus"/></td>
      </tr>
        </xsl:if>
      </xsl:for-each>
    </table>
  </xsl:template>

</xsl:stylesheet>

When applied to the restructured input (as presented in this answer) that produces

<table border="1" id="result_table">
  <tr bgcolor="#777">
    <th align="left">TestFile/TestCase</th>
    <th align="left">Pass</th>
    <th align="left">Fail</th>
    <th align="left">Error</th>
  </tr>
  <tr bgcolor="#6c6">
    <td>checkLoginPage.test1</td>
    <td>0</td>
    <td>1</td>
    <td>1</td>
  </tr>
</table>

, which seems to be the form you want.


问:
Test whether a UIView is hidden using XCUITest
How do I test whether a view is hidden using XCUITest?  A view is sometimes hidden (set in Xcode like this: Hidden view)
How do I test for that in XCUITest using Swift?  In my case, the view is just a label.  I tried something like this: XCTAssertFalse(app.staticTexts["pushNotificationInstruction"].accessibilityElementsHidden) .  But that's not it.  accessibilityElementsHidden is not the same as the view is hidden.  Thanks.

答:
You can assert that the view does not exists and use another test to check the scenario when it does exists. Maybe a bit fragile, but that would cover you case. </p>

```<code>let viewControllerShown = app.otherElements["view_myviewcontroller"].waitForExistence(timeout: 5)
XCTAssert(viewControllerShown)
let instructionViewExists = app.staticTexts["pushNotificationInstruction"].exists
XCTAssertFalse(instructionViewExists)
</code>```

Body:
You can assert that the view does not exists and use another test to check the scenario when it does exists. Maybe a bit fragile, but that would cover you case.

let viewControllerShown = app.otherElements["view_myviewcontroller"].waitForExistence(timeout: 5)
XCTAssert(viewControllerShown)
let instructionViewExists = app.staticTexts["pushNotificationInstruction"].exists
XCTAssertFalse(instructionViewExists)


问:
Sequences (using as ID) issue in Oracle SQL Developer
I am using sequences to create IDs, so while executing insert stored procedure it will create unique value for ID. But after some time it is losing the definition for the sequence.

Not sure why this is happening again and again and how to solve the problem?

I am using Oracle SQL Developer and in the edit table property there is 'Identity Column' setting. See below:

Next step is setting up trigger and sequence:

It was working fine for some time until this property defaulted. Now it is not there anymore:

Still have this trigger and sequence object in the schema and able to setup again but it will break later.

How to avoid this problem in future?

答:
This is what I received from IT support regarding the issue:

A few possibilities that might cause this:

1 - Another user with limited privileges might be editing the table using SQL Developer. In this case, if this user's privilege is not enough to obtain the sequence and/or trigger information from the database, the tool might leave the fields blank and disable it when table changes are saved.

2 - The objects are being changed or removed outside of SQL Developer, causing it to lose the information. In my tests I noticed that dropping the trigger and recreating it with the same name caused the identity property information to be lost on SQL Developer.

Even being the trigger enabled, and working for inserts it could not retrieve the information.

Then, if I run an alter trigger to enable it (even tough dba_trigger is reporting it as already enabled), SQL Developer will list the information again:
ALTER TRIGGER "AWS"."TABLE1_TRG" ENABLE;

So it looks like there are some issues with the SQL Developer, that is causing this behavior.
Next time it happen, please check if the trigger still exist on the database and is enabled with the query below:

```<code>select owner, trigger_name, TRIGGER_TYPE, TRIGGERING_EVENT, TABLE_OWNER, TABLE_NAME, STATUS
from dba_triggers
where trigger_name = 'ENTER_YOUR_TRG_NAME'; --Just change the trigger name in WHERE
</code>```

Body:
This is what I received from IT support regarding the issue:

A few possibilities that might cause this:

1 - Another user with limited privileges might be editing the table using SQL Developer. In this case, if this user's privilege is not enough to obtain the sequence and/or trigger information from the database, the tool might leave the fields blank and disable it when table changes are saved.

2 - The objects are being changed or removed outside of SQL Developer, causing it to lose the information. In my tests I noticed that dropping the trigger and recreating it with the same name caused the identity property information to be lost on SQL Developer.

Even being the trigger enabled, and working for inserts it could not retrieve the information.

Then, if I run an alter trigger to enable it (even tough dba_trigger is reporting it as already enabled), SQL Developer will list the information again:
ALTER TRIGGER "AWS"."TABLE1_TRG" ENABLE;

So it looks like there are some issues with the SQL Developer, that is causing this behavior.
Next time it happen, please check if the trigger still exist on the database and is enabled with the query below:

select owner, trigger_name, TRIGGER_TYPE, TRIGGERING_EVENT, TABLE_OWNER, TABLE_NAME, STATUS
from dba_triggers
where trigger_name = 'ENTER_YOUR_TRG_NAME'; --Just change the trigger name in WHERE


问:
Pass environment variable to dockerfile build
I am trying to create a service consisting of a web server and database all in docker containers. Currently I am trying to create same environment file for both of them that would contain database credentials. Unfortunatelly, when I try to build database with it, it turns out that they are empty. How can I create a project with single environment file for both components? Here is my docker-compose.yml:

```<code>version: '2'

services:
  db:
    build:
      context: .
      dockerfile: Dockerfile-db
    ports:
      - '5433:5432'
    env_file:
      - env
  web:
    build: .
    ports:
      - '8000:8000'
    command: venv/bin/python manage.py runserver 0.0.0.0:8000
    depends_on:
      - db
    env_file:
      - env
</code>```

Here is part of my Dockerfile-db file responsible for creating database:

```<code>FROM ubuntu:16.04

RUN apt-get update && apt-get install -y postgresql-9.5-postgis-2.2

USER postgres

ARG DB_PASSWORD
ARG DB_NAME

RUN echo $DB_PASSWORD

RUN /etc/init.d/postgresql start && \
    psql --command "ALTER USER postgres WITH PASSWORD '$DB_PASSWORD';" && \
    psql --command "CREATE DATABASE $DB_NAME;" && \
    psql --command "\\c $DB_NAME" && \
    psql --command "CREATE EXTENSION postgis;" && \
    psql --command "CREATE EXTENSION postgis_topology;"
</code>```

And my env file has following structure:

```<code>DB_NAME=some_name
DB_USER=postgres
DB_PASSWORD=some_password
DB_HOST=db
DB_PORT=5432
</code>```

答:
The environment file is not part of the build process, it is used when running the container.

You need to use build-args. In docker-compose you can specify build args in the file:

```<code>build:
  context: .
  dockerfile: Dockerfile-db
  args:
    DB_NAME: some_name
    DB_USER: postgress
    ...
</code>```

This might not be a good idea if you want to publish the composefile, as you are storing credentials in it. You can explicitly build and pass --build-arg

```<code>docker-compose build --build-arg DB_NAME= some_name ...
</code>```

And when running specify no build in docker-compose run --no-build

Update:

As suggested by @gonczor, a shorter and cleaner syntax to use pass the env file as build args is:

```<code>docker-compose build --build-args $(cat envfile)
</code>```

Body:
I am trying to create a service consisting of a web server and database all in docker containers. Currently I am trying to create same environment file for both of them that would contain database credentials. Unfortunatelly, when I try to build database with it, it turns out that they are empty. How can I create a project with single environment file for both components? Here is my docker-compose.yml:

version: '2'

services:
  db:
    build:
      context: .
      dockerfile: Dockerfile-db
    ports:
      - '5433:5432'
    env_file:
      - env
  web:
    build: .
    ports:
      - '8000:8000'
    command: venv/bin/python manage.py runserver 0.0.0.0:8000
    depends_on:
      - db
    env_file:
      - env

Here is part of my Dockerfile-db file responsible for creating database:

FROM ubuntu:16.04

RUN apt-get update && apt-get install -y postgresql-9.5-postgis-2.2

USER postgres

ARG DB_PASSWORD
ARG DB_NAME

RUN echo $DB_PASSWORD

RUN /etc/init.d/postgresql start && \
    psql --command "ALTER USER postgres WITH PASSWORD '$DB_PASSWORD';" && \
    psql --command "CREATE DATABASE $DB_NAME;" && \
    psql --command "\\c $DB_NAME" && \
    psql --command "CREATE EXTENSION postgis;" && \
    psql --command "CREATE EXTENSION postgis_topology;"

And my env file has following structure:

DB_NAME=some_name
DB_USER=postgres
DB_PASSWORD=some_password
DB_HOST=db
DB_PORT=5432

Body:
The environment file is not part of the build process, it is used when running the container.

You need to use build-args. In docker-compose you can specify build args in the file:

build:
  context: .
  dockerfile: Dockerfile-db
  args:
    DB_NAME: some_name
    DB_USER: postgress
    ...

This might not be a good idea if you want to publish the composefile, as you are storing credentials in it. You can explicitly build and pass --build-arg

docker-compose build --build-arg DB_NAME= some_name ...

And when running specify no build in docker-compose run --no-build

Update:

As suggested by @gonczor, a shorter and cleaner syntax to use pass the env file as build args is:

docker-compose build --build-args $(cat envfile)


问:
Is this UI layout possible with Android (java based)?
I'm a complete newbie to Android but played with the idea to port an app to Android to learn it. After doing some first steps with the SDK and looking at the UI samples, I'm still unsure whether the particular ui layout of this conference schedule/timetable app you can see here

http://www.youtube.com/watch?v=dJ5rDybL8es

is possible with Android.

I particular, the layout consists of something like a table with a fixed column on the left showing the times, which is always visible, and a column to the right which shows sessions that take place in the room displayed at the columns top.
By swiping left/right on the right column, you can change the room and see the corresponding session.
(In landscape view all three rooms are shown next to each other, but I'm particularly interested in that scroller possibility of the portrait layout)

I've seen that there is a ViewFlipper class, but I'm unsure whether that could scroll parts of the screen (the right "column" in my example) and also if by swiping.

I would be very happy if someone with Android experience could give me some advice with which view elements I can replicate that layout on Android, if possible.

Thanks

答:
In its very simplest form you're gonna want a ScrollView on the left, and then a SwipeView on the right, and then within that SwipeView you're gonna want another ScrollView.

I'd consider not using a ScrollView though, but instead using a ListView so that only the elements in view are actually loaded in.

ScrollView is part of the Android SDK.

SwipeView is a nice little addition to the Android SDK, have some links:

http://jasonfry.co.uk/?id=23

http://jasonfry.co.uk/?id=24

https://jasonfry.co.uk/blog/android-swipeview-update/

(disclaimer, I made SwipeView...;)

Here is some information about ListView:
http://developer.android.com/reference/android/widget/ListView.html

Have a look in the API demos app that you should have downloaded with the SDK for how to use a ListView (as well as a lot of other very useful things...)

The layout in the video is definitely possible! Good luck!

ContentLicense: CC BY-SA 4.0


问:
Cannot update identity column
I want to edit data in database but if I tried to edit any value in a row, an error message

Cannot update identity column 'ProductID'

appeared after trying to update the data. I'm just a beginner, so I have no idea where the bug is.

```<code><asp:SqlDataSource ID="Adventure" runat="server"
     ConnectionString="<%$ ConnectionStrings:ConStrAdventure %>"
     DeleteCommand="DELETE FROM [Production].[Product] WHERE [ProductID] = @ProductID"
     InsertCommand="INSERT INTO [Production].[Product]  ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (@ProductID, @Name, @ProductNumber, @MakeFlag, @FinishedGoodFlag, @Color, @SafetyStockLevel, @ReorderPoint, @StandardCost, @ListPrice, @Size, @SizeUnitMeasureCode, @WeightUnitMeasureCode, @Weight, @DaysToManufacture, @ProductLine, @Class, @Style, @ProductSubcategoryID, @ProductModelID, @SellStartDate, @SellEndDate, @DiscontinuedDate, @rowguid, @ModifiedDate) " SelectCommand="SELECT * FROM [Production].[Product]"
     UpdateCommand="UPDATE [Production].[Product] SET [ProductID] = @ProductID,[Name] = @Name, [ProductNumber] = @ProductNumber, [MakeFlag] = @MakeFlag, [FinishedGoodsFlag] = @FinishedGoodsFlag, [Color] = @Color, [SafetyStockLevel] = @SafetyStockLevel, [ReorderPoint] = @ReorderPoint, [StandardCost] = @StandardCost, [ListPrice] = @ListPrice, [Size] = @Size, [SizeUnitMeasureCode] = @SizeUnitMeasureCode, [WeightUnitMeasureCode] = @WeightUnitMeasureCode, [Weight] = @Weight, [DaysToManufacture] =  @DaysToManufacture, [ProductLine] = @ProductLine, [Class] = @Class, [Style] = @Style, [ProductSubcategoryID] = @ProductSubcategoryID, [ProductModelID] = @ProductModelID, [SellStartDate] = @SellStartDate, [SellEndDate] = @SellEndDate, [DiscontinuedDate] = @DiscontinuedDate, [rowguid] = @rowguid, [ModifiedDate] = @ModifiedDate WHERE [ProductID] = @ProductID">
</code>```

The second part of the code here as image.

Thank you in advance for any ideas.

答:
Your update command begins,

```<code>UpdateCommand="UPDATE [Production].[Product] SET [ProductID] = @ProductID,[Name],.....
</code>```

The error message is telling you you can't update [ProductID] as it's an
'identity column'
, that is your primary key. You can't update your primary key, that's what identifies the record. Just drop [ProductID] = @ProductID from the list of column/data pairs in your UpdateCommand.

Title: Cannot update identity column

Body:
I want to edit data in database but if I tried to edit any value in a row, an error message

Cannot update identity column 'ProductID'

appeared after trying to update the data. I'm just a beginner, so I have no idea where the bug is.

<asp:SqlDataSource ID="Adventure" runat="server"
     ConnectionString="<%$ ConnectionStrings:ConStrAdventure %>"
     DeleteCommand="DELETE FROM [Production].[Product] WHERE [ProductID] = @ProductID"
     InsertCommand="INSERT INTO [Production].[Product]  ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (@ProductID, @Name, @ProductNumber, @MakeFlag, @FinishedGoodFlag, @Color, @SafetyStockLevel, @ReorderPoint, @StandardCost, @ListPrice, @Size, @SizeUnitMeasureCode, @WeightUnitMeasureCode, @Weight, @DaysToManufacture, @ProductLine, @Class, @Style, @ProductSubcategoryID, @ProductModelID, @SellStartDate, @SellEndDate, @DiscontinuedDate, @rowguid, @ModifiedDate) " SelectCommand="SELECT * FROM [Production].[Product]"
     UpdateCommand="UPDATE [Production].[Product] SET [ProductID] = @ProductID,[Name] = @Name, [ProductNumber] = @ProductNumber, [MakeFlag] = @MakeFlag, [FinishedGoodsFlag] = @FinishedGoodsFlag, [Color] = @Color, [SafetyStockLevel] = @SafetyStockLevel, [ReorderPoint] = @ReorderPoint, [StandardCost] = @StandardCost, [ListPrice] = @ListPrice, [Size] = @Size, [SizeUnitMeasureCode] = @SizeUnitMeasureCode, [WeightUnitMeasureCode] = @WeightUnitMeasureCode, [Weight] = @Weight, [DaysToManufacture] =  @DaysToManufacture, [ProductLine] = @ProductLine, [Class] = @Class, [Style] = @Style, [ProductSubcategoryID] = @ProductSubcategoryID, [ProductModelID] = @ProductModelID, [SellStartDate] = @SellStartDate, [SellEndDate] = @SellEndDate, [DiscontinuedDate] = @DiscontinuedDate, [rowguid] = @rowguid, [ModifiedDate] = @ModifiedDate WHERE [ProductID] = @ProductID">

The second part of the code here as image.

Thank you in advance for any ideas.

Body:
Your update command begins,

UpdateCommand="UPDATE [Production].[Product] SET [ProductID] = @ProductID,[Name],.....

The error message is telling you you can't update [ProductID] as it's an
'identity column'
, that is your primary key. You can't update your primary key, that's what identifies the record. Just drop [ProductID] = @ProductID from the list of column/data pairs in your UpdateCommand.


问:
xpath replace not working?
With this HTML

```<code><tr>
                <td class="listOddRow"><a href="/bnc/page?BPPC=BPPC17111409443230443484&aliasDispatcher=bankingAccountHistory&key=1027510022703&cAliasDispatcher=bankingStatement&kookToken=wHwy83w6cX" class="listLinks" onclick="setValidExitDocument();">Chequing</a> </td>
                <td class="listOddRow">00-227-03</td>
                <td class="listOddRow" nowrap="">0275-1</td>
                <td class="listOddRow" align="right" nowrap="">$ 28.08</td>

            </tr>
</code>```

Anyone knows why this works

//td[contains(text(),"00-227-03")]/parent::tr//a

but not this? I want to remove the dashes from the text() before calling contains()

//td[contains(replace(text(), "-", ""),"0022703")]/parent::tr//a

答:
At least in xpath 1.0 there is no function replace, but there is translate working in the same way - it replaces in the 1st string chars presented in the 2nd one by corresponding chars in the 3rd. So, you can use the Xpath

```<code>//td[contains(translate(text(), "-", ""),"0022703")]/parent::tr//a
</code>```

Title: xpath replace not working?

Body:
With this HTML

                Chequing
                00-227-03
                0275-1
                $ 28.08

Anyone knows why this works

//td[contains(text(),"00-227-03")]/parent::tr//a

but not this? I want to remove the dashes from the text() before calling contains()

//td[contains(replace(text(), "-", ""),"0022703")]/parent::tr//a

Body:
At least in xpath 1.0 there is no function replace, but there is translate working in the same way - it replaces in the 1st string chars presented in the 2nd one by corresponding chars in the 3rd. So, you can use the Xpath

//td[contains(translate(text(), "-", ""),"0022703")]/parent::tr//a


问:
How Can I see steps of running codes in phpstorm?
I have a problem in my PHP codes I cant find that. because dont display any warning or error and redirect to the main page of my website project and after many test couldnt find problem.

I want to see steps of running the code for example:

get values of $click and $usercode variables===> redirect to request_change.php and run mysql_query with value="select * from users where userid=65643"==> get $username ==> and else...

I can see some running steps by debugging but not exact that I Want and display many error about finding some directories in require_once function but while my webpages display and process information right by wamp.

Is any way to debugging same as that by Phpstorm or any other programs?

OR
 How can I run My php code in phpstorm step-by-step and line-by-line??

Update:

I configured phpstorm for debugging but Just I can use debug and select one of page to debug.I checked all the settings steps that were done correctly But The step by step debug buttons is'nt active such as stepOver and step intro and else... In addition, after debugging the codes, the error :   PHP Warning: include_once(): Failed opening '.\dref.php' for inclusion (include_path='.;C:\php\pear') in C:\wamp\www\srn\mrt\req_v.php on line 260

  is displayed, while the same code works well in the wamp by Firefox

What should I do to solve this problem?

答:
One of the most powerful and useful tools any developer could have is a debugger. I use xDebug myself. With it you can step through a program during execution and watch each method call, every variable value change, and every action the program does. With PHPStorm it is typically very easy to enable / use xDebug. This would be my recommendation for troubleshooting the issue you have.

References:
https://www.jetbrains.com/help/phpstorm/configuring-xdebug.html

https://confluence.jetbrains.com/display/PhpStorm/Zero-configuration+Web+Application+Debugging+with+Xdebug+and+PhpStorm

https://confluence.jetbrains.com/display/PhpStorm/Xdebug+Installation+Guide


问:
Is there a library to perform reflection on .Net objects based on a string?
I'm looking for a library that would allow you to perform reflection on an object using a string, e.g.

class SampleClass {
    public SampleClass Child {get; set;}
    public string SomeValue {get;set;}
}
var a = new SampleClass { Child = new SampleClass { SomeValue = "v"}};
var parser = new ReflectionParser();
var result = parser.Parse("Child.SomeValue", a);
// result is "v"
```

If not, I'm considering writing one and open sourcing it - but I didn't want to re-invent the wheel. Initially it would just get property values, but in the longer term I could see it gaining the ability to running methods, parsing arguments as need be.

The closest I have found is an XPath style library https://code.google.com/archive/p/antix-software/wikis/AntixReflectionQuery.wiki referenced in Using an XPath-style Query with Reflection and Traversing an arbitrary C# object graph using XPath/applying XSL transforms - however this doesn't appear to be available any more.

答:
The .NET base class library contains a DataBinder class which does exactly what you want.

It was designed for ASP.NET WebForms databinding, so it's in the System.Web.UI namespace and requires a reference to System.Web. But don't let that stop you, it can be used outside of web projects just as well.

```<code>class SampleClass
{
    public SampleClass Child { get; set; }
    public SampleClass[] Children { get; set; }
    public string SomeValue { get; set; }
}

var a = new SampleClass { Child = new SampleClass { SomeValue = "v" } };

var result = DataBinder.Eval(a, "Child.SomeValue");
Console.WriteLine(result); // yields v
</code>```

DataBinder also supports indexing over collections, so Children[0].SomeValue would also be evaluated correctly:

```<code>var a = new SampleClass { Children = new SampleClass[] { new SampleClass { SomeValue = "v" } } };

var result = DataBinder.Eval(a, "Children[0].SomeValue");
Console.WriteLine(result); // yields v
</code>```

Body:
I'm looking for a library that would allow you to perform reflection on an object using a string, e.g.

class SampleClass {
    public SampleClass Child {get; set;}
    public string SomeValue {get;set;}
}
var a = new SampleClass { Child = new SampleClass { SomeValue = "v"}};
var parser = new ReflectionParser();
var result = parser.Parse("Child.SomeValue", a);
// result is "v"

If not, I'm considering writing one and open sourcing it - but I didn't want to re-invent the wheel. Initially it would just get property values, but in the longer term I could see it gaining the ability to running methods, parsing arguments as need be.

The closest I have found is an XPath style library https://code.google.com/archive/p/antix-software/wikis/AntixReflectionQuery.wiki referenced in Using an XPath-style Query with Reflection and Traversing an arbitrary C# object graph using XPath/applying XSL transforms - however this doesn't appear to be available any more.

Body:
The .NET base class library contains a DataBinder class which does exactly what you want.

It was designed for ASP.NET WebForms databinding, so it's in the System.Web.UI namespace and requires a reference to System.Web. But don't let that stop you, it can be used outside of web projects just as well.

class SampleClass
{
    public SampleClass Child { get; set; }
    public SampleClass[] Children { get; set; }
    public string SomeValue { get; set; }
}

var a = new SampleClass { Child = new SampleClass { SomeValue = "v" } };

var result = DataBinder.Eval(a, "Child.SomeValue");
Console.WriteLine(result); // yields v

DataBinder also supports indexing over collections, so Children[0].SomeValue would also be evaluated correctly:

var a = new SampleClass { Children = new SampleClass[] { new SampleClass { SomeValue = "v" } } };

var result = DataBinder.Eval(a, "Children[0].SomeValue");
Console.WriteLine(result); // yields v


问:
Json POST request works in java but not PHP?
I have an odd problem that i cannot seem to solve at all. We have a rest service that is supposed to accept submission data as a JSON object.

I have been going round in circles using curl. The command works with any service off the corporate network, and any EXTERNAL one when i use the curl proxy option but nothing is accessible (get or post) on the internal network. I always get a "false" comming back  as response. Here is the PHP code:

```<code>$data_string =  "{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}";
$ch = curl_init('http://xxx.xxx.com/fashionnewssignup');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
//curl_setopt($ch, CURLOPT_PROXY, "http://proxy.xxxx.com");
//curl_setopt($ch, CURLOPT_PROXYPORT, "8080");
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, CRED);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 50);

//execute post
$result = curl_exec($ch);
echo "```";
var_dump( curl_getinfo($ch) ) . '
';
echo curl_errno($ch) . '
';
echo curl_error($ch) . '
';
//close connection
curl_close($ch);
var_dump ($result);
die;
```

<hr>

<h2>and it's output:</h2>

```array(26) {
  'url' =>
  string(59) "http://xxx.xxx.com/fashionnewssignup"
  'content_type' =>
  NULL
  'http_code' =>
  int(0)
  'header_size' =>
  int(0)
  'request_size' =>
  int(251)
  'filetime' =>
  int(-1)
  'ssl_verify_result' =>
  int(0)
  'redirect_count' =>
  int(0)
  'total_time' =>
  double(0.031)
  'namelookup_time' =>
  double(0)
  'connect_time' =>
  double(0.016)
  'pretransfer_time' =>
  double(0.016)
  'size_upload' =>
  double(0)
  'size_download' =>
  double(0)
  'speed_download' =>
  double(0)
  'speed_upload' =>
  double(0)
  'download_content_length' =>
  double(-1)
  'upload_content_length' =>
  double(-1)
  'starttransfer_time' =>
  double(0.031)
  'redirect_time' =>
  double(0)
  'redirect_url' =>
  string(0) ""
  'primary_ip' =>
  string(12) "XX.XX.XXX.12"
  'certinfo' =>
  array(0) {
  }
  'primary_port' =>
  int(1080)
  'local_ip' =>
  string(13) "XX.XX.XXX.196"
  'local_port' =>
  int(56107)
}
52
Empty reply from server
C:\xampp\htdocs\at\test.php:46:
bool(false)

Process finished with exit code 0
```

<hr>

<p>"Empty reply from server" 52 is what i get regardless of what URL i feed in. As i said above this code works fine off the network with other sites.</p>

<p>A git-bash curl gives this:</p>

```    curl -H "Content-Type: application/json" -X POST -d '{"fashionNewsSignups":[{"                                    corporateBrandId":0,"vendorId":null,"countryCode":"pt","languageCode":"pt","emai                                    l":"test@ytDessddefwwt.com","genderCode":0,"hasChildren":0,"zipcode":"12345"}]}'                                     http://xxx.xxx.com/fashionnewssignup
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   184    0     0  100   184      0   5935 --:--:-- --:--:-- --:--:-- 12266
curl: (52) Empty reply from server
```

<p><strong>The strange part is, when i try the same thing in JAVA on the same machine on the same network using this code, it works 100% fine, no proxy or anything required.</strong></p>

<p>This JAVA code works:</p>

```HttpClient httpClient = new DefaultHttpClient();

try {
    HttpPost request = new HttpPost("http://xxx.xxx.com/fashionnewssignup");
    StringEntity params =new StringEntity("{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}");
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
    String s = response.getStatusLine()+" " + response.toString();
    System.out.println(s);
}catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}
```

Anyone know what i am doing wrong? The service i am trying to access is written in JAVA if that is important :/

答:
Ok solved in the end, it was down to needing this line:

```<code>curl_setopt($ch, CURLOPT_NOPROXY , 'xxx.xxx.com');
</code>```

for anyone having the same issue :)

I did not try it because it was not in the list of constants in curl_d.php, and intelliJ reports that the "constant is undefined"
... but it works?!? :o
-who knew lol.

Body:
I have an odd problem that i cannot seem to solve at all. We have a rest service that is supposed to accept submission data as a JSON object.

I have been going round in circles using curl. The command works with any service off the corporate network, and any EXTERNAL one when i use the curl proxy option but nothing is accessible (get or post) on the internal network. I always get a "false" comming back  as response. Here is the PHP code:

$data_string =  "{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}";
$ch = curl_init('http://xxx.xxx.com/fashionnewssignup');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
//curl_setopt($ch, CURLOPT_PROXY, "http://proxy.xxxx.com");
//curl_setopt($ch, CURLOPT_PROXYPORT, "8080");
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, CRED);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 50);

//execute post
$result = curl_exec($ch);
echo "
";
var_dump( curl_getinfo($ch) ) . '
';
echo curl_errno($ch) . '
';
echo curl_error($ch) . '
';
//close connection
curl_close($ch);
var_dump ($result);
die;

and it's output:

array(26) {
  'url' =>
  string(59) "http://xxx.xxx.com/fashionnewssignup"
  'content_type' =>
  NULL
  'http_code' =>
  int(0)
  'header_size' =>
  int(0)
  'request_size' =>
  int(251)
  'filetime' =>
  int(-1)
  'ssl_verify_result' =>
  int(0)
  'redirect_count' =>
  int(0)
  'total_time' =>
  double(0.031)
  'namelookup_time' =>
  double(0)
  'connect_time' =>
  double(0.016)
  'pretransfer_time' =>
  double(0.016)
  'size_upload' =>
  double(0)
  'size_download' =>
  double(0)
  'speed_download' =>
  double(0)
  'speed_upload' =>
  double(0)
  'download_content_length' =>
  double(-1)
  'upload_content_length' =>
  double(-1)
  'starttransfer_time' =>
  double(0.031)
  'redirect_time' =>
  double(0)
  'redirect_url' =>
  string(0) ""
  'primary_ip' =>
  string(12) "XX.XX.XXX.12"
  'certinfo' =>
  array(0) {
  }
  'primary_port' =>
  int(1080)
  'local_ip' =>
  string(13) "XX.XX.XXX.196"
  'local_port' =>
  int(56107)
}
52
Empty reply from server
C:\xampp\htdocs\at\test.php:46:
bool(false)

Process finished with exit code 0

"Empty reply from server" 52 is what i get regardless of what URL i feed in. As i said above this code works fine off the network with other sites.

A git-bash curl gives this:

    curl -H "Content-Type: application/json" -X POST -d '{"fashionNewsSignups":[{"                                    corporateBrandId":0,"vendorId":null,"countryCode":"pt","languageCode":"pt","emai                                    l":"test@ytDessddefwwt.com","genderCode":0,"hasChildren":0,"zipcode":"12345"}]}'                                     http://xxx.xxx.com/fashionnewssignup
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   184    0     0  100   184      0   5935 --:--:-- --:--:-- --:--:-- 12266
curl: (52) Empty reply from server

The strange part is, when i try the same thing in JAVA on the same machine on the same network using this code, it works 100% fine, no proxy or anything required.

This JAVA code works:

HttpClient httpClient = new DefaultHttpClient();

try {
    HttpPost request = new HttpPost("http://xxx.xxx.com/fashionnewssignup");
    StringEntity params =new StringEntity("{\"fashionSignups\":[{\"corporateBrandId\":0,\"vendorId\":null,\"countryCode\":\"pt\",\"languageCode\":\"pt\",\"email\":\"test@ytDessddefwwt.com\",\"genderCode\":0,\"hasChildren\":0,\"zipcode\":\"12345\"}]}");
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
    String s = response.getStatusLine()+" " + response.toString();
    System.out.println(s);
}catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}

Anyone know what i am doing wrong? The service i am trying to access is written in JAVA if that is important :/

Body:
Ok solved in the end, it was down to needing this line:

curl_setopt($ch, CURLOPT_NOPROXY , 'xxx.xxx.com');

for anyone having the same issue :)

I did not try it because it was not in the list of constants in curl_d.php, and intelliJ reports that the "constant is undefined"
... but it works?!? :o
-who knew lol.


问:
How to ensure Makefile variable is set as a prerequisite?
A Makefile deploy recipe needs an environment variable ENV to be set to properly execute itself, whereas other recipes don't care, e.g.,

```<code>ENV =

.PHONY: deploy hello

deploy:
    rsync . $(ENV).example.com:/var/www/myapp/

hello:
    echo "I don't care about ENV, just saying hello!"
</code>```

How can I make sure this ENV variable is set? Is there a way to declare this makefile variable as a prerequisite of the deploy recipe? e.g.,

```<code>deploy: make-sure-ENV-variable-is-set
</code>```

答:
You can use ifdef instead of a different target.

```<code>.PHONY: deploy
deploy:
ifdef ENV
    rsync . $(ENV).example.com:/var/www/myapp/
else
    @echo 1>&2 "ENV must be set"
        false                            # Cause deploy to fail
endif
</code>```

Body:
A Makefile deploy recipe needs an environment variable ENV to be set to properly execute itself, whereas other recipes don't care, e.g.,

ENV =

.PHONY: deploy hello

deploy:
    rsync . $(ENV).example.com:/var/www/myapp/

hello:
    echo "I don't care about ENV, just saying hello!"

How can I make sure this ENV variable is set? Is there a way to declare this makefile variable as a prerequisite of the deploy recipe? e.g.,

deploy: make-sure-ENV-variable-is-set

Body:
You can use ifdef instead of a different target.

.PHONY: deploy
deploy:
ifdef ENV
    rsync . $(ENV).example.com:/var/www/myapp/
else
    @echo 1>&2 "ENV must be set"
        false                            # Cause deploy to fail
endif


问:
Enable underscores in headers on Azure ingress
I have a problem with headers not forwarded into my services, I am not sure how support for Ingress was added, however I have the following Ingress service:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: my-ingress
  annotations:
    ingress.kubernetes.io/rewrite-target: /
    "nginx.org/proxy-pass-headers": "custom_header"
spec:
  rules:
  - host: myingress.westus.cloudapp.azure.com
    http:
      paths:
      - path: /service1
        backend:
          serviceName: service1
          servicePort: 8080
</code>```

However, my custom_header will not be forwarded. In nginx I set underscores_in_headers:

```<code>underscores_in_headers on;
</code>```

How can I add this configuration into my ingress nginx service?

Thanks.

答:
According to ingress configmap spec you can use this header directly in configspec e.g.:

```<code>apiVersion: v1
data:
  enable-underscores-in-headers: "on"
kind: ConfigMap
metadata:
  name: nginx-configuration
  namespace: ingress-nginx
  labels:
    app: ingress-nginx

kubectl apply -f configmap.yml
</code>```

Also there is an example of setting custom headers
Did you try that?

Body:
I have a problem with headers not forwarded into my services, I am not sure how support for Ingress was added, however I have the following Ingress service:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: my-ingress
  annotations:
    ingress.kubernetes.io/rewrite-target: /
    "nginx.org/proxy-pass-headers": "custom_header"
spec:
  rules:
  - host: myingress.westus.cloudapp.azure.com
    http:
      paths:
      - path: /service1
        backend:
          serviceName: service1
          servicePort: 8080

However, my custom_header will not be forwarded. In nginx I set underscores_in_headers:

underscores_in_headers on;

How can I add this configuration into my ingress nginx service?

Thanks.

Body:
According to ingress configmap spec you can use this header directly in configspec e.g.:

apiVersion: v1
data:
  enable-underscores-in-headers: "on"
kind: ConfigMap
metadata:
  name: nginx-configuration
  namespace: ingress-nginx
  labels:
    app: ingress-nginx

kubectl apply -f configmap.yml

Also there is an example of setting custom headers
Did you try that?


问:
Synchronize data 2 times per day in Android
I have a server which stores dynamically changing data. My app after launching is connecting to the server and gets this data but I'm updating it manually. So I need to automatically synchronize server and get updated data at least 2 times per day. Any suggestions how to do it?

P.S. I'm getting data from server in json format using gson google lib.

P.P.S. As I understood I need to use Sync Adapter but I really don't know how to do it.

答: You should use an Alarm Manager when you first start your application, register your Alarm Manager to fire setting the "repeat" flag to 12 hours. Then register a receiver for that alarm, and when the Broadcast Receiver recives the intent, make it start a service that handles your server connection.</p>


问:
Gradle Project Sync Failed Android Studio 3.0 (JDK 9.0.1)
I tried all solutions to fix it, but nothing has succeeded. (Turned gradle to "offline work", deleted .gradle files, invalidated and restarted. I also removed the jdk-android studio completely and installed again.)

Here is the problem's screenshot:
Android Studio 3.0 Gradle Sync Problem

Here is my java version

and here is the system/log file:

答:
You can open build.gradle file in Android studio, then change compileSdkVersion ,  buildToolsVersion dependencies like this

```<code>android {
compileSdkVersion 23
buildToolsVersion "24.0.1"
....
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
</code>```

}

If you did not understood it, can you please share screen shots of your build.gradle file ?
Which is in left side of android studio, under Gradle Scripts -> build.gradle (Modual:app)

Body:
You can open build.gradle file in Android studio, then change compileSdkVersion ,  buildToolsVersion dependencies like this

android {
compileSdkVersion 23
buildToolsVersion "24.0.1"
....
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'

}

If you did not understood it, can you please share screen shots of your build.gradle file ?
Which is in left side of android studio, under Gradle Scripts -> build.gradle (Modual:app)


问:
Please explain this base 62 PHP conversion function/algorithm
Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

```<code>private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}
</code>```

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.

答:
Hope this helps.</p>

```<code>// Define a set of allowable characters
private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

// Function declaration
private static function _convertBase($num)
{
    $base = strlen(self::$_characters); // Count the number of characters available
    $string = '';                       // Initialize an empty string

    // Start the iterator off as (num / character count). Continue until it is zero.
    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));              // Find the numeric (0-$base) position of the corresponding character.
        $string .= substr(self::$_characters, $a, 1);   // Pull that character out and add it to the return string
        $num = $num - ($a * pow($base, $t));            // Subtract it from $num
    }

    return $string;                    // Return the encoded string
}
</code>```

Body:
Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.

Body:
Hope this helps.

// Define a set of allowable characters
private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

// Function declaration
private static function _convertBase($num)
{
    $base = strlen(self::$_characters); // Count the number of characters available
    $string = '';                       // Initialize an empty string

    // Start the iterator off as (num / character count). Continue until it is zero.
    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));              // Find the numeric (0-$base) position of the corresponding character.
        $string .= substr(self::$_characters, $a, 1);   // Pull that character out and add it to the return string
        $num = $num - ($a * pow($base, $t));            // Subtract it from $num
    }

    return $string;                    // Return the encoded string
}