问:
What is the most efficent way to filter an object with an array of arrays?
I'm trying to filter an Object by an array of arrays, getting back an array of objects.

Like this:

 let obj =
{
  "a.1":1,
  "a.2":2,
  "b.1":3,
  "b.2":4,
  "c.1":5,
  "c.2":6
}

let array =
[
  ["a.1","b.1"],
  ["a"],
  ["b","c.1"]
]

let expectedResult =
[
  {
    "a.1":1,
    "b.1":3,
  },
  {
    "a.1":1,
    "a.2":2,
  },
  {
    "b.1":3,
    "b.2":4,
    "c.1":5
  },
]

// this is what I came up with
const filterObjectByArray = (obj, arr) =>
    Object.keys(obj)
    .filter(ch => {
        for (var index = 0; index < arr.length; index++)
            if (ch.startsWith(arr[index]))
                return true;
    })
    .reduce((ret, key) =>{
        ret[key] = obj[key]
        return ret
    },{})

let result = array.map(arr => filterObjectByArray(obj, arr))

//kind of deepEqual
console.log(JSON.stringify(expectedResult) == JSON.stringify(result))```

Is there a easier or more convenient way to do that? I need to do this operation quite often and my object will be up to couple hundreds entries big, so I see a potential bottleneck here.

答:
I would create a one type mapping of the "base" (the letter) to the "real" keys, and then use it to translate the letter to the real keys when create the object.

const obj = {
  "a.1": 1,
  "a.2": 2,
  "b.1": 3,
  "b.2": 4,
  "c.1": 5,
  "c.2": 6
};

const array = [
  ["a.1", "b.1"],
  ["a"],
  ["b", "c.1"]
];

const getBaseKey = (key) => key.match(/^[a-z]+/)[0]; // get the base of the key - the letter. If it's only one letter, you can use key[0]

/** create a one time map of keys by their base **/
const oobjKeysMap = Object.keys(obj).reduce((map, key) => {
  const baseKey = getBaseKey(key);
  const curr = map.get(baseKey) || [];
  curr.push(key);
  return map.set(baseKey, curr);
}, new Map());

const result = array.map((sub) => // iterate the array
  [].concat(...sub.map((k) => k in obj ? k : oobjKeysMap.get(getBaseKey(k)))) // create the least of "real" keys
  .reduce((ret, key) => { // create the object
    ret[key] = obj[key];
    return ret;
  }, {})
);

console.log(result);```

Body:
I'm trying to filter an Object by an array of arrays, getting back an array of objects.

Like this:

 let obj =
{
  "a.1":1,
  "a.2":2,
  "b.1":3,
  "b.2":4,
  "c.1":5,
  "c.2":6
}

let array =
[
  ["a.1","b.1"],
  ["a"],
  ["b","c.1"]
]

let expectedResult =
[
  {
    "a.1":1,
    "b.1":3,
  },
  {
    "a.1":1,
    "a.2":2,
  },
  {
    "b.1":3,
    "b.2":4,
    "c.1":5
  },
]

// this is what I came up with
const filterObjectByArray = (obj, arr) =>
    Object.keys(obj)
    .filter(ch => {
        for (var index = 0; index < arr.length; index++)
            if (ch.startsWith(arr[index]))
                return true;
    })
    .reduce((ret, key) =>{
        ret[key] = obj[key]
        return ret
    },{})

let result = array.map(arr => filterObjectByArray(obj, arr))

//kind of deepEqual
console.log(JSON.stringify(expectedResult) == JSON.stringify(result))

Is there a easier or more convenient way to do that? I need to do this operation quite often and my object will be up to couple hundreds entries big, so I see a potential bottleneck here.


来源: stackexchange

问:
How do you use CSS grid layouts with React effectively?
I'm currently building a Single Page Application using ReactJs and CSS grid layouts for the placement and styling of components.

However, the two technologies don't feel like they go together well: CSS grid layouts can only (easily) be applied to children elements (grid items) of the parent container. But the very nature of ReactJS means components with grand-children components and even great-grand-children are common.

As an example:

React component tree: App > ToDoList > ToDo Item > Details...

If, onClick, I want to move the 'ToDo Item' to grid-row: 1 of the 'App' component it seems the only way to do so is for ToDoList to itself be a grid of the entire App component. This then causes layout issues of other elements on the page.

Am I right in thinking these two approaches don't play well together, or is it a flaw in my understanding of the two technologies?

答:
You're right, subgrids were deprecated from the CSS Grid Candidate Recommendation (https://github.com/w3c/csswg-drafts/issues/958).

Hopefully they'll reappear, they seem really useful for simplifying complicated layouts.   I've only found CSS grid to be useful laying out the top level of an react application or a container.

ContentLicense: CC BY-SA 3.0


问:
Insert "-" in the name of all files in a folder at position 4 and 6
I got a bunch of PDFs in a folder which must be renamed. They are all built like this: YYYYMMDD_Text.pdf. The system is Windows 7.

I want to insert a - between the dates, so the documents look like:
YYYY-MM-DD_Text.pdf.

This is what I got, but it's not working and I searched a dozen threads but could not find the solution:

```<code>    Ordner = "C:\xte Stelle\Test Doku"

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set Fld = fso.GetFolder(Ordner)

    For i = 0 To UBound(Arr)
        WScript.Echo i & vbTab & Arr(i)
    Next

    For Each File In Folder.Files
        File.Name = Left(File.Name, 4) & "-" & Mid(File.Name, 6) & "-" & Mid(File.Name, 8)
End Sub
</code>```

Edit:

This is what I got now. I can run it and it does not crash, but does not function either. It simply does nothing. Any idea on that?

```<code>Ordner = "C:\xte Stelle\Test Doku"

Set fso = CreateObject("Scripting.FileSystemObject")
Set Fld = fso.GetFolder(Ordner)

Sub test
    For Each File In Fld.Files
        File.Name = Left(File.Name, 4) & "-" & Mid(File.Name, 5, 2) & "-" & Mid(File.Name, 7)
    Next
End Sub
</code>```

答:
Your code is not only incomplete, but downright broken.

You have an End Sub without a corresponding Sub.

You assign a folder object to the variable Fld, but then enumerate files from a variable Folder.

Your second For Each loop is missing a Next.

The Mid function returns the number of characters defined by the third parameter starting from the position defined by the second parameter. If the third parameter is omitted the substring from the position defined by the third parameter to the end of the string will be returned. Hence your filename reconstruction should look like this:

```<code>File.Name = Left(File.Name, 4) & "-" & Mid(File.Name, 5, 2) & "-" & Mid(File.Name, 7)
</code>```

Note: if you put your code in a procedure or function you need to actually invoke that procedure/function to get the code executed.

Body:
I got a bunch of PDFs in a folder which must be renamed. They are all built like this: YYYYMMDD_Text.pdf. The system is Windows 7.

I want to insert a - between the dates, so the documents look like:
YYYY-MM-DD_Text.pdf.

This is what I got, but it's not working and I searched a dozen threads but could not find the solution:

    Ordner = "C:\xte Stelle\Test Doku"

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set Fld = fso.GetFolder(Ordner)

    For i = 0 To UBound(Arr)
        WScript.Echo i & vbTab & Arr(i)
    Next

    For Each File In Folder.Files
        File.Name = Left(File.Name, 4) & "-" & Mid(File.Name, 6) & "-" & Mid(File.Name, 8)
End Sub

Edit:

This is what I got now. I can run it and it does not crash, but does not function either. It simply does nothing. Any idea on that?

Ordner = "C:\xte Stelle\Test Doku"

Set fso = CreateObject("Scripting.FileSystemObject")
Set Fld = fso.GetFolder(Ordner)

Sub test
    For Each File In Fld.Files
        File.Name = Left(File.Name, 4) & "-" & Mid(File.Name, 5, 2) & "-" & Mid(File.Name, 7)
    Next
End Sub

Body:
Your code is not only incomplete, but downright broken.

You have an End Sub without a corresponding Sub.

You assign a folder object to the variable Fld, but then enumerate files from a variable Folder.

Your second For Each loop is missing a Next.

The Mid function returns the number of characters defined by the third parameter starting from the position defined by the second parameter. If the third parameter is omitted the substring from the position defined by the third parameter to the end of the string will be returned. Hence your filename reconstruction should look like this:

File.Name = Left(File.Name, 4) & "-" & Mid(File.Name, 5, 2) & "-" & Mid(File.Name, 7)

Note: if you put your code in a procedure or function you need to actually invoke that procedure/function to get the code executed.


问:
What is the use of "," in while loop condition c++?
```<code>string command;
string bookName;
while (cin >> command, command != "END")
{...}
</code>```

Here in while loop's condition, there is a comma.
I know that multiple conditions can be added using && or ||.

But why use ,?

Is there any certain benefits? Can you please explain the usage and syntax?

答:
It's the comma operator, also known as the "evaluate and forget" operator. The effect of a, b is:

Evaluate a, including any side effects

Discard its value (i.e. do nothing with it)

Evaluate b

Use the result of b as the result of the entire expression a, b

The author of the loop wanted to express the following:

Read command from cin, and then enter the loop body unless command is equal to "END"

However, they would have been better off using && instead of , here, because cin >> command can fail (i.e. if the end of input is reached before the word END is found). In such case, the condition with , will not do what was intended (it will likely loop forever, as command will never receive the value END), while the condition with && would do the right thing (terminate).

Body:
string command;
string bookName;
while (cin >> command, command != "END")
{...}

Here in while loop's condition, there is a comma.
I know that multiple conditions can be added using && or ||.

But why use ,?

Is there any certain benefits? Can you please explain the usage and syntax?


问:
scraping data from websites with scrapy and output to javascript
I want to build a simple chatbot (with nodejs) that scrapes data from websites to users by using scrapy (python framework). My problem is how does my nodejs app gets the scraped data from the scrapy framework. </p>

答: Use a node equivalent of scrapy or another node module like the built in http (recommended).</p>


问:
getting a list of data in a specific manner using iterator
I am having these list of data from the database

```<code>Level 1
Level 2
Level 3
will get 100 points
will get 200 points
will get 300 points
</code>```

My java code:

```<code>List ln5 = readDB(iStepNumber, status, query5);
Iterator itr5 = ln5.iterator();
while (itr5.hasNext()) {
   String Levels1 = (String) itr5.next();
   String LevelsDescription1 = (String) itr5.next();
   String Levels2 = (String) itr5.next();
   String LevelsDescription2 = (String) itr5.next();
   String Levels3 = (String) itr5.next();
   String LevelsDescription3 = (String) itr5.next();
}
</code>```

I need to get the data as follows,

```<code>Level 1
will get 100 points
Level 2
will get 200 points
Level 3
will get 300 points
</code>```

Any Suggestion Plz?

答:
Suggestion 1 : Change the way you stock your datas. It's a strange way to do it

Suggestion 2 : If you can't change, then use a for on the list

```<code>for(int i = 0;i< ln5.size()/2;i++){
    System.out.println(ln5.get(i));
    System.out.println(ln5.get(i+ln5.size()/2));
}
</code>```

Body:
I am having these list of data from the database

Level 1
Level 2
Level 3
will get 100 points
will get 200 points
will get 300 points

My java code:

List ln5 = readDB(iStepNumber, status, query5);
Iterator itr5 = ln5.iterator();
while (itr5.hasNext()) {
   String Levels1 = (String) itr5.next();
   String LevelsDescription1 = (String) itr5.next();
   String Levels2 = (String) itr5.next();
   String LevelsDescription2 = (String) itr5.next();
   String Levels3 = (String) itr5.next();
   String LevelsDescription3 = (String) itr5.next();
}

I need to get the data as follows,

Level 1
will get 100 points
Level 2
will get 200 points
Level 3
will get 300 points

Any Suggestion Plz?

Body:
Suggestion 1 : Change the way you stock your datas. It's a strange way to do it

Suggestion 2 : If you can't change, then use a for on the list

for(int i = 0;i< ln5.size()/2;i++){
    System.out.println(ln5.get(i));
    System.out.println(ln5.get(i+ln5.size()/2));
}


问:
Give different ID to each element in for loop
I have a far loop which check the number and output the result to number of that.

For exmaple, in below picture the "cut image" is displayed in multiples times. I have  tag in the far loop so it outputs the image according to number of times. And that number come from database.

MY Question.
Obviously all the images in first row will have same ID. Currently user can only click the first image of the row. I would like to give each element different ID  if possible. Than I would like to use JQuery to add click event. So if I click on 4th image in first row, it alert message and if i click 5th image it shows different alert message.

How I can assign different ID to each element in far loop so  it does only make first Image clickable but instead all elements clickable.

My loop

```<code> <table class="table table-bordered">
    <thead>
    <tbody>
      <tr>
        <?php
        for($x=0; $x < $row['noof10s_vnr']; $x++){
            ?>

            <td><img alt="" class="yellow-process center-block " id ="cut-full-roll-<?php echo $row['id_vnr']; ?>" name="<?php echo $row['id_vnr']; ?>" src="../../css/icons/vinyl-rolls/cut.png"></td>
        <?php
        }
        ?>

      </tr>
    </tbody>
  </table>
</code>```

My jquery selector
If I can give each element different ID, than I can do something like this to add clicked event to clicked image.

```<code>jQuery( "#vinyl-roll-down-<?php echo $row['id_vnr']; ?>" ).click(function() {
</code>```

But I need help assign different unique to each element in far loop.

Thanks in advance.

答:
You can try this

In html:

```<code><table class="table table-bordered">
    <thead>
    <tbody>
    <tr>
        <?php
        for($x=0; $x < $row['noof10s_vnr']; $x++){
        ?>
        <td><img id="image{{$x}}" alt="" class="yellow-process center-block " onclick="imageClick(<?php echo $row['id_vnr']; ?>)" name="<?php echo $row['id_vnr']; ?>" src="../../css/icons/vinyl-rolls/cut.png"></td>
        <?php
        }
        ?>

    </tr>
    </tbody>
</table>
</code>```

in jquery

```<code>function imageClick(id) {
    alert(id);
  var imageId = jQuery(this).attr("id");
   alert(imageId);
//    your code
}
</code>```

I thigh it will help you.

Body:
I have a far loop which check the number and output the result to number of that.

For exmaple, in below picture the "cut image" is displayed in multiples times. I have  tag in the far loop so it outputs the image according to number of times. And that number come from database.

MY Question.
Obviously all the images in first row will have same ID. Currently user can only click the first image of the row. I would like to give each element different ID  if possible. Than I would like to use JQuery to add click event. So if I click on 4th image in first row, it alert message and if i click 5th image it shows different alert message.

How I can assign different ID to each element in far loop so  it does only make first Image clickable but instead all elements clickable.

My loop

        <?php
        for($x=0; $x < $row['noof10s_vnr']; $x++){
            ?>

            <img alt="" class="yellow-process center-block " id ="cut-full-roll-<?php echo $row['id_vnr']; ?>" name="<?php echo $row['id_vnr']; ?>" src="../../css/icons/vinyl-rolls/cut.png">
        <?php
        }
        ?>

My jquery selector
If I can give each element different ID, than I can do something like this to add clicked event to clicked image.

jQuery( "#vinyl-roll-down-<?php echo $row['id_vnr']; ?>" ).click(function() {

But I need help assign different unique to each element in far loop.

Thanks in advance.

Body:
You can try this

In html:

<table class="table table-bordered">
    <thead>
    <tbody>
    <tr>
        <?php
        for($x=0; $x < $row['noof10s_vnr']; $x++){
        ?>
        <td><img id="image{{$x}}" alt="" class="yellow-process center-block " onclick="imageClick(<?php echo $row['id_vnr']; ?>)" name="<?php echo $row['id_vnr']; ?>" src="../../css/icons/vinyl-rolls/cut.png"></td>
        <?php
        }
        ?>

    </tr>
    </tbody>
</table>

in jquery

function imageClick(id) {
    alert(id);
  var imageId = jQuery(this).attr("id");
   alert(imageId);
//    your code
}

I thigh it will help you.


问:
window.location = window.location not work in IE7
To refresh the page I am using window.location = window.location it works fine with FireFox but not with IE7

any Idea??

Thanx

答:
Call the reload method instead</p>

```<code>location.reload(true)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Call the reload method instead

location.reload(true)


问:
.net mvc data annotation model state return always true
When I post an invalid serial, its set to ""(empty string) and I expect ModelState.isValid is false but it returns true.. here is my code.

```<code>        private string _tcno { get; set; }

        [Required(ErrorMessage = "Enter serial")]
        [StringLength(11, MinimumLength = 11, ErrorMessage="Invalid Serial Number")]
        [Column(TypeName = "nchar")]
        public string TCNO
        {
            get { return _tcno ?? ""; }
            set {
                 value = value ?? "";
                 _tcno = value.IsValidTC() ? value : "";
            }
        }
</code>```

I trust min 11 length validation why ModelState.isValid is true here?

答:
Woking copy below is using my validation method and sets '-' if its invalid serial number, this way validatior error message is as I expected.</p>

```<code>private string _tcno { get; set; }
        [Required(ErrorMessage = "Enter Serial")]
        [StringLength(11, MinimumLength = 11, ErrorMessage="Invalid Serial Number.")]
        [Column(TypeName = "nchar")]
        public string TCNO
        {
            get { return _tcno ?? ""; }
            set {
                value = value.IsValidTC() ? value : "-";
                _tcno = value;
            }
        }
</code>```

Body:
When I post an invalid serial, its set to ""(empty string) and I expect ModelState.isValid is false but it returns true.. here is my code.

        private string _tcno { get; set; }

        [Required(ErrorMessage = "Enter serial")]
        [StringLength(11, MinimumLength = 11, ErrorMessage="Invalid Serial Number")]
        [Column(TypeName = "nchar")]
        public string TCNO
        {
            get { return _tcno ?? ""; }
            set {
                 value = value ?? "";
                 _tcno = value.IsValidTC() ? value : "";
            }
        }

I trust min 11 length validation why ModelState.isValid is true here?

Body:
Woking copy below is using my validation method and sets '-' if its invalid serial number, this way validatior error message is as I expected.

private string _tcno { get; set; }
        [Required(ErrorMessage = "Enter Serial")]
        [StringLength(11, MinimumLength = 11, ErrorMessage="Invalid Serial Number.")]
        [Column(TypeName = "nchar")]
        public string TCNO
        {
            get { return _tcno ?? ""; }
            set {
                value = value.IsValidTC() ? value : "-";
                _tcno = value;
            }
        }


问:
Laravel Echo BroadcastException in PusherBroadcaster.php line 106: Unknown auth_key
I am getting Unknown auth_key error when trying to broadcast an event. I tried changing my cluster as mentioned in other posts but not working. I have uncommented broadcast service provider in app.php.

.env

```<code>PUSHER_APP_ID=******
PUSHER_APP_KEY=******
PUSHER_APP_SECRET=******
</code>```

config/broadcasting

```<code> 'pusher' => [
  'driver' => 'pusher',
  'key' => env('PUSHER_APP_KEY'),
  'secret' => env('PUSHER_APP_SECRET'),
  'app_id' => env('PUSHER_APP_ID'),
  'options' => [
   ],
],
</code>```

\app\Events\MessagePosted.php

```<code>public function broadcastOn() {
  return new PresenceChannel('chatroom');
 }
</code>```

\resources\assets\js\bootstrap.js

```<code>window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

import Echo from "laravel-echo"
window.Pusher = require('pusher-js');
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '*****',
    cluster: 'ap2',
    encrypted: true
});
</code>```

\resources\assets\js\app.js

```<code>const app = new Vue({
    el: '#app',
    data: {
        messages: [],
        usersInRoom: []
    },
    methods: {
        addMessage(message) {
            // Add to existing messages
            this.messages.push(message);

            // Persist to the database etc
            axios.post('/messages', message).then(response => {
                // Do whatever;
            })
        }
    },
    created() {
        axios.get('/messages').then(response => {
            this.messages = response.data;
        });
        Echo.join('chatroom')
                .here((users) => {
                    this.usersInRoom = users;
                })
                .joining((user) => {
                    this.usersInRoom.push(user);
                })
                .leaving((user) => {
                    this.usersInRoom = this.usersInRoom.filter(u => u != user)
                })
                .listen('MessagePosted', (e) => {
                    this.messages.push({
                        message: e.message.message,
                        user: e.user
                    });
                });
    }
});
</code>```

答:
in config/broadcasting add 'cluster' => 'us2',
                'encrypted' => true in 'options'

```<code>'pusher' => [
  'driver' => 'pusher',
  'key' => env('PUSHER_APP_KEY'),
  'secret' => env('PUSHER_APP_SECRET'),
  'app_id' => env('PUSHER_APP_ID'),
  'options' => [
       'cluster' => 'us2',
       'encrypted' => true
  ],
],
</code>```

Body:
I am getting Unknown auth_key error when trying to broadcast an event. I tried changing my cluster as mentioned in other posts but not working. I have uncommented broadcast service provider in app.php.

.env

PUSHER_APP_ID=******
PUSHER_APP_KEY=******
PUSHER_APP_SECRET=******

config/broadcasting

 'pusher' => [
  'driver' => 'pusher',
  'key' => env('PUSHER_APP_KEY'),
  'secret' => env('PUSHER_APP_SECRET'),
  'app_id' => env('PUSHER_APP_ID'),
  'options' => [
   ],
],

\app\Events\MessagePosted.php

public function broadcastOn() {
  return new PresenceChannel('chatroom');
 }

\resources\assets\js\bootstrap.js

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

import Echo from "laravel-echo"
window.Pusher = require('pusher-js');
window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '*****',
    cluster: 'ap2',
    encrypted: true
});

\resources\assets\js\app.js

const app = new Vue({
    el: '#app',
    data: {
        messages: [],
        usersInRoom: []
    },
    methods: {
        addMessage(message) {
            // Add to existing messages
            this.messages.push(message);

            // Persist to the database etc
            axios.post('/messages', message).then(response => {
                // Do whatever;
            })
        }
    },
    created() {
        axios.get('/messages').then(response => {
            this.messages = response.data;
        });
        Echo.join('chatroom')
                .here((users) => {
                    this.usersInRoom = users;
                })
                .joining((user) => {
                    this.usersInRoom.push(user);
                })
                .leaving((user) => {
                    this.usersInRoom = this.usersInRoom.filter(u => u != user)
                })
                .listen('MessagePosted', (e) => {
                    this.messages.push({
                        message: e.message.message,
                        user: e.user
                    });
                });
    }
});

Body:
in config/broadcasting add 'cluster' => 'us2',
                'encrypted' => true in 'options'

'pusher' => [
  'driver' => 'pusher',
  'key' => env('PUSHER_APP_KEY'),
  'secret' => env('PUSHER_APP_SECRET'),
  'app_id' => env('PUSHER_APP_ID'),
  'options' => [
       'cluster' => 'us2',
       'encrypted' => true
  ],
],


问:
Call a function on PHP file using jQuery
I have a php file (treatment.php) which contains some functions, for example :

```<code>public function connexion(){
    $user = 'invité';
    if($_POST){
        if(isset($_POST['user'])) {
            session_start();
            $user = $_POST['user'];
        }
    }
    echo $user;
}
</code>```

And I want to call this function via Ajax with the following code but it doesn't work :

```<code>$(document).on("click", "#valider-btn", function(){
  $.ajax({
    url : 'treatment.php/Connexion',
    type : 'POST',
    data : 'user=' + $("#name").val(),
    dataType : 'html',
    success : function(donnees) {
    $("#name").val("");
    $("#formulaire").hide();
    $("#decompte").html(donnees);
    }
  });
});
</code>```

So can someone help please ? Thanks

答:
You misunderstood PHP with JS.

You can call .php file, with executing code, but not function itself.
Best is to seperate PHP with treatment2.php:

```<code><?php
include_once "treatment.php";
connexion();
</code>```

And call this file instead.

Function itself is declaration - when you use this in PHP file, then you can execute that from outside.

Body:
I have a php file (treatment.php) which contains some functions, for example :

public function connexion(){
    $user = 'invité';
    if($_POST){
        if(isset($_POST['user'])) {
            session_start();
            $user = $_POST['user'];
        }
    }
    echo $user;
}

And I want to call this function via Ajax with the following code but it doesn't work :

$(document).on("click", "#valider-btn", function(){
  $.ajax({
    url : 'treatment.php/Connexion',
    type : 'POST',
    data : 'user=' + $("#name").val(),
    dataType : 'html',
    success : function(donnees) {
    $("#name").val("");
    $("#formulaire").hide();
    $("#decompte").html(donnees);
    }
  });
});

So can someone help please ? Thanks

Body:
You misunderstood PHP with JS.

You can call .php file, with executing code, but not function itself.
Best is to seperate PHP with treatment2.php:

<?php
include_once "treatment.php";
connexion();

And call this file instead.

Function itself is declaration - when you use this in PHP file, then you can execute that from outside.


问:
Angularjs Unexpected token JSON
I have a problem with angularjs and JSON.

This is my code.

list_user.jsp (this is the page where I print the table)

```<code><tr ng-repeat="per in persons">
  <td>{{ per.user }}</td>
  <td>{{ per.password }}</td>
  <td>{{ per.profile }}</td>
</tr>
</code>```

controller.js

```<code> $http({
      method : 'POST',
      url : 'views/user/user.json'
    }).success(function(data){
      $scope.persons = data;
    });
</code>```

user.json

```<code> [
        {
            "user": "Quarterback",
            "password": 5,
            "profile": "ppp"
        },
        {
            "user": "Wide Receiver",
            "password": 89,
            "profile": "oooo"
        }
    ]
</code>```

This way the table is generated correctly, but the json is fixed.
Now I'll paste the code with which I want to print the data by taking them from a query

controller.js

```<code> $http({
        method : 'POST',
        url : 'views/user/user.jsp'
    }).success(function(data){

        /*
        var jsonStr="your json string";
        var json=JSON.stringify(data);
        json=JSON.parse(json)
        console.log(json);
        */
        console.log(data);
        $scope.persons = data;
    });
</code>```

The code between / * .. * / left them to show that I also tried that road without success.

user.jsp

```<code>JSONArray jdata = new JSONArray();
UserRest as = new UserRest();
jdata = as.getAll();
logger.info("jdata in user.jsp "+jdata);
</code>```

UserRest.class (just paste the code where I create the JSON)

```<code> while (iter.hasNext()) {
      User ut = (User) iter.next();
      JSONObject jtemp = new JSONObject();
      jtemp.put("user", ut.getUserName());
      jtemp.put("password", ut.getPassword());
      jtemp.put("profilo", ut.getProfilo());
      jarray.put(jtemp);
    }
    return  jarray;
</code>```

the result of logger.info("jdata in user.jsp "+jdata) in user.jsp

```<code>jdata in user.jsp [{"user":"aaaaaaa","password":"1111111","profile":"0"},{"user":"bbbbbbbb","password":"222222222","profile":"1"}]
</code>```

As you can see the json looks the same, but when in the browser I call the list_user.jsp page in the console the value "data" in controller.js returns me

```<code> <? Xml version = "1.0" encoding = "utf-8"?>
</code>```

I also tried with JSON.parse or JSON.stringify but it does not work.
I also added "track by $ index" here:

```<code><tr ng-repeat = "for people track by $ index">
</code>```

in list_user.jsp but it does not work.

Please help me because I do not know how to do it anymore.

答:
Well, your problem appears to be that you should call a SERVICE, not a jsp.

A JSP builds a new web page for you and so it will put that:

```<code>< ? Xml version = "1.0" encoding = "utf-8"? >
</code>```

Try doing, instead a jsp, a servlet (or use JAX-RS, as you prefer) and putting you logic inside the 'doGet' method (again, or use JAX-RS).

Do a simple thing, like

```<code> protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
response.getWriter().append(your working JSON properly hardcoded);
}
</code>```

This way should work. Then put your service logic there.

Title: Angularjs Unexpected token JSON

Body:
I have a problem with angularjs and JSON.

This is my code.

list_user.jsp (this is the page where I print the table)

  {{ per.user }}
  {{ per.password }}
  {{ per.profile }}

controller.js

 $http({
      method : 'POST',
      url : 'views/user/user.json'
    }).success(function(data){
      $scope.persons = data;
    });

user.json

 [
        {
            "user": "Quarterback",
            "password": 5,
            "profile": "ppp"
        },
        {
            "user": "Wide Receiver",
            "password": 89,
            "profile": "oooo"
        }
    ]

This way the table is generated correctly, but the json is fixed.
Now I'll paste the code with which I want to print the data by taking them from a query

controller.js

 $http({
        method : 'POST',
        url : 'views/user/user.jsp'
    }).success(function(data){

        /*
        var jsonStr="your json string";
        var json=JSON.stringify(data);
        json=JSON.parse(json)
        console.log(json);
        */
        console.log(data);
        $scope.persons = data;
    });

The code between / * .. * / left them to show that I also tried that road without success.

user.jsp

JSONArray jdata = new JSONArray();
UserRest as = new UserRest();
jdata = as.getAll();
logger.info("jdata in user.jsp "+jdata);

UserRest.class (just paste the code where I create the JSON)

 while (iter.hasNext()) {
      User ut = (User) iter.next();
      JSONObject jtemp = new JSONObject();
      jtemp.put("user", ut.getUserName());
      jtemp.put("password", ut.getPassword());
      jtemp.put("profilo", ut.getProfilo());
      jarray.put(jtemp);
    }
    return  jarray;

the result of logger.info("jdata in user.jsp "+jdata) in user.jsp

jdata in user.jsp [{"user":"aaaaaaa","password":"1111111","profile":"0"},{"user":"bbbbbbbb","password":"222222222","profile":"1"}]

As you can see the json looks the same, but when in the browser I call the list_user.jsp page in the console the value "data" in controller.js returns me

 <? Xml version = "1.0" encoding = "utf-8"?>

I also tried with JSON.parse or JSON.stringify but it does not work.
I also added "track by $ index" here:

in list_user.jsp but it does not work.

Please help me because I do not know how to do it anymore.

Body:
Well, your problem appears to be that you should call a SERVICE, not a jsp.

A JSP builds a new web page for you and so it will put that:

< ? Xml version = "1.0" encoding = "utf-8"? >

Try doing, instead a jsp, a servlet (or use JAX-RS, as you prefer) and putting you logic inside the 'doGet' method (again, or use JAX-RS).

Do a simple thing, like

 protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
response.getWriter().append(your working JSON properly hardcoded);
}

This way should work. Then put your service logic there.


问:
How to continue a landscape orientation for a particular div tag while converting html to pdf in itext 7?
```<code><div isLandscape=false style="page-break-after:always">
<p class="title">
this is the first title in the portrait mode
</p>
<div>
this is the content following the first title in portrait mode
</div>
</div>
<div isLandscape=true style="page-break-after:always">
<p class="title">
this is the first title in the Landscape mode
</p>
<div style="page-break-after:always">
this is the content following the first title in Landscape mode
</div>
<p>
This content which is on the next page should be rendered on a landscape
page and all the content in this parent div should continue to be in the
landscape page.
</p>
</div>
<div isLandscape=false style="page-break-after:always">
<p class="title">
this content should be rendered on the portrait page and continue to be on a
portrait page till the end of the parent div tag.
</p>
</div>
</code>```

I want the first div content to be on the portrait A4 page and the next to be on the landscape A4 page.This should be not by rotation but by actually setting the pagesize.

答:
One of the ways you can achieve this is by parsing to layout elements instead of straight to a file or pdfDocument, and apply the page size modification using page events.

I made a quick example below that switches orientation every X pages:

```<code>public void createPdfFromHtml(String htmlSource, String pdfDest, String resoureLoc) throws IOException, InterruptedException {
    File pdf = new File(pdfDest);
    pdf.getParentFile().mkdirs();

    //convertToElements takes the string containing the HTML as input
    byte[] bytes = StreamUtil.inputStreamToArray(new FileInputStream(htmlSource));
    String html = new String(bytes);

    PdfWriter writer = new PdfWriter(pdfDest);
    PdfDocument pdfDoc = new PdfDocument(writer);

    Document doc = new Document(pdfDoc,pageSize);

    // Create the page size modifying event handler
    PageSize pageSize = PageSize.A4;
    pageSize = pageSize.rotate();//Start in landscape
    int differentPageSizeInterval = 5;
    PageSizeModifier pageSizeModifier = new PageSizeModifier(doc, differentPageSizeInterval, pageSize);
    //Register it to the pdfDocument and set it to trigger at the start of a page
    pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE,pageSizeModifier);
    ConverterProperties converterProperties = new ConverterProperties();
    converterProperties.setBaseUri(resoureLoc);
    //Convert the html to elements
    try {
        //parse and return the top level elements of the <body>
        List<IElement> elements = HtmlConverter.convertToElements(html, converterProperties);
        for (IElement ele : elements) {
            //Add the elements to the layout document
            doc.add((BlockElement) ele);
        }
        doc.close();
    } catch (PdfException e) {
        System.out.println(e);
        e.printStackTrace();
    }
}

protected class PageSizeModifier implements IEventHandler {

    Document doc;
    int interval;
    int counter;
    PageSize pageSize;

    public PageSizeModifier(Document doc, int interval,PageSize pageSize) {
        this.doc = doc; //A reference to the layout document must be kept so we can change the margins on the fly
        this.interval = interval;
        this.counter = 1;
        this.pageSize = pageSize;//Start out in landscape
    }
    @Override
    public void handleEvent(Event event) {
        if(counter == interval){
            //Rotate
            pageSize = pageSize.rotate();
            //For the rendering framework, change the default page size
            doc.getPdfDocument().setDefaultPageSize(pageSize);

            //because the page was already created, we need to update the various boxes determining the pagesize
            //By default, only the trim and mediabox will be present
            ((PdfDocumentEvent) event).getPage().setMediaBox(pageSize);
            ((PdfDocumentEvent) event).getPage().setTrimBox(pageSize);

            //Reset the counter
            counter = 1;

        }else{
            counter++;
        }

    }
</code>```

Body:
this is the first title in the portrait mode

this is the content following the first title in portrait mode

this is the first title in the Landscape mode

this is the content following the first title in Landscape mode

This content which is on the next page should be rendered on a landscape
page and all the content in this parent div should continue to be in the
landscape page.

this content should be rendered on the portrait page and continue to be on a
portrait page till the end of the parent div tag.

I want the first div content to be on the portrait A4 page and the next to be on the landscape A4 page.This should be not by rotation but by actually setting the pagesize.

Body:
One of the ways you can achieve this is by parsing to layout elements instead of straight to a file or pdfDocument, and apply the page size modification using page events.

I made a quick example below that switches orientation every X pages:

public void createPdfFromHtml(String htmlSource, String pdfDest, String resoureLoc) throws IOException, InterruptedException {
    File pdf = new File(pdfDest);
    pdf.getParentFile().mkdirs();

    //convertToElements takes the string containing the HTML as input
    byte[] bytes = StreamUtil.inputStreamToArray(new FileInputStream(htmlSource));
    String html = new String(bytes);

    PdfWriter writer = new PdfWriter(pdfDest);
    PdfDocument pdfDoc = new PdfDocument(writer);

    Document doc = new Document(pdfDoc,pageSize);

    // Create the page size modifying event handler
    PageSize pageSize = PageSize.A4;
    pageSize = pageSize.rotate();//Start in landscape
    int differentPageSizeInterval = 5;
    PageSizeModifier pageSizeModifier = new PageSizeModifier(doc, differentPageSizeInterval, pageSize);
    //Register it to the pdfDocument and set it to trigger at the start of a page
    pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE,pageSizeModifier);
    ConverterProperties converterProperties = new ConverterProperties();
    converterProperties.setBaseUri(resoureLoc);
    //Convert the html to elements
    try {
        //parse and return the top level elements of the <body>
        List<IElement> elements = HtmlConverter.convertToElements(html, converterProperties);
        for (IElement ele : elements) {
            //Add the elements to the layout document
            doc.add((BlockElement) ele);
        }
        doc.close();
    } catch (PdfException e) {
        System.out.println(e);
        e.printStackTrace();
    }
}

protected class PageSizeModifier implements IEventHandler {

    Document doc;
    int interval;
    int counter;
    PageSize pageSize;

    public PageSizeModifier(Document doc, int interval,PageSize pageSize) {
        this.doc = doc; //A reference to the layout document must be kept so we can change the margins on the fly
        this.interval = interval;
        this.counter = 1;
        this.pageSize = pageSize;//Start out in landscape
    }
    @Override
    public void handleEvent(Event event) {
        if(counter == interval){
            //Rotate
            pageSize = pageSize.rotate();
            //For the rendering framework, change the default page size
            doc.getPdfDocument().setDefaultPageSize(pageSize);

            //because the page was already created, we need to update the various boxes determining the pagesize
            //By default, only the trim and mediabox will be present
            ((PdfDocumentEvent) event).getPage().setMediaBox(pageSize);
            ((PdfDocumentEvent) event).getPage().setTrimBox(pageSize);

            //Reset the counter
            counter = 1;

        }else{
            counter++;
        }

    }


问:
Handle multiple parameters in array_map call back
I have the following code:

```<code>$a=array(15,12,13,25,27,36,18);
$b=array(1,1,1,1,1,1,1);//is it possible to pass only one value=1, instead of array containing seven 1's
// expectation: $b = array(1); or $b= 1;
//instead of $b=array(1,1,1,1,1,1,1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);
</code>```

I want something like:

```<code>$a=array(15,12,13,25,27,36,18);
$b=array(1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);
</code>```

Any better solution thanks.

答:
Have a look at array_walk

From Your example, it would be:

```<code>function array_add( &$item, $key, $toAdd) {
   $item+=$toAdd;
}
array_walk($a, 'array_add', 1);
</code>```

I would also recommend that you have a look at the answer provided using closure(use)

Body:
I have the following code:

$a=array(15,12,13,25,27,36,18);
$b=array(1,1,1,1,1,1,1);//is it possible to pass only one value=1, instead of array containing seven 1's
// expectation: $b = array(1); or $b= 1;
//instead of $b=array(1,1,1,1,1,1,1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);

I want something like:

$a=array(15,12,13,25,27,36,18);
$b=array(1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);

Any better solution thanks.

Body:
Have a look at array_walk

From Your example, it would be:

function array_add( &$item, $key, $toAdd) {
   $item+=$toAdd;
}
array_walk($a, 'array_add', 1);

I would also recommend that you have a look at the answer provided using closure(use)


问:
How to check more gently that some part of the code running 4 times a day
I have the script running by crontab and I want some part of the code being executed 4 times a day.

I have the snippet of code which

```<code>from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time == time(10,00) or now_time == time(16,00) or now_time == time(22,00) or now_time == time (4,00):
    func()
</code>```

The minus of this solution is that this part of the code may be executed on 10.01, 10.02 and will be skipped this way.

Is there more gentle and shorter way to write down this part of code?

Thanks!

答:
What you are after are time intervals. From the same package datetime you can create timedelta objects (difference between two datetimes) and cast them to seconds

Your code becomes:

```<code>from datetime import datetime, time
now = datetime.now()
today = now.date()
minutes_accepted = 5
execution_times = [time(hour=10), time(hour=16), time(hour=22)]
for delta in [datetime.combine(today, et) - now for et in execution_times]:
    if abs(delta.total_seconds()) < minutes_accepted * 60:
        print 'func'
</code>```

Body:
I have the script running by crontab and I want some part of the code being executed 4 times a day.

I have the snippet of code which

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time == time(10,00) or now_time == time(16,00) or now_time == time(22,00) or now_time == time (4,00):
    func()

The minus of this solution is that this part of the code may be executed on 10.01, 10.02 and will be skipped this way.

Is there more gentle and shorter way to write down this part of code?

Thanks!

Body:
What you are after are time intervals. From the same package datetime you can create timedelta objects (difference between two datetimes) and cast them to seconds

Your code becomes:

from datetime import datetime, time
now = datetime.now()
today = now.date()
minutes_accepted = 5
execution_times = [time(hour=10), time(hour=16), time(hour=22)]
for delta in [datetime.combine(today, et) - now for et in execution_times]:
    if abs(delta.total_seconds()) < minutes_accepted * 60:
        print 'func'


问:
How would I set the background image CSS property to a random file in a folder in JavaScript
Psuedo Code:

```<code>if currentCondition is snow {
    aFunction()
} else {
    // something else
}

function aFunction {
    look inside the snow folder at /images/condition/snow
    chose random jpeg/jpg from that folder
    use JQuery to set the css background-image property of a div
}
</code>```

How would I make the above in JavaScript? I can accomplish everything except choosing the random picture inside the snow folder. Thanks.

EDIT: The files are incrementing (file_1.jpg, file_2.jpg, etc.)

答:
Here's how to pick a random image, provided the number of images is set:

```<code>var totalBGs = 15;
var rnd = Math.floor(Math.random() * totalBGs) + 1; // 1 - 15
</code>```

Next you need to set that as CSS background (jQuery):

```<code>$(document).ready(function () {
  $("#some_element").css({ backgroundImage: "url(path/to/img/file_" + rnd + ".jpg)" });
});
</code>```

Body:
Psuedo Code:

if currentCondition is snow {
    aFunction()
} else {
    // something else
}

function aFunction {
    look inside the snow folder at /images/condition/snow
    chose random jpeg/jpg from that folder
    use JQuery to set the css background-image property of a div
}

How would I make the above in JavaScript? I can accomplish everything except choosing the random picture inside the snow folder. Thanks.

EDIT: The files are incrementing (file_1.jpg, file_2.jpg, etc.)

Body:
Here's how to pick a random image, provided the number of images is set:

var totalBGs = 15;
var rnd = Math.floor(Math.random() * totalBGs) + 1; // 1 - 15

Next you need to set that as CSS background (jQuery):

$(document).ready(function () {
  $("#some_element").css({ backgroundImage: "url(path/to/img/file_" + rnd + ".jpg)" });
});


问:
Parse WSDL with Zeep
I want to parse a WSDL file with Zeep and get out:

All the operations

Request xml messages for each operations

Any examples on parsing the wsdl?

I guess I should use zeep.wsdl and the parse_service method?

/A

答:
solved:</p>

```<code>client= Client('url_to_wsdl')
for service in client.wsdl.services.values():
    for port in service.ports.values():
        operations = sorted(
        port.binding._operations.values(),
        key=operator.attrgetter('name'))

        for operation in operations:
           print operation.name
           node = client.create_message(client.service, operation.name)
           print node
</code>```

Title: Parse WSDL with Zeep

Body:
solved:

client= Client('url_to_wsdl')
for service in client.wsdl.services.values():
    for port in service.ports.values():
        operations = sorted(
        port.binding._operations.values(),
        key=operator.attrgetter('name'))

        for operation in operations:
           print operation.name
           node = client.create_message(client.service, operation.name)
           print node


问:
How do I execute a new job on success or failure of Hangfire job?
I'm working on a Web API RESTful service that on a request needs to perform a task. We're using Hangfire to execute that task as a job, and on failure, will attempt to retry the job up to 10 times.

If the job eventually succeeds I want to run an additional job (to send an event to another service). If the job fails even after all of the retry attempts, I want to run a different additional job (to send a failure event to another service).

However, I can't figure out how to do this. I've created the following JobFilterAttribute:

```<code>public class HandleEventsAttribute : JobFilterAttribute, IElectStateFilter
{
    public IBackgroundJobClient BackgroundJobClient { get; set; }

    public void OnStateElection(ElectStateContext context)
    {
        var failedState = context.CandidateState as FailedState;
        if (failedState != null)
        {
            BackgroundJobClient.Enqueue<MyJobClass>(x => x.RunJob());
        }
    }
}
</code>```

The one problem I'm having is injecting the IBackgroundJobClient into this attribute. I can't pass it as a property to the attribute (I get a "Cannot access non-static field 'backgroundJobClient' in static context" error). We're using autofac for dependency injection, and I tried figuring out how to use property injection, but I'm at a loss. All of this leads me to believe I may be on the wrong track.

I'd think it would be a fairly common pattern to run some additional cleanup code if a Hangfire job fails. How do most people do this?

Thanks for the help. Let me know if there's any additional details I can provide.

答:
Hangfire can build an execution chains. If you want to schedule next job after first one succeed, you need to use ContinueWith(string parentId, Expression<Action> methodCall, JobContinuationOptions options); with the JobContinuationOptions.OnlyOnSucceededState to run it only after success.

But you can create a HangFire extension like JobExecutor and run tasks inside it to get more possibilities.

Something like that:

```<code>public static JobResult<T> Enqueue<T>(Expression<Action> a, string name)
{
    var exprInfo = GetExpressionInfo(a);

    Guid jGuid = Guid.NewGuid();

    var jobId = BackgroundJob.Enqueue(() => JobExecutor.Execute(jGuid, exprInfo.Method.DeclaringType.AssemblyQualifiedName, exprInfo.Method.Name, exprInfo.Parameters, exprInfo.ParameterTypes));

    JobResult<T> result = new JobResult<T>(jobId, name, jGuid,  0, default(T));
    JobRepository.WriteJobState(new JobResult<T>(jobId, name, jGuid, 0, default(T)));

    return result;
}
</code>```

More detailed information you can find here: https://indexoutofrange.com/Don%27t-do-it-now!-Part-5.-Hangfire-job-continuation,-ContinueWith/

Body:
I'm working on a Web API RESTful service that on a request needs to perform a task. We're using Hangfire to execute that task as a job, and on failure, will attempt to retry the job up to 10 times.

If the job eventually succeeds I want to run an additional job (to send an event to another service). If the job fails even after all of the retry attempts, I want to run a different additional job (to send a failure event to another service).

However, I can't figure out how to do this. I've created the following JobFilterAttribute:

public class HandleEventsAttribute : JobFilterAttribute, IElectStateFilter
{
    public IBackgroundJobClient BackgroundJobClient { get; set; }

    public void OnStateElection(ElectStateContext context)
    {
        var failedState = context.CandidateState as FailedState;
        if (failedState != null)
        {
            BackgroundJobClient.Enqueue<MyJobClass>(x => x.RunJob());
        }
    }
}

The one problem I'm having is injecting the IBackgroundJobClient into this attribute. I can't pass it as a property to the attribute (I get a "Cannot access non-static field 'backgroundJobClient' in static context" error). We're using autofac for dependency injection, and I tried figuring out how to use property injection, but I'm at a loss. All of this leads me to believe I may be on the wrong track.

I'd think it would be a fairly common pattern to run some additional cleanup code if a Hangfire job fails. How do most people do this?

Thanks for the help. Let me know if there's any additional details I can provide.

Body:
Hangfire can build an execution chains. If you want to schedule next job after first one succeed, you need to use ContinueWith(string parentId, Expression<Action> methodCall, JobContinuationOptions options); with the JobContinuationOptions.OnlyOnSucceededState to run it only after success.

But you can create a HangFire extension like JobExecutor and run tasks inside it to get more possibilities.

Something like that:

public static JobResult<T> Enqueue<T>(Expression<Action> a, string name)
{
    var exprInfo = GetExpressionInfo(a);

    Guid jGuid = Guid.NewGuid();

    var jobId = BackgroundJob.Enqueue(() => JobExecutor.Execute(jGuid, exprInfo.Method.DeclaringType.AssemblyQualifiedName, exprInfo.Method.Name, exprInfo.Parameters, exprInfo.ParameterTypes));

    JobResult<T> result = new JobResult<T>(jobId, name, jGuid,  0, default(T));
    JobRepository.WriteJobState(new JobResult<T>(jobId, name, jGuid, 0, default(T)));

    return result;
}

More detailed information you can find here: https://indexoutofrange.com/Don%27t-do-it-now!-Part-5.-Hangfire-job-continuation,-ContinueWith/


问:
android different langues for single textview
How can I display multiple languages for single textview without changing system language?

here donor search is single textview with english and marathi languages at a time.

how to do this??

答:
Use /n in when you write text in textview like</p>

```<code> <TextView
            android:id="@+id/check"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/deatils_news_img"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:textSize="20sp"
            android:text="This is just a text \n یہ صرف ایک متن ہے"
            android:textColor="@color/colortitle" />
</code>```

Body:
Use /n in when you write text in textview like

 <TextView
            android:id="@+id/check"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/deatils_news_img"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:textSize="20sp"
            android:text="This is just a text \n یہ صرف ایک متن ہے"
            android:textColor="@color/colortitle" />


问:
small tricky query on self join
I have a table EMP with columns as below:

```<code>create table emp(
empno    number(4,0),
ename    varchar2(10),
job      varchar2(9),
mgr_id   number(4,0),
sal      number(7,2),
deptno   number(2,0));
</code>```

I want to list all employees' names along with their manager names, including those who do not have a manager. For those employees, their manager's name should be displayed as 'BOSS'.

答:
This work fine in oracle:</p>

```<code>SELECT e.ename,
 nvl(m.ename, 'BOSS')mgr
   FROM emp a
LEFT JOIN emp b
ON m.empno = e.mgr_id;
</code>```

Title: small tricky query on self join

Body:
I have a table EMP with columns as below:

create table emp(
empno    number(4,0),
ename    varchar2(10),
job      varchar2(9),
mgr_id   number(4,0),
sal      number(7,2),
deptno   number(2,0));

I want to list all employees' names along with their manager names, including those who do not have a manager. For those employees, their manager's name should be displayed as 'BOSS'.

Body:
This work fine in oracle:

SELECT e.ename,
 nvl(m.ename, 'BOSS')mgr
   FROM emp a
LEFT JOIN emp b
ON m.empno = e.mgr_id;


问:
How to feed multiple inputs through feed_dict in tensorflow
I have a network consist of multiple sub-network (multiple convolution net and at last one fully connected + soft max layer). Every ConvNet feed with specific region and size of images. so, to feed my network I write image place holder for every convnet input and one label place holder to feed label of all images in one batch (all of the input images in all convnet inputs have the same labels).
Unfortunately I don't have any idea for feed_dict part.
for example this code is for only one convnet training:

```<code>    images_r, labels_r = sess.run([images, labels])
    train_feed = {images_placeholder: images_r,
              labels_placeholder: labels_r}
    _, loss_value = sess.run([train_op, loss_func], feed_dict=train_feed)
</code>```

How can I extend above code for feed all conv nets?

答:
So for each of the conv networks, if the placeholders for inputs are: conv_1_input, conv_2_input.... conv_N_input, then you pass the list in the feed_dict like this:

```<code>train_feed = {`conv_1_input`: image_1, `conv_2_input`: image_2,.. `conv_N_input`: image_N,
          labels_placeholder: labels_r}
_, loss_value = sess.run([train_op, loss_func], feed_dict=train_feed)
</code>```

Body:
I have a network consist of multiple sub-network (multiple convolution net and at last one fully connected + soft max layer). Every ConvNet feed with specific region and size of images. so, to feed my network I write image place holder for every convnet input and one label place holder to feed label of all images in one batch (all of the input images in all convnet inputs have the same labels).
Unfortunately I don't have any idea for feed_dict part.
for example this code is for only one convnet training:

    images_r, labels_r = sess.run([images, labels])
    train_feed = {images_placeholder: images_r,
              labels_placeholder: labels_r}
    _, loss_value = sess.run([train_op, loss_func], feed_dict=train_feed)

How can I extend above code for feed all conv nets?

Body:
So for each of the conv networks, if the placeholders for inputs are: conv_1_input, conv_2_input.... conv_N_input, then you pass the list in the feed_dict like this:

train_feed = {`conv_1_input`: image_1, `conv_2_input`: image_2,.. `conv_N_input`: image_N,
          labels_placeholder: labels_r}
_, loss_value = sess.run([train_op, loss_func], feed_dict=train_feed)


问:
egrep search for whitespace
I'm trying to use egrep with a regex pattern to match whitespace.

I've used RegEx with Perl and C# before and they both support the pattern \s to search for whitespace. egrep (or at least the version I'm using) does not seem to support this pattern.

In a few articles online I've come across a shorthand [[:space:]], but this does not seem to work. Any help is appreciated.

Using: SunOS 5.10

答:
```<code>$ cat > file
this line has whitespace
thislinedoesnthave
$ egrep [[:space:]] file
this line has whitespace
</code>```

Works under debian.

For Solaris, isn't there an "eselect" like (see gentoo) or alternatives file to set default your egrep version?

Have you tried grep -E, because if the egrep that is on your path is not the good one, maybe grep is.

Title: egrep search for whitespace

Body:
$ cat > file
this line has whitespace
thislinedoesnthave
$ egrep [[:space:]] file
this line has whitespace

Works under debian.

For Solaris, isn't there an "eselect" like (see gentoo) or alternatives file to set default your egrep version?

Have you tried grep -E, because if the egrep that is on your path is not the good one, maybe grep is.

OwnerDisplayName: Aif

LastEditorDisplayName: Aif


问:
Append filename to CSV in new column
I have a lot of csv files stored in a directory.
In each csv file need to add the name as column this through powershell.

Example

File location: <SERVERNAME>\Export\FILENAME1.CSV

Contents:

```<code>1232;Description;a1
1232;Description;a2
</code>```

The result must be:

```<code>1232;Description;a1;FILENAME1.CSV
1232;Description;a2;FILENAME1.CSV
</code>```

Can someone help me with this?

答:
The following will append a Filename column to each .CSV file in a directory:

```<code>Get-ChildItem *.csv | ForEach-Object {
    $CSV = Import-CSV -Path $_.FullName -Delimiter ";"
    $FileName = $_.Name

    $CSV | Select-Object *,@{N='Filename';E={$FileName}} | Export-CSV $_.FullName -NTI -Delimiter ";"
}
</code>```

Explanation:

Uses Get-ChildItem to get all files named *.csv

Iterates through each file with ForEach-Object and uses Import-CSV to load their contents as a PowerShell object

Records the name of the file in $FileName

Uses Select-Object to add a calculated property with the name Filename and the value of the $FileName variable

Uses Export-CSV to write back over the original file. The -NTI (NoTypeInformation) switch is used to ensure the PowerShell object header line is not included.

Title: Append filename to CSV in new column

Body:
I have a lot of csv files stored in a directory.
In each csv file need to add the name as column this through powershell.

Example

File location: <SERVERNAME>\Export\FILENAME1.CSV

Contents:

1232;Description;a1
1232;Description;a2

The result must be:

1232;Description;a1;FILENAME1.CSV
1232;Description;a2;FILENAME1.CSV

Can someone help me with this?

Body:
The following will append a Filename column to each .CSV file in a directory:

Get-ChildItem *.csv | ForEach-Object {
    $CSV = Import-CSV -Path $_.FullName -Delimiter ";"
    $FileName = $_.Name

    $CSV | Select-Object *,@{N='Filename';E={$FileName}} | Export-CSV $_.FullName -NTI -Delimiter ";"
}

Explanation:

Uses Get-ChildItem to get all files named *.csv

Iterates through each file with ForEach-Object and uses Import-CSV to load their contents as a PowerShell object

Records the name of the file in $FileName

Uses Select-Object to add a calculated property with the name Filename and the value of the $FileName variable

Uses Export-CSV to write back over the original file. The -NTI (NoTypeInformation) switch is used to ensure the PowerShell object header line is not included.


问:
Is there any alternate to acquire dependencies without using POM.xml?
My question is, I don't want to write XML code for dependencies in the POM.xml again and again.
For example, I want to use the log4j JAR in my project. instead of writing XML code is there any option to download the related JAR files?

答: Yes you can add them through the java build path from your IDE. However, I would recommend that you add these jars as dependencies in the pom.xml and build your project through maven. This will make sure that you will not run into any error regarding the missing dependencies in case any jar gets deleted accidentally or if you want the same set of jars for a new project. And understanding a pom.xml is not a difficult task</p>


问:
Owl Carousel Slider Smoothly Not working
I created Owl Carousel Slider with auto play but it not sliding smoothly. Anyone know how to create following code run smoothly?

Javascript Code

```<code>var owl = $('.owl-carousel');
owl.owlCarousel({
  autoPlay: 1000, //Set AutoPlay to 3 seconds
  dots: true,
  items: 2,
  margin: 10,
});
</code>```

Demo

答:
increase autoplay duration.</p>

```<code>var owl = $('.owl-carousel');
owl.owlCarousel({
  autoPlay: 3000, //Set AutoPlay to 3 seconds
  dots: true,
  items: 2,
  margin: 10,
});
</code>```

Body:
I created Owl Carousel Slider with auto play but it not sliding smoothly. Anyone know how to create following code run smoothly?

Javascript Code

var owl = $('.owl-carousel');
owl.owlCarousel({
  autoPlay: 1000, //Set AutoPlay to 3 seconds
  dots: true,
  items: 2,
  margin: 10,
});

Demo

Body:
increase autoplay duration.

var owl = $('.owl-carousel');
owl.owlCarousel({
  autoPlay: 3000, //Set AutoPlay to 3 seconds
  dots: true,
  items: 2,
  margin: 10,
});


问:
ODBC call failed - Random date overflow errors after moving from 32-bit ODBC 5.1 to 64-bit 5.3
Background:

Legacy code running in MS Access 2003.

Sqls run by CurrentDB in Access.

Currently running on Windows 7 32-bit machine.

Connecting to MySQL Server 5.5 through a ODBC 5.1 Driver.

Problem:

Trying to migrate to Windows server 2012 64 bit.

ODBC 5.3 Unicode Driver (32 bit).

Don't want to use time rewriting everything as there is a lot of code, and it will in a not to distant future be removed.

Issue:

Several sql statements fail when running on the new servers. Worked on old servers.

All the failed sqls have now() in the statement.

Error description says ODBC call failed. While the more detailed description says date overflow - "[MySQL][ODBC 5.3(w) Driver][mysqlid-5.5.28-log]Date overflow".

Happens randomly, and when it happens and Access stops one can usually just choose continue and the sql will then work. It fails less than 1% of the times it runs (of thousands).

The only dates in the sql are in the where clause: "and fieldA > now()", where fieldA is a datetime column. This is a get recordset sql. Another error during an insert is the same, but where an integer was subtracted from now() before compared to a datetime.

I don't understand why it says date overflow when there doesn't seem to be a reason for the time of either datetime or "now" to be removed? And since the datetime field is already in the database and now() will get current date and time there shouldn't be any invalid dates?

Any help in what the problem might be or how to debug/log anything that might help would be highly appreciated.

Turning trace on in the ODBC driver is not an option because it happens so randomly, there is so much traffic therefore this would slow down everything such that nothing happens.

Note that I also did encounter one sql where the date overflow error message was correct. It seems that prior to 5.3 when inserting a datetime into a date field it was automatically truncated, because a sql which had been successfull 3000 times started failing. Therefore this sql has been fixed by extracting the date from the field first. But the other errors must be something different.

答:
New version containing a bugfix has been released by Oracle: 5.3.8

This error was a bug that seems to have been introduced in version 5.1.11.

In advanced options there is now a Date overflow check box which has to be ticked for the code to continue when there is an error.

Reply from Oracle about the fix:
"For your information the fix approach was that in C or C++ it is possible to read or write DATE type using SQL_TIMESTAMP_STRUCT.
This struct can hold both date and time.
The error (Date overflow) was generated when with operations that are supposed to be DATE-only this struct got non-zero values for time.
That is the canonical approach as ODBC API requires, however, it causes inconveniences sometimes when for instance the app did not bother
to initialize the whole structure with 0 values because it knows it will only need the DATE part but the random values for TIME fraction could cause the errors despite of being truncated.
A new option was introduced to continue with the query execution rather then return error.
The server will ignore the TIME part and the result is the same as if there were zeroes."


问:
Need help in building regular expression
What is the Regular expression for

```<code>OD
-0D

-123D

-145Y

234w

and not +234D or -678m etc.
</code>```

I do have

```<code>string EXP_REGEX_VALID_LITERAL = @"[0-9]*[d|D|w|W|m|M|q|Q|y|Y]";
Regex regex = new Regex(EXP_REGEX_VALID_LITERAL);
return regex.IsMatch(inputString);
</code>```

but it is failing for "/0345d"

Validation Rules:

the expression is a alphanumeric one(where the alphabets are optional) where the alphabets can be only d|D|w|W|m|M|q|Q|y|Y and can appear only after the numerals. Also if any character can come before any numerals that can only be a minus.so -123 is valid or -123d or 123d or 123w are valid. but not 23dw or +12d etc.

Thanks

答:
If I understand well what you want, may be this will work:

```<code>/^-?\d+[dwmqy]$/i
</code>```

c# syntax (not quite sure):

```<code>Regex.Match("/0123d", "^-?\d+[dwmqy]$",RegexOptions.IgnoreCase);
</code>```

Where:

```<code>^   begining of the string
-?  optionnal -
\d+ one or more digits
[dwmqy]  one of these char
$   end of the string

i   case insensitive
</code>```

Body:
What is the Regular expression for

OD
-0D

-123D

-145Y

234w

and not +234D or -678m etc.

I do have

string EXP_REGEX_VALID_LITERAL = @"[0-9]*[d|D|w|W|m|M|q|Q|y|Y]";
Regex regex = new Regex(EXP_REGEX_VALID_LITERAL);
return regex.IsMatch(inputString);

but it is failing for "/0345d"

Validation Rules:

the expression is a alphanumeric one(where the alphabets are optional) where the alphabets can be only d|D|w|W|m|M|q|Q|y|Y and can appear only after the numerals. Also if any character can come before any numerals that can only be a minus.so -123 is valid or -123d or 123d or 123w are valid. but not 23dw or +12d etc.

Thanks

Body:
If I understand well what you want, may be this will work:

/^-?\d+[dwmqy]$/i

c# syntax (not quite sure):

Regex.Match("/0123d", "^-?\d+[dwmqy]$",RegexOptions.IgnoreCase);

Where:

^   begining of the string
-?  optionnal -
\d+ one or more digits
[dwmqy]  one of these char
$   end of the string

i   case insensitive


问:
Change color of jquery pageguide on runtime
I have a .NET core application with a jquery pageguide in it. The colors of the application, for example the menubars, can be configured by the user.
To achieve this, I add a HtmlString with a

Body:
Read the users input by sending it to your .NET application

when rendering your page, overwrite it by generating a CSS-file or <style> tag which you can then implement on your HTML file. That CSS overwrites the default colors.


问:
How to put single flag if same cust have different product
Let me explain what is my requirment. I need to check if i have customers with different productid if yes then i have to check if they have any producttype null or not in case any of the customerid have NULL producttype then flag for both the customerid should be N else Y

For example :I have a table in which i have many columns. PFB the table stucture

```<code>Customerid   productid  producttype

  1             a             x
  1             b            Null
  2             c             y
  2             d             y
  3             e             z
  3             f            Null
</code>```

what i want is like below:

```<code>Customerid  Productid   Productype  flag

1             a           x           N
1             b          Null         N
2             c           y           Y
2             d           y           Y
3             e           z           N
3             f          Null         N
</code>```

till now what i have done

```<code>;with cte as
(

select * from test where customerid  in

(select  customerid  from test  group by customerid having count(*) >1

) )
</code>```

from this i collect all the customerid who have more then one productid and different producttpe now i want to add the flag part.

Please let me know if this approach is good and how can i achieve the next thing.

Thanks in advance !!

答:
You are on right track. I haved used CTE but with lesser complicated inner query.
Try this :

```<code>Create table #temp(Customerid int,   productid varchar(1), producttype varchar(1))
insert into #temp values
  (1,'a','x'),
  (1,'b',Null),
  (2,'c','y'),
  (2,'d','y'),
  (3,'e','z'),
  (3,'f',Null)

;with cte as
(
select distinct customerid, 'T' as tempflag from #temp where  producttype is null
)
Select b.*,
case  a.tempflag when 'T' then 'N' else 'Y' end as Flag
 from cte a
right join #temp b
on a.customerid = b.customerid
</code>```

output :

```<code>Customerid  productid producttype Flag
----------- --------- ----------- ----
1           a         x           N
1           b         NULL        N
2           c         y           Y
2           d         y           Y
3           e         z           N
3           f         NULL        N
</code>```

Body:
Let me explain what is my requirment. I need to check if i have customers with different productid if yes then i have to check if they have any producttype null or not in case any of the customerid have NULL producttype then flag for both the customerid should be N else Y

For example :I have a table in which i have many columns. PFB the table stucture

Customerid   productid  producttype

  1             a             x
  1             b            Null
  2             c             y
  2             d             y
  3             e             z
  3             f            Null

what i want is like below:

Customerid  Productid   Productype  flag

1             a           x           N
1             b          Null         N
2             c           y           Y
2             d           y           Y
3             e           z           N
3             f          Null         N

till now what i have done

;with cte as
(

select * from test where customerid  in

(select  customerid  from test  group by customerid having count(*) >1

) )

from this i collect all the customerid who have more then one productid and different producttpe now i want to add the flag part.

Please let me know if this approach is good and how can i achieve the next thing.

Thanks in advance !!

Body:
You are on right track. I haved used CTE but with lesser complicated inner query.
Try this :

Create table #temp(Customerid int,   productid varchar(1), producttype varchar(1))
insert into #temp values
  (1,'a','x'),
  (1,'b',Null),
  (2,'c','y'),
  (2,'d','y'),
  (3,'e','z'),
  (3,'f',Null)

;with cte as
(
select distinct customerid, 'T' as tempflag from #temp where  producttype is null
)
Select b.*,
case  a.tempflag when 'T' then 'N' else 'Y' end as Flag
 from cte a
right join #temp b
on a.customerid = b.customerid

output :

Customerid  productid producttype Flag
----------- --------- ----------- ----
1           a         x           N
1           b         NULL        N
2           c         y           Y
2           d         y           Y
3           e         z           N
3           f         NULL        N


问:
Scanning multiple files and printing them alphabetically
I'm reading multiple text files using Java and printing their directories and I wonder why the output is not alphabetically arranged?

Code Snippet (got it from the internet also)

```<code>File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
for (File path : listOfFiles) {
    System.out.println(path);
}
</code>```

Output:

```<code>dilapitan@NT071855:~/Desktop/xml-parsing$ java Multiple
/home/dilapitan/Desktop/xml-parsing/files/c.txt
/home/dilapitan/Desktop/xml-parsing/files/b.txt
/home/dilapitan/Desktop/xml-parsing/files/a.txt
dilapitan@NT071855:~/Desktop/xml-parsing$
</code>```

Can I do it with the output being:

```<code>a.txt
b.txt
c.txt
</code>```

Thank you in advance!

答:
Just another way to do it, but using the power of java8

```<code>List<Path> x = Files.list(Paths.get("C:\\myPath\\Tools"))
            .filter(p -> Files.exists(p))
            .map(s -> s.getFileName())
            .sorted()
            .collect(Collectors.toList());

x.forEach(System.out::println);
</code>```

or even better

```<code>List<Path> x = Files.list(Paths.get("C:\\Users\\myPath\\Tools"))
                .filter(Files::exists)
                .map(Path::getFileName)
                .sorted()
                .collect(Collectors.toList());

x.forEach(System.out::println);
</code>```

Body:
I'm reading multiple text files using Java and printing their directories and I wonder why the output is not alphabetically arranged?

Code Snippet (got it from the internet also)

File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
for (File path : listOfFiles) {
    System.out.println(path);
}

Output:

dilapitan@NT071855:~/Desktop/xml-parsing$ java Multiple
/home/dilapitan/Desktop/xml-parsing/files/c.txt
/home/dilapitan/Desktop/xml-parsing/files/b.txt
/home/dilapitan/Desktop/xml-parsing/files/a.txt
dilapitan@NT071855:~/Desktop/xml-parsing$

Can I do it with the output being:

a.txt
b.txt
c.txt

Thank you in advance!

Body:
Just another way to do it, but using the power of java8

List<Path> x = Files.list(Paths.get("C:\\myPath\\Tools"))
            .filter(p -> Files.exists(p))
            .map(s -> s.getFileName())
            .sorted()
            .collect(Collectors.toList());

x.forEach(System.out::println);

or even better

List<Path> x = Files.list(Paths.get("C:\\Users\\myPath\\Tools"))
                .filter(Files::exists)
                .map(Path::getFileName)
                .sorted()
                .collect(Collectors.toList());

x.forEach(System.out::println);


问:
Nginx to serve php files from a different server
I am trying to configure nginx to serve PHP from another server.

The files can be located within a directory under /sample on the other server

Fast CGI is running on port 9000 on the other server

Here is what I have tried, which is not working at the moment.

```<code>location ~ [^/]\.php(/|$) {
                proxy_pass      http://192.168.x.xx;
                proxy_redirect http://192.168.x.xx /sample;
                fastcgi_split_path_info ^(.+?\.php)(/.*)$;
                if (!-f $document_root$fastcgi_script_name)
                {
                        return 404;
                }
                # Mitigate https://httpoxy.org/ vulnerabilities
                fastcgi_param HTTP_PROXY "";
                fastcgi_read_timeout 150;
                fastcgi_buffers 4 256k;
                fastcgi_buffer_size 128k;
                fastcgi_busy_buffers_size 256k;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
</code>```

I also need to configure nginx to serve static files from the same server

答:
The following configuration does exactly what you need:

```<code>server {
    listen 80;
    index index.php index.html;
    server_name localhost;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root {STATIC-FILES-LOCATION};

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass {PHP-FPM-SERVER}:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}
</code>```

All you have to do is replace {STATIC-FILES-LOCATION} with the location of your static files on the Nginx server and {PHP-FPM-SERVER} with the IP of the PHP-FPM server.

This way you will serve all files without the PHP extension statically from the Nginx server and all the PHP files will be interpreted with the PHP-FPM server.

Here's a working example of a dockerised version of what you are trying to achieve - https://github.com/mikechernev/dockerised-php/. It serves the static files from Nginx and interprets the PHP files via the PHP-FPM container. In the accompanying blog post (http://geekyplatypus.com/dockerise-your-php-application-with-nginx-and-php7-fpm/) I go in lengths about the whole connection between Nginx and PHP-FPM.

EDIT: One important thing to keep in mind is that the paths in both the Nginx and PHP-FPM servers should match. So you will have to put your php files in the same directory on the PHP-FPM server as your static files on the Nginx one ({STATIC-FILES-LOCATION}).

An example would be to have /var/www/ on Nginx holding your static files and /var/www on PHP-FPM to hold your php files.

Hope this helps :)

Body:
I am trying to configure nginx to serve PHP from another server.

The files can be located within a directory under /sample on the other server

Fast CGI is running on port 9000 on the other server

Here is what I have tried, which is not working at the moment.

location ~ [^/]\.php(/|$) {
                proxy_pass      http://192.168.x.xx;
                proxy_redirect http://192.168.x.xx /sample;
                fastcgi_split_path_info ^(.+?\.php)(/.*)$;
                if (!-f $document_root$fastcgi_script_name)
                {
                        return 404;
                }
                # Mitigate https://httpoxy.org/ vulnerabilities
                fastcgi_param HTTP_PROXY "";
                fastcgi_read_timeout 150;
                fastcgi_buffers 4 256k;
                fastcgi_buffer_size 128k;
                fastcgi_busy_buffers_size 256k;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }

I also need to configure nginx to serve static files from the same server

Body:
The following configuration does exactly what you need:

server {
    listen 80;
    index index.php index.html;
    server_name localhost;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root {STATIC-FILES-LOCATION};

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass {PHP-FPM-SERVER}:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

All you have to do is replace {STATIC-FILES-LOCATION} with the location of your static files on the Nginx server and {PHP-FPM-SERVER} with the IP of the PHP-FPM server.

This way you will serve all files without the PHP extension statically from the Nginx server and all the PHP files will be interpreted with the PHP-FPM server.

Here's a working example of a dockerised version of what you are trying to achieve - https://github.com/mikechernev/dockerised-php/. It serves the static files from Nginx and interprets the PHP files via the PHP-FPM container. In the accompanying blog post (http://geekyplatypus.com/dockerise-your-php-application-with-nginx-and-php7-fpm/) I go in lengths about the whole connection between Nginx and PHP-FPM.

EDIT: One important thing to keep in mind is that the paths in both the Nginx and PHP-FPM servers should match. So you will have to put your php files in the same directory on the PHP-FPM server as your static files on the Nginx one ({STATIC-FILES-LOCATION}).

An example would be to have /var/www/ on Nginx holding your static files and /var/www on PHP-FPM to hold your php files.

Hope this helps :)


问:
PHP: How to remove/disable a selection from a checkbox group if the value is already selected and stored in database previously
Right now I am coding in PHP & HTML

I need to make a selection from the checkbox group
and it goes like this:

The value in the dropdown menu is retrieved from the value stored in the database in table subject. So the checkbox options will appears as (for example) Mathematics, Algebra, Calculus, English, Linguistic etc. -- I have no problem with displaying this one.

Table subject

```<code>subject_id       subject_name
==========       ============
     1            Mathematics
     2            Algebra
     3            Calculus
     4            English
     5            Linguistic
</code>```

So after that, a student can choose their subject and it will be stored in another table named student_subject where it stores the student_id and the subject_id (to store what subjects did a student chose)
Example:

table student_subject

```<code>    student_id       subject_id
    ==========       ===========
        1                 1
        1                 2
        1                 3
        2                 1
        2                 3
</code>```

Now, the student comes again to add another subject to his profile. The same checkbox option will be displayed as mentioned earlier in (1) but I would love to disabled/remove/not display the already selected option from being selectable again to avoid redundancy.

I really have no idea on how to create this function. I know there are a lot of experienced programmers and developera here so I wish you could show me the right way. Your guidance is highly appreciated.

答:
You can use a query which only picks up subjects which ID isn't in student_subject.

It would look something like:

```<code>SELECT * FROM `subject`
WHERE `subject_id` NOT IN (
    SELECT `subject_id` FROM `student_subject` WHERE `student_id` = '1'
)
</code>```

(you can ommit the inner where clause if you don't want this to be user specific)

and then build the <select> element based on the array returned from it.

Body:
Right now I am coding in PHP & HTML

I need to make a selection from the checkbox group
and it goes like this:

The value in the dropdown menu is retrieved from the value stored in the database in table subject. So the checkbox options will appears as (for example) Mathematics, Algebra, Calculus, English, Linguistic etc. -- I have no problem with displaying this one.

Table subject

subject_id       subject_name
==========       ============
     1            Mathematics
     2            Algebra
     3            Calculus
     4            English
     5            Linguistic

So after that, a student can choose their subject and it will be stored in another table named student_subject where it stores the student_id and the subject_id (to store what subjects did a student chose)
Example:

table student_subject

    student_id       subject_id
    ==========       ===========
        1                 1
        1                 2
        1                 3
        2                 1
        2                 3

Now, the student comes again to add another subject to his profile. The same checkbox option will be displayed as mentioned earlier in (1) but I would love to disabled/remove/not display the already selected option from being selectable again to avoid redundancy.

I really have no idea on how to create this function. I know there are a lot of experienced programmers and developera here so I wish you could show me the right way. Your guidance is highly appreciated.

Body:
You can use a query which only picks up subjects which ID isn't in student_subject.

It would look something like:

SELECT * FROM `subject`
WHERE `subject_id` NOT IN (
    SELECT `subject_id` FROM `student_subject` WHERE `student_id` = '1'
)

(you can ommit the inner where clause if you don't want this to be user specific)

and then build the <select> element based on the array returned from it.


问:
ASP.NET MVC Cookie Implementation
I try to implement a basic cookie helper in my application.
Mainly I check in base controller everytime whether or not if cookie is set.
If cookie

```<code>public class MyCookie
{

    public static string CookieName {get;set;}
    public virtual User User { get; set; }
    public virtual Application App { get; set; }

    public MyCookie(Application app)
    {
        CookieName = "MyCookie" + app;
        App = app;
    }

    public void SetCookie(User user)
    {
        HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName] ?? new HttpCookie(CookieName);
        myCookie.Values["UserId"] = user.UserId.ToString();
        myCookie.Values["LastVisit"] = DateTime.Now.ToString();
        myCookie.Expires = DateTime.Now.AddDays(365);
        HttpContext.Current.Response.Cookies.Add(myCookie);
    }

    public HttpCookie GetCookie()
    {
        HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName];
        if(myCookie != null)
        {
            int userId = Convert.ToInt32(myCookie.Values["UserId"]);
            User user = session.Get<User>(userId);
            return user;
        }
        return null;
    }
}
</code>```

if session is null I try to get from cookie or if session initialize I set cookie but I never see my cookie in browser. What is wrong?

I always start session but with userId=0
To get cookie and set session from cookie:

```<code>if (userId == 0)
{
    MyCookie myCookie = new MyCookie(_app);
    User user = cookieHelper.GetCookie();
    if (user != null)
        SessionHelper.SetSession(user);
}
</code>```

答:
Try this </p>

```<code>HttpCookie cookie = new HttpCookie("Remember_Me");
cookie["userID"] = Userid.ToString();
cookie.Expires = DateTime.Now.AddMonths(3);
Response.Cookies.Add(cookie);
</code>```

Title: ASP.NET MVC Cookie Implementation

Body:
I try to implement a basic cookie helper in my application.
Mainly I check in base controller everytime whether or not if cookie is set.
If cookie

public class MyCookie
{

    public static string CookieName {get;set;}
    public virtual User User { get; set; }
    public virtual Application App { get; set; }

    public MyCookie(Application app)
    {
        CookieName = "MyCookie" + app;
        App = app;
    }

    public void SetCookie(User user)
    {
        HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName] ?? new HttpCookie(CookieName);
        myCookie.Values["UserId"] = user.UserId.ToString();
        myCookie.Values["LastVisit"] = DateTime.Now.ToString();
        myCookie.Expires = DateTime.Now.AddDays(365);
        HttpContext.Current.Response.Cookies.Add(myCookie);
    }

    public HttpCookie GetCookie()
    {
        HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName];
        if(myCookie != null)
        {
            int userId = Convert.ToInt32(myCookie.Values["UserId"]);
            User user = session.Get<User>(userId);
            return user;
        }
        return null;
    }
}

if session is null I try to get from cookie or if session initialize I set cookie but I never see my cookie in browser. What is wrong?

I always start session but with userId=0
To get cookie and set session from cookie:

if (userId == 0)
{
    MyCookie myCookie = new MyCookie(_app);
    User user = cookieHelper.GetCookie();
    if (user != null)
        SessionHelper.SetSession(user);
}

Body:
Try this

HttpCookie cookie = new HttpCookie("Remember_Me");
cookie["userID"] = Userid.ToString();
cookie.Expires = DateTime.Now.AddMonths(3);
Response.Cookies.Add(cookie);


问:
CXF JAXB basics Equals/Hashcode
I have a problem generating equals and hashcode methods for my imported xsd files which are output to a separate location to my wsdl files. I currently have a .wsdl and .xsd file in the same folder. The .wsdl file imports these xsd files which have a different namespace to the wsdl file. When these xsd files are generated they do not contain equals or hashcode methods. Below is a sample of my pom/xml config and files:

```<code><wsdlOption>
    <wsdl>
        src/main/xml/wsdl/Rule.wsdl
    </wsdl>
    <wsdlLocation>classpath:wsdl/Rule.wsdl</wsdlLocation>
    <bindingFiles>
        <bindingFile>src/main/xml/wsdl/bindings.xjb</bindingFile>
    </bindingFiles>
    <extraargs>
        <extraarg>-impl</extraarg>
        <extraarg>-verbose</extraarg>
        <extraarg>-xjc-XsimpleEquals</extraarg>
        <extraarg>-xjc-XsimpleHashCode</extraarg>
    </extraargs>
</wsdlOption>
</code>```

Sample wsdl (imported Rule.xsd is not generating methods):

```<code><wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.ws.com/Rule/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="Rule"
targetNamespace="http://www.ws.com/Rule/">
<wsdl:types>
    <xsd:schema targetNamespace="http://http://www.ws.com/Rule/">
    </xsd:schema>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.ws.com/Rule/"
        xmlns:pref="http://www.xsd.com/Rule" xmlns:pref1="http://www.xsd.com/Common">
        <xsd:import schemaLocation="Rule.xsd"
            namespace="http://www.xsd.com/Rule">
        </xsd:import>
        <xsd:import schemaLocation="Common.xsd" namespace="http://www.xsd.com/Common"></xsd:import>
        <xsd:element name="ListGrid">
            <xsd:complexType>
                <xsd:sequence>
                    <xsd:element name="request"
                        type="pref:test" maxOccurs="1" minOccurs="1">
                    </xsd:element>
                </xsd:sequence>
            </xsd:complexType>
        </xsd:element>
</code>```

I assume this is a problem with the location of the generated xsd as I can get it to work by moving this to the same parent folder as the wsdl namespace. I would like to get this to work without moving these files locations as I have a large codebase that would require a large refactor if I do this.

Any suggestions would be welcome.

答:
I found a solution to this problem by adding the following to the pom.xml configuration:

```<code><extraarg>-p</extraarg>
<extraarg>http://www.xsd.com/Rule=com.xsd.rule</extraarg>
</code>```

Even though this does not change the namespace/package location it seems to now generate the imported files equals and hashcode methods.

Title: CXF JAXB basics Equals/Hashcode

Body:
I have a problem generating equals and hashcode methods for my imported xsd files which are output to a separate location to my wsdl files. I currently have a .wsdl and .xsd file in the same folder. The .wsdl file imports these xsd files which have a different namespace to the wsdl file. When these xsd files are generated they do not contain equals or hashcode methods. Below is a sample of my pom/xml config and files:

<wsdlOption>
    <wsdl>
        src/main/xml/wsdl/Rule.wsdl
    </wsdl>
    <wsdlLocation>classpath:wsdl/Rule.wsdl</wsdlLocation>
    <bindingFiles>
        <bindingFile>src/main/xml/wsdl/bindings.xjb</bindingFile>
    </bindingFiles>
    <extraargs>
        <extraarg>-impl</extraarg>
        <extraarg>-verbose</extraarg>
        <extraarg>-xjc-XsimpleEquals</extraarg>
        <extraarg>-xjc-XsimpleHashCode</extraarg>
    </extraargs>
</wsdlOption>

Sample wsdl (imported Rule.xsd is not generating methods):

<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.ws.com/Rule/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="Rule"
targetNamespace="http://www.ws.com/Rule/">
<wsdl:types>
    <xsd:schema targetNamespace="http://http://www.ws.com/Rule/">
    </xsd:schema>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.ws.com/Rule/"
        xmlns:pref="http://www.xsd.com/Rule" xmlns:pref1="http://www.xsd.com/Common">
        <xsd:import schemaLocation="Rule.xsd"
            namespace="http://www.xsd.com/Rule">
        </xsd:import>
        <xsd:import schemaLocation="Common.xsd" namespace="http://www.xsd.com/Common"></xsd:import>
        <xsd:element name="ListGrid">
            <xsd:complexType>
                <xsd:sequence>
                    <xsd:element name="request"
                        type="pref:test" maxOccurs="1" minOccurs="1">
                    </xsd:element>
                </xsd:sequence>
            </xsd:complexType>
        </xsd:element>

I assume this is a problem with the location of the generated xsd as I can get it to work by moving this to the same parent folder as the wsdl namespace. I would like to get this to work without moving these files locations as I have a large codebase that would require a large refactor if I do this.

Any suggestions would be welcome.

Body:
I found a solution to this problem by adding the following to the pom.xml configuration:

<extraarg>-p</extraarg>
<extraarg>http://www.xsd.com/Rule=com.xsd.rule</extraarg>

Even though this does not change the namespace/package location it seems to now generate the imported files equals and hashcode methods.


问:
Removing Rails/Spree image upload limit?
My client called today because they couldn't upload their images to their shopping site, and I have absolutely no idea where the upload file size limits are configured.

So here's my server configuration: Ubuntu 10.04LTS, Spree on Rails 2.3, Nginx.

Basically I want to remove the file-size upload limit.

Anyone know where I should go to get started?

答: Be sure to also checkout spree-user google group for Spree-related questions.  You might get a faster response there.</p>


问:
Memory leak when threads created, GC not effective
My application (written in C#) was OK in the past several months, but last week suddenly started to cause memory leak. I did not rebuild it, the binaries are the same!

While tried to find out what the root cause would be, I've ended up with the same test application I found later in Thread memory leak. So I simply copied the solution, suggested by Hans, and launched it. The memory leak persisted. Adding GC.Collect() caused only that memory growth became jaggy, as GC recovered a little part of the allocated memory in each call.

Checked with a profiler, all other managed or unmanaged objects were correctly finalized, except something related to threads.

```<code>class Program
{
    static void test()
    {
    }

    static void Main(string[] args)
    {
        int cnt = 0;
        while (true)
        {
            Thread test_thread = new Thread(() => test());
            test_thread.Start();
            if (++cnt % 256 == 0) GC.Collect();
            Thread.Sleep(20);
        }
    }
}
</code>```

Then I tried the same test code above on another PC, and (surprise!) it was working perfectly, and there was no memory leak at all.

UPDATE: Inspired by this topic
.Net Memory Leak when creating lots of threads
I tried to build for different target. Using x64 target seems to solve the issue in the test application. Unfortunately my real project contains a 3rd party subproject which cannot be rebuilt.

So it seems, something went wrong on my PC, which prevents GC from working correctly. Could you suggest, what to check, where to look? Thanks in advance.

答:
The solution was there among the comments to .Net Memory Leak when creating lots of threads. I checked that there is no leak in Windows Safe Mode. Then in normal mode, I started to kill non-vital processes. The antivirus process did the trick, as suggested by Hans Passant. Thanks!

My application is working again,  but the PC is without protection.
Also, there is no explanation and no lesson to learn.

Body:
My application (written in C#) was OK in the past several months, but last week suddenly started to cause memory leak. I did not rebuild it, the binaries are the same!

While tried to find out what the root cause would be, I've ended up with the same test application I found later in Thread memory leak. So I simply copied the solution, suggested by Hans, and launched it. The memory leak persisted. Adding GC.Collect() caused only that memory growth became jaggy, as GC recovered a little part of the allocated memory in each call.

Checked with a profiler, all other managed or unmanaged objects were correctly finalized, except something related to threads.

class Program
{
    static void test()
    {
    }

    static void Main(string[] args)
    {
        int cnt = 0;
        while (true)
        {
            Thread test_thread = new Thread(() => test());
            test_thread.Start();
            if (++cnt % 256 == 0) GC.Collect();
            Thread.Sleep(20);
        }
    }
}

Then I tried the same test code above on another PC, and (surprise!) it was working perfectly, and there was no memory leak at all.

UPDATE: Inspired by this topic
.Net Memory Leak when creating lots of threads
I tried to build for different target. Using x64 target seems to solve the issue in the test application. Unfortunately my real project contains a 3rd party subproject which cannot be rebuilt.

So it seems, something went wrong on my PC, which prevents GC from working correctly. Could you suggest, what to check, where to look? Thanks in advance.