问:
Why change xml file in Eclipse project will trigger project auto build
If there is a xml file in a Eclipse java project, and with "build Automatically" enabled, every time I change the xml file, and save, it will trigger Eclipse to build the project, and sometimes it cause much time to finish.

I just thought that xml files are just resource files, or at least it is not code change and should not trigger project build. What's the reason for this, and is there anyway to disable it?

答:
From Eclipse documentation,

```<code>A build is a process that derives new resources from existing ones, updates existing
resources, or both
</code>```

It is not just compilation of source code

Body:
From Eclipse documentation,

A build is a process that derives new resources from existing ones, updates existing
resources, or both

It is not just compilation of source code


来源: stackexchange

问:
Optimal memory for page loading in hosted environment?
In PHP, shared hosting environment, what shall be an optimal memory consumption to load a page. My current PHP script is consuming 3,183,440 bytes of memory. What shall I consider a good memory usage, to entertain say, 10000 users parallely?

Please be detailed, as I am a novice in optimization part.

Thanks in advance

答:
3MB isn't that bad - keep in mind that parts of PHP are shared, depending on which server is used (IIS, ngx, apache etc.) you can specify pools and clusters as well when having to scale up.

But the old adage testing is knowledge goes well here, try load tests on the site, concurrent 10 -> 100 -> 1000 connections and look at the performance metrics, it wil give you more insight on how much memory is required.

For comparison, the site I normally work on has an average of 300+ users concurrently online and the memory usage is just under 600MB, however I run certain processes locally it will easily use up 16MB.

ContentLicense: CC BY-SA 3.0


问:
Using async/await recursively with node request package
I'm making an http request using the response node library and I am trying to call it recursively (If the user made a commit on one day, check the previous day. If not, count up all the days to get the streak).

The problem is that the line

```<code>const githubResponse = await request(options);
</code>```

Spits out the error

```<code>Unexpected token o in JSON at position 1
</code>```

await request(options) doesn't seem to return the JSON GitHub API response I am expecting, but instead githubResponse seems to be an object that I can't use. I'm guessing I'm using async/await improperly, but I'm not sure how to fix it.

```<code>async function checkUserCommitForDate(user, date) {
    const options = {
        url: `https://api.github.com/search/commits?q=author:${user}+author-date:${date}`,
        headers: {
            'User-Agent': 'request',
            'Accept': 'application/vnd.github.cloak-preview'
        }
    };
    const githubResponse = await request(options)

    // I get an error on the next line

    if (JSON.parse(githubResponse).total_count > 0) {
        const previousDaysDate = moment(date).subtract(1, 'day').format('YYYY-MM-DD');
        let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
        streakCounter++;
        console.log('streakCounter', streakCounter);
        return streakCounter;
    } else {
        return 0;
    }
}
</code>```

UPDATE: It seems like this is not a promise, so I need to format this differently (as a callback). When I try this:

```<code>async function checkUserCommitForDate(user, date) {
    const options = {
        url: `https://api.github.com/search/commits?q=author:${user}+author-date:${date}`,
        headers: {
            'User-Agent': 'request',
            'Accept': 'application/vnd.github.cloak-preview'
        }
    };
    request(options, async function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        if (JSON.parse(body).total_count > 0) {
            const previousDaysDate = moment(date).subtract(1, 'day').format('YYYY-MM-DD');
            let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
            streakCounter++;
            console.log('streakCounter', streakCounter);
            return streakCounter;
        } else {
            return 0;
        }
    });
}
</code>```

The line

```<code>let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
</code>```

becomes the problem as streakCounter is undefined, making the log NaN.

答:
If you are upgraded to Node 8 LTS, then native util.promisfy can be used as below:

```<code>const { promisify } = require('util')
const request = promisify(require('request'))

async function checkUserCommitForDate(user, date) {
  const options = {
    url: `https://api.github.com/search/commits?q=author:${user}+author-date:${date}`,
    headers: {
      'User-Agent': 'request',
      'Accept': 'application/vnd.github.cloak-preview',
      'json':true
    }
  };

  try{
    const githubResponse = await request(options);
    if (githubResponse.body.total_count > 0) {
      const previousDaysDate = moment(date).subtract(1, 'day').format('YYYY-MM-DD');
      let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
      streakCounter++;
      console.log('streakCounter', streakCounter);
      return streakCounter;
    } else {
        return 0;
    }
  }
  catch(err){
    console.error(err)
    return 0;
  }
}
</code>```

Using json:true in the options, will reduce another step to parse as the response will be in JSON format.

Body:
I'm making an http request using the response node library and I am trying to call it recursively (If the user made a commit on one day, check the previous day. If not, count up all the days to get the streak).

The problem is that the line

const githubResponse = await request(options);

Spits out the error

Unexpected token o in JSON at position 1

await request(options) doesn't seem to return the JSON GitHub API response I am expecting, but instead githubResponse seems to be an object that I can't use. I'm guessing I'm using async/await improperly, but I'm not sure how to fix it.

async function checkUserCommitForDate(user, date) {
    const options = {
        url: `https://api.github.com/search/commits?q=author:${user}+author-date:${date}`,
        headers: {
            'User-Agent': 'request',
            'Accept': 'application/vnd.github.cloak-preview'
        }
    };
    const githubResponse = await request(options)

    // I get an error on the next line

    if (JSON.parse(githubResponse).total_count > 0) {
        const previousDaysDate = moment(date).subtract(1, 'day').format('YYYY-MM-DD');
        let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
        streakCounter++;
        console.log('streakCounter', streakCounter);
        return streakCounter;
    } else {
        return 0;
    }
}

UPDATE: It seems like this is not a promise, so I need to format this differently (as a callback). When I try this:

async function checkUserCommitForDate(user, date) {
    const options = {
        url: `https://api.github.com/search/commits?q=author:${user}+author-date:${date}`,
        headers: {
            'User-Agent': 'request',
            'Accept': 'application/vnd.github.cloak-preview'
        }
    };
    request(options, async function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        if (JSON.parse(body).total_count > 0) {
            const previousDaysDate = moment(date).subtract(1, 'day').format('YYYY-MM-DD');
            let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
            streakCounter++;
            console.log('streakCounter', streakCounter);
            return streakCounter;
        } else {
            return 0;
        }
    });
}

The line

let streakCounter = await checkUserCommitForDate(user, previousDaysDate);

becomes the problem as streakCounter is undefined, making the log NaN.

Body:
If you are upgraded to Node 8 LTS, then native util.promisfy can be used as below:

const { promisify } = require('util')
const request = promisify(require('request'))

async function checkUserCommitForDate(user, date) {
  const options = {
    url: `https://api.github.com/search/commits?q=author:${user}+author-date:${date}`,
    headers: {
      'User-Agent': 'request',
      'Accept': 'application/vnd.github.cloak-preview',
      'json':true
    }
  };

  try{
    const githubResponse = await request(options);
    if (githubResponse.body.total_count > 0) {
      const previousDaysDate = moment(date).subtract(1, 'day').format('YYYY-MM-DD');
      let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
      streakCounter++;
      console.log('streakCounter', streakCounter);
      return streakCounter;
    } else {
        return 0;
    }
  }
  catch(err){
    console.error(err)
    return 0;
  }
}

Using json:true in the options, will reduce another step to parse as the response will be in JSON format.


问:
Convert epoch to days
I have the following code:

```<code><?php
function cuantosdias($d){
    $d = strtotime($d);
    $c = strtotime("now");
    $e = $c - $d;
    return $e;
};
$fecha = "13-10-2016 00:00:00";
$cant = cuantosdias($fecha);
echo $cant/86400 . "\n";
</code>```

I get the days between 2 dates.

I wonder how can I get $cant in format:d H:i:s.

Is there a function to do that?

答:
Simply, you can try this way:</p>

```<code><?php

$fecha = "13-10-2016 00:00:00";

function dateDifference($date, $differenceFormat = '%y year(s) %m month(s) %d day(s) %H:%i:%s' )
{
    $datetime1 = date_create($date);
    $datetime2 = date_create();
    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}

echo dateDifference($fecha);
</code>```

Title: Convert epoch to days

Body:
I have the following code:

<?php
function cuantosdias($d){
    $d = strtotime($d);
    $c = strtotime("now");
    $e = $c - $d;
    return $e;
};
$fecha = "13-10-2016 00:00:00";
$cant = cuantosdias($fecha);
echo $cant/86400 . "\n";

I get the days between 2 dates.

I wonder how can I get $cant in format:d H:i:s.

Is there a function to do that?

Body:
Simply, you can try this way:

<?php

$fecha = "13-10-2016 00:00:00";

function dateDifference($date, $differenceFormat = '%y year(s) %m month(s) %d day(s) %H:%i:%s' )
{
    $datetime1 = date_create($date);
    $datetime2 = date_create();
    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}

echo dateDifference($fecha);


问:
valid_email not working along with callback function in codeigniter
Hello all i was using form_validation Library in codeigniter inside my application. I am making a password retrieving function. I have made a submit form of the email . Now, on the email input field i want to apply these validations.

required

valid_email

check email exist or not.

For the 3rd one i am using call back function to check the database and it worked fine. But with the call back function valid_email is not functioning. This is my controller functions.

```<code>     public function password_retrieve()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {

        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback__email_exists');
        if ($this->form_validation->run() == false) {
            $this->load->view('login_header');
            $this->load->view('password_retrieve');
            $this->load->view('login_footer');
        } else {

        }
    } else {
        $this->load->view('login_header');
        $this->load->view('password_retrieve');
        $this->load->view('login_footer');
    }
    }

    function _email_exists($email)
    {
    $this->load->model('users_model');

    $result = $result = $this->users_model->check_email_is_exist($email);
    if (!$result) {
        $this->form_validation->set_message(__FUNCTION__, 'This %s address does not exist!');
        return false;
    } else {
        return true;
    }
    }
</code>```

It should checked the valid_email rather than the going to the callback function.

In other mean i want to know what is the order of the rules. Is callback rule runs before the valid_email?

答:
By Searching the official documentation and git repository i have found out that there is not a particular order in which a function will run in codeigniter. This means $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback__email_exists');
In this case valid_email will run after the callback__email_exists. There is not a order in which first trim, then required and then valid_email will run.

So what i have done is to make a new function in my callback function which runs after the required but before the check_email.

Answering this question so that in future people can get the benefit from it. Cheers!

Body:
Hello all i was using form_validation Library in codeigniter inside my application. I am making a password retrieving function. I have made a submit form of the email . Now, on the email input field i want to apply these validations.

required

valid_email

check email exist or not.

For the 3rd one i am using call back function to check the database and it worked fine. But with the call back function valid_email is not functioning. This is my controller functions.

     public function password_retrieve()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {

        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback__email_exists');
        if ($this->form_validation->run() == false) {
            $this->load->view('login_header');
            $this->load->view('password_retrieve');
            $this->load->view('login_footer');
        } else {

        }
    } else {
        $this->load->view('login_header');
        $this->load->view('password_retrieve');
        $this->load->view('login_footer');
    }
    }

    function _email_exists($email)
    {
    $this->load->model('users_model');

    $result = $result = $this->users_model->check_email_is_exist($email);
    if (!$result) {
        $this->form_validation->set_message(__FUNCTION__, 'This %s address does not exist!');
        return false;
    } else {
        return true;
    }
    }

It should checked the valid_email rather than the going to the callback function.

In other mean i want to know what is the order of the rules. Is callback rule runs before the valid_email?


问:
reading a json file with nested arrays at every line in R
I have json file which contains 585 nested arrays. Each of the 585 arrays has the following structure:

```<code>[["12345678", [["12345678912345678", "dummy tweet #hashtag", "2015-05-20 15:33:11", "en"], ["12345678123456781", "dummy tweet again", "2015-05-18 22:08:30", "en"]]]
</code>```

each array has a user id, and a corresponding array of arrays of that has user's tweets, in which each array has, tweet id, tweet, date and language.

I tried to stream the file with jsonlite stream in function as followstest_json = stream_in(file("test.json")) but i get the following error:

```<code>Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  :
  arguments imply differing number of rows: 3189, 607, 219, 3120, 3091
closing file input connection.
</code>```

I then read 10 lines test10_json =readLines("test.json", n =10) which worked for me.

Now I wanted to read this json and tried fromJSON(test10_json) but I get this error:

```<code>Error: parse error: trailing garbage
          015-05-06 19:18:35", "en"]]] ["123456789", [["5101600420255
                     (right here) ------^
</code>```

which means that when it tries to read the next array/record (the second row of the file, 2nd user's record) it gives an error.
However when I read each user record separately as follows test10_row1 = fromJSON(test10_json[1]) it reads them individually. and creates a list of List of 2

```<code> $ : chr "19211550"
 $ : chr [1:3189, 1:4]
</code>```

where each of 1:3189 contains a list with tweet id, tweet, date and language.

First of all I would like to know how to read the file test.json altogether without having to read lines, if that is possible.

Secondly, I would like to after completing step 1, how to parse all arrays together to R, rather than parsing them individually.

Third, instead of getting a list of lists (for 585 records: 585 lists of 2 lists each with each list having as many lists as the number of tweets) I would like to get a dataframe which I could flatten.

答:
Well I read the whole document with test_json =readLines("test.json")
It has read all the user records for me

I converted each json record in R base using test_list = lapply(test_all,fromJSON)

Body:
I have json file which contains 585 nested arrays. Each of the 585 arrays has the following structure:

[["12345678", [["12345678912345678", "dummy tweet #hashtag", "2015-05-20 15:33:11", "en"], ["12345678123456781", "dummy tweet again", "2015-05-18 22:08:30", "en"]]]

each array has a user id, and a corresponding array of arrays of that has user's tweets, in which each array has, tweet id, tweet, date and language.

I tried to stream the file with jsonlite stream in function as followstest_json = stream_in(file("test.json")) but i get the following error:

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  :
  arguments imply differing number of rows: 3189, 607, 219, 3120, 3091
closing file input connection.

I then read 10 lines test10_json =readLines("test.json", n =10) which worked for me.

Now I wanted to read this json and tried fromJSON(test10_json) but I get this error:

Error: parse error: trailing garbage
          015-05-06 19:18:35", "en"]]] ["123456789", [["5101600420255
                     (right here) ------^

which means that when it tries to read the next array/record (the second row of the file, 2nd user's record) it gives an error.
However when I read each user record separately as follows test10_row1 = fromJSON(test10_json[1]) it reads them individually. and creates a list of List of 2

 $ : chr "19211550"
 $ : chr [1:3189, 1:4]

where each of 1:3189 contains a list with tweet id, tweet, date and language.

First of all I would like to know how to read the file test.json altogether without having to read lines, if that is possible.

Secondly, I would like to after completing step 1, how to parse all arrays together to R, rather than parsing them individually.

Third, instead of getting a list of lists (for 585 records: 585 lists of 2 lists each with each list having as many lists as the number of tweets) I would like to get a dataframe which I could flatten.


问:
nodejs async.queue call callback from other method
Is it possible to call the finish callback for a job from another function than the worker function? Because what I want to do is the following:

I receive a POST request which is pushed into the async.queue

The worker function provided to the async.queue sends then sends some data via sockets.

The request is finished, when the server receives back an answer also over the socket

The following is my setup:

```<code>io.on('connection', function(client) {
    client.setMaxListeners(0);

    client.on('answer', (data) => {
        console.log(data);
        console.log(request_queue.workersList());

        returnResponse(data, request_queue.workersList()[0].data, request_queue.workersList()[0].callback);
    })
});

var request_queue = asyn.queue(requestHandler, 1);

app.post('/', function(request, response) {

    request_queue.push({req: request, res: response}, () => {
        console.log("pushed new request");
    });

    console.log(request_queue.length());

});

function requestHandler(req_res, finish) {

    // Do something with the data received in the request

    io.sockets.emit('update_img', JSON.stringify(data_to_send));

}

function returnResponse(data, res_req, finish) {
    data = JSON.parse(data);
    var res = res_req.res;

    var error = data.error;

    if (error) {
        console.log("I WAS HERE");
        error = {};
        error['error'] = 'There has been an error!'
        res.json(error);
        finish("There was an error");
    }

    // send back actual response

    res.json(data);
    console.log("Right before finish");
    finish();
}
</code>```

Unfortunately, this produces the following error:

```<code>GET / 304 3.845 ms - -
1
[Function]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
DATA_RECEIVED
[ { data: { req: [Object], res: [Object] },
    callback: [Function],
    next: null,
    prev: null } ]
Right before finish
pushed new request
POST / 200 7901.287 ms - 267
16
17
18
19
20
21
22
23
24
DATA_RECEIVED
[ { data: { req: [Object], res: [Object] },
    callback: [Function],
    next: null,
    prev: null } ]
_http_outgoing.js:489
    throw new Error('Can\'t set headers after they are sent.');
    ^
</code>```

So it seems to me that the worker function has not finished correctly, otherwise the response object would be a different one right? I am not sure if I have passed the callback function of the worker correctly with request_queue.workersList()[0].callback.

Can anyone help me out?

答:
There must be a simpler way to do this. Lets add a global callbacks map were we can store a callback for each process. For that we need to identify the socket/POST by a unique id both share:

```<code> const callbacks = new Map();

 io.on('connection', function(client) {
  client.setMaxListeners(0);

  client.on('answer', (data) => {
    console.log(data);
    const cb = callbacks.get(data.id /*TODO*/);
    if(!cb) return client.emit("error","process with that id not found");
    cb(data);
    callbacks.delete(data.id);
  })
});
</code>```

So now we can add a callback to the socket wich will only ve called once. Usable like this:

```<code> app.post("/:id", function(req, res){
   callbacks.set( req.params.id, data => {
     res.json(data);
   });
});
</code>```

If you want to terminate the POST request after a certain time ( to prevent DOS attacks ) you might use a simple timeout:

```<code>app.post("/:id", function(req, res){
   callbacks.set( req.params.id, data => {
     res.json(data);
   });
   //recycle after inactive time:
   setTimeout( id => {
     if( !callbacks.has(id) ) return; //all fine, user answered already
     callbacks.delete(id);
     res.json({ error: "no answer from socket"});
  }, 10000, req.params.id);
});
</code>```

Body:
Is it possible to call the finish callback for a job from another function than the worker function? Because what I want to do is the following:

I receive a POST request which is pushed into the async.queue

The worker function provided to the async.queue sends then sends some data via sockets.

The request is finished, when the server receives back an answer also over the socket

The following is my setup:

io.on('connection', function(client) {
    client.setMaxListeners(0);

    client.on('answer', (data) => {
        console.log(data);
        console.log(request_queue.workersList());

        returnResponse(data, request_queue.workersList()[0].data, request_queue.workersList()[0].callback);
    })
});

var request_queue = asyn.queue(requestHandler, 1);

app.post('/', function(request, response) {

    request_queue.push({req: request, res: response}, () => {
        console.log("pushed new request");
    });

    console.log(request_queue.length());

});

function requestHandler(req_res, finish) {

    // Do something with the data received in the request

    io.sockets.emit('update_img', JSON.stringify(data_to_send));

}

function returnResponse(data, res_req, finish) {
    data = JSON.parse(data);
    var res = res_req.res;

    var error = data.error;

    if (error) {
        console.log("I WAS HERE");
        error = {};
        error['error'] = 'There has been an error!'
        res.json(error);
        finish("There was an error");
    }

    // send back actual response

    res.json(data);
    console.log("Right before finish");
    finish();
}

Unfortunately, this produces the following error:

GET / 304 3.845 ms - -
1
[Function]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
DATA_RECEIVED
[ { data: { req: [Object], res: [Object] },
    callback: [Function],
    next: null,
    prev: null } ]
Right before finish
pushed new request
POST / 200 7901.287 ms - 267
16
17
18
19
20
21
22
23
24
DATA_RECEIVED
[ { data: { req: [Object], res: [Object] },
    callback: [Function],
    next: null,
    prev: null } ]
_http_outgoing.js:489
    throw new Error('Can\'t set headers after they are sent.');
    ^

So it seems to me that the worker function has not finished correctly, otherwise the response object would be a different one right? I am not sure if I have passed the callback function of the worker correctly with request_queue.workersList()[0].callback.

Can anyone help me out?

Body:
There must be a simpler way to do this. Lets add a global callbacks map were we can store a callback for each process. For that we need to identify the socket/POST by a unique id both share:

 const callbacks = new Map();

 io.on('connection', function(client) {
  client.setMaxListeners(0);

  client.on('answer', (data) => {
    console.log(data);
    const cb = callbacks.get(data.id /*TODO*/);
    if(!cb) return client.emit("error","process with that id not found");
    cb(data);
    callbacks.delete(data.id);
  })
});

So now we can add a callback to the socket wich will only ve called once. Usable like this:

 app.post("/:id", function(req, res){
   callbacks.set( req.params.id, data => {
     res.json(data);
   });
});

If you want to terminate the POST request after a certain time ( to prevent DOS attacks ) you might use a simple timeout:

app.post("/:id", function(req, res){
   callbacks.set( req.params.id, data => {
     res.json(data);
   });
   //recycle after inactive time:
   setTimeout( id => {
     if( !callbacks.has(id) ) return; //all fine, user answered already
     callbacks.delete(id);
     res.json({ error: "no answer from socket"});
  }, 10000, req.params.id);
});


问:
How can i get my program to remove from end of list instead of start in python
```<code>class Node:
    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.size = 0
        self.head = None
        self.tail = None

    def append(self, data):
        node = Node()
        node.data = data
        if not self.head:
            self.head = node
            self.tail = node
            self.size = 1
            return
        self.tail.next = node
        self.tail = node
        self.size += 1

    def __repr__(self):
        return 'Stack(%s)' % str(self)

    def __iter__(self):
        current = self.head
        while current:
            yield current.data
            current = current.next

    def __str__(self):
        return '[%s]' % ', '.join([x for x in self])

    def __len__(self):
        return self.size

    def pop(self):
        data = self.head.data
        self.head = self.head.next
        return data

if __name__ == '__main__':
    list = Stack()

    reply = 0

    while reply!="5":

        print("1. Add to list")
        print("2. Display list")
        print("3. Size of list")
        print("4. Remove from list")
        print("5. Exit")

        reply = int(input("what would you like to do?"))

        if reply == 1:
            data = input("Add an element:")
            list.append(data)
        if reply == 2:
            print(list)
        if reply == 3:
            print(len(list))
        if reply == 4:
            list.pop()

        if reply == 5:
            print("good bye")
</code>```

I'm a fairly new to python , and for a class assignment i have been asked to implement a stack linked list with interface, i understand the basics of a linked list however, when i press 4 it should remove the last element which i have inputted , however it removes the first which is not (stack - last in first out)
Any help would be appreciated .

答:
Use the pop method; every Python list defines it:

```<code>whole = range(5)   # [0,1,2,3]
print whole.pop()  # 4
print whole        # [0, 1, 2, 3]
print whole.pop(0) # 0
print whole        # [1, 2, 3]
</code>```

Body:
class Node:
    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.size = 0
        self.head = None
        self.tail = None

    def append(self, data):
        node = Node()
        node.data = data
        if not self.head:
            self.head = node
            self.tail = node
            self.size = 1
            return
        self.tail.next = node
        self.tail = node
        self.size += 1

    def __repr__(self):
        return 'Stack(%s)' % str(self)

    def __iter__(self):
        current = self.head
        while current:
            yield current.data
            current = current.next

    def __str__(self):
        return '[%s]' % ', '.join([x for x in self])

    def __len__(self):
        return self.size

    def pop(self):
        data = self.head.data
        self.head = self.head.next
        return data

if __name__ == '__main__':
    list = Stack()

    reply = 0

    while reply!="5":

        print("1. Add to list")
        print("2. Display list")
        print("3. Size of list")
        print("4. Remove from list")
        print("5. Exit")

        reply = int(input("what would you like to do?"))

        if reply == 1:
            data = input("Add an element:")
            list.append(data)
        if reply == 2:
            print(list)
        if reply == 3:
            print(len(list))
        if reply == 4:
            list.pop()

        if reply == 5:
            print("good bye")

I'm a fairly new to python , and for a class assignment i have been asked to implement a stack linked list with interface, i understand the basics of a linked list however, when i press 4 it should remove the last element which i have inputted , however it removes the first which is not (stack - last in first out)
Any help would be appreciated .

Body:
Use the pop method; every Python list defines it:

whole = range(5)   # [0,1,2,3]
print whole.pop()  # 4
print whole        # [0, 1, 2, 3]
print whole.pop(0) # 0
print whole        # [1, 2, 3]


问:
Apache Airflow Multi Tenant
I'm attempting to work out how Airflow might work in a multi-tenant environment. Specifically the requirements should look something like this:

Two teams, TeamA and TeamB, are using a single Airflow instance.

Team's A  and B each have their own service user account: serviceUserA and ServiceUserB which they should run their jobs under.

For security reasons, Team A should not be able to create jobs that run under ServiceUserB and vice versa.

At this point it's not clear to me whether requirement 3. can be met with Airflow, short of giving each team a separate Airflow instance. Is there any way in which this can be achieved?

答:
It depends what you mean with Airflow Instance.

You could spin up 2 groups of Airflow services (webserver, scheduler, worker) through systemctl, each of them relying on a different airflow.cfg.

In the airflow.cfg you would then separate the 2 groups.

ContentLicense: CC BY-SA 4.0

Title: Apache Airflow Multi Tenant


问:
How to use let inside if block inside a do notation in haskell
I'm getting an error with the following code:

```<code>main = do
    putStrLn "Enter parameter"
    parameter <- getLine
    if head parameter == "c" then
        let object = getObject parameter
        print object
    else
        putStrLn "Error, try again"
        main
</code>```

The error I get is:

```<code>parse error on input `print'
</code>```

when trying to print the object. If I instead try to print the value of the function without saving it with let it works just fine, but I need to save the object for later use.

How should the syntax be to make it work?

Also in the "else" part I get the following error:

```<code>The function `putStrLn' is applied to two arguments,
    but its type `String -> IO ()' has only one
    In the expression: putStrLn "Error" main
</code>```

It thinks I try to run main as a parameter to putStrLn, but what I really want to do is first show the error and then run main again. How can I fix this?

Thanks in advance!

答:
There's a few issues with your code.

Firstly, there's the parse error. There's two ways to fix this. One is by using a let .. in block, as @Lee points out.

```<code>let object = getObject parameter
in  print object
</code>```

Alternatively, we can just start another do block in the else clause:

```<code>then do
   let object = getObject parameter
   print object
</code>```

Secondly, you're comparing the head of a string, to another string:

head parameter == "c"

getLine returns a string, so the head of a string is a character. We can just change this to

head parameter == 'c'

And finally, you're trying to do two statements in one block, similar to before in your else clause:

```<code>else
    putStrLn "Error, try again"
    main
</code>```

If you want to chain together multiple statements, we have to use a do block, as before:

```<code>else do
    putStrLn "Error, try again"
    main
</code>```

Putting it all together:

```<code>main = do
    putStrLn "Enter parameter"
    parameter <- getLine
    if head parameter == 'c' then do
        let object = getObject parameter
        print object
    else do
        putStrLn "Error, try again"
        main
</code>```

Body:
I'm getting an error with the following code:

main = do
    putStrLn "Enter parameter"
    parameter <- getLine
    if head parameter == "c" then
        let object = getObject parameter
        print object
    else
        putStrLn "Error, try again"
        main

The error I get is:

parse error on input `print'

when trying to print the object. If I instead try to print the value of the function without saving it with let it works just fine, but I need to save the object for later use.

How should the syntax be to make it work?

Also in the "else" part I get the following error:

The function `putStrLn' is applied to two arguments,
    but its type `String -> IO ()' has only one
    In the expression: putStrLn "Error" main

It thinks I try to run main as a parameter to putStrLn, but what I really want to do is first show the error and then run main again. How can I fix this?

Thanks in advance!

Body:
There's a few issues with your code.

Firstly, there's the parse error. There's two ways to fix this. One is by using a let .. in block, as @Lee points out.

let object = getObject parameter
in  print object

Alternatively, we can just start another do block in the else clause:

then do
   let object = getObject parameter
   print object

Secondly, you're comparing the head of a string, to another string:

head parameter == "c"

getLine returns a string, so the head of a string is a character. We can just change this to

head parameter == 'c'

And finally, you're trying to do two statements in one block, similar to before in your else clause:

else
    putStrLn "Error, try again"
    main

If you want to chain together multiple statements, we have to use a do block, as before:

else do
    putStrLn "Error, try again"
    main

Putting it all together:

main = do
    putStrLn "Enter parameter"
    parameter <- getLine
    if head parameter == 'c' then do
        let object = getObject parameter
        print object
    else do
        putStrLn "Error, try again"
        main


问:
How to remove margin-left and margin-right of col class in bootstrap?
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

```<code><div class="container">
    <div class="row">
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
        <div class="col-sm-6">
            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
        </div>
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
    </div>
</div>
</code>```

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

答:
In your css class add margin: 0 !important;
this will remove all margins.
If you want to remove just left and right margins and keep top and bottom you need to specify margin-left: 0 !important; margin-right: !important;

Body:
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!


问:
Close all other sub-menus on click
Hello everyone,
Thank you for taking the time to view this post.

I have the following problem I am trying to create a menu with sub-menus.

Menu should:

Open sub-menus on click. (working)

Sub-menus stay open on selected menu. (working)

3. Once clicked in other menus the previous sub-menus should close. (not working)

HTML

```<code>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <ul class="bottom-menu">
      <li class="drop"><a>Hyperlink 1</a></li>
      <li class="drop"><a>Hyperlink 2</a>
      <ul id="m1" class="bottom-menu-sub">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
    <li class="drop"><a>Hyperlink 3</a>
      <ul id="m2">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
    <li class="drop"><a>Hyperlink 4</a>
      <ul id="m3">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
</ul>
</code>```

CSS:

```<code>      .bottom-menu li ul {
      display:none;
      }
</code>```

JS:

```<code>jQuery(function ($) {
    // jQuery code in here can safely use $
    $('.bottom-menu li')
        .css({
        cursor: "pointer"
    });

    $(".drop>a").on('click', function (eventData) {
        var $listItem = $(this).closest('li');

        $listItem.find('ul').toggle();
        $listItem.toggleClass('open');

        $.cookie('open_items', 'the_value');
        openItems = new Array();
        $("li.drop").each(function (index, item) {
            if ($(item).hasClass('open')) {
                openItems.push(index);
            }
        });
        $.cookie('open_items', openItems.join(','));
    });

    if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
        previouslyOpenItems = $.cookie('open_items');
        openItemIndexes = previouslyOpenItems.split(',');
        $(openItemIndexes).each(function (index, item) {
            $("li.drop").eq(item).addClass('open').find('ul').toggle();
        });
    }
});
</code>```

jsFiddle

答:
As Flame already mentioned, what you want to do is close (hide) everything upon click

Edited your snipped by adding

```<code>            $('.bottom-menu ul').each(function() {
                $(this).hide();
            });
</code>```

after your click event (takes bottom-menu class, finds each unordered list inside and hides it)

https://codepen.io/anon/pen/WXZaNe

Title: Close all other sub-menus on click

Body:
Hello everyone,
Thank you for taking the time to view this post.

I have the following problem I am trying to create a menu with sub-menus.

Menu should:

Open sub-menus on click. (working)

Sub-menus stay open on selected menu. (working)

3. Once clicked in other menus the previous sub-menus should close. (not working)

HTML

Hyperlink 1

Hyperlink 2

Hyperlink Sub

Hyperlink Sub

Hyperlink Sub

Hyperlink 3

Hyperlink Sub

Hyperlink Sub

Hyperlink 4

Hyperlink Sub

Hyperlink Sub

CSS:

      .bottom-menu li ul {
      display:none;
      }

JS:

jQuery(function ($) {
    // jQuery code in here can safely use $
    $('.bottom-menu li')
        .css({
        cursor: "pointer"
    });

    $(".drop>a").on('click', function (eventData) {
        var $listItem = $(this).closest('li');

        $listItem.find('ul').toggle();
        $listItem.toggleClass('open');

        $.cookie('open_items', 'the_value');
        openItems = new Array();
        $("li.drop").each(function (index, item) {
            if ($(item).hasClass('open')) {
                openItems.push(index);
            }
        });
        $.cookie('open_items', openItems.join(','));
    });

    if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
        previouslyOpenItems = $.cookie('open_items');
        openItemIndexes = previouslyOpenItems.split(',');
        $(openItemIndexes).each(function (index, item) {
            $("li.drop").eq(item).addClass('open').find('ul').toggle();
        });
    }
});

jsFiddle

Body:
As Flame already mentioned, what you want to do is close (hide) everything upon click

Edited your snipped by adding

            $('.bottom-menu ul').each(function() {
                $(this).hide();
            });

after your click event (takes bottom-menu class, finds each unordered list inside and hides it)

https://codepen.io/anon/pen/WXZaNe


问:
round() for float in C++
I need a simple floating point rounding function, thus:

```<code>double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1
</code>```

I can find ceil() and floor() in the math.h - but not round().

Is it present in the standard C++ library under another name, or is it missing??

答:
As pointed out in comments and other answers, the ISO C++ standard library did not add round() until ISO C++11, when this function was pulled in by reference to the ISO C99 standard math library.

For positive operands in [½, ub] round(x) == floor (x + 0.5), where ub is 223 for float when mapped to IEEE-754 (2008) binary32, and 252 for double when it is mapped to IEEE-754 (2008)  binary64. The numbers 23 and 52 correspond to the number of stored mantissa bits in these two floating-point formats. For positive operands in [+0, ½) round(x) == 0, and for positive operands in (ub, +∞] round(x) == x. As the function is symmetric about the x-axis, negative arguments x can be handled according to round(-x) == -round(x).

This leads to the compact code below. It compiles into a reasonable number of machine instructions across various platforms. I observed the most compact code on GPUs, where my_roundf() requires about a dozen instructions. Depending on processor architecture and toolchain, this floating-point based approach could be either faster or slower than the integer-based implementation from newlib referenced in a different answer.

I tested my_roundf() exhaustively against the newlib roundf() implementation using Intel compiler version 13, with both /fp:strict and /fp:fast. I also checked that  the newlib version matches the roundf() in the mathimf library of the Intel compiler. Exhaustive testing is not possible for double-precision round(), however the code is structurally identical to the single-precision implementation.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>

float my_roundf (float x)
{
    const float half = 0.5f;
    const float one = 2 * half;
    const float lbound = half;
    const float ubound = 1L << 23;
    float a, f, r, s, t;
    s = (x < 0) ? (-one) : one;
    a = x * s;
    t = (a < lbound) ? x : s;
    f = (a < lbound) ? 0 : floorf (a + half);
    r = (a > ubound) ? x : (t * f);
    return r;
}

double my_round (double x)
{
    const double half = 0.5;
    const double one = 2 * half;
    const double lbound = half;
    const double ubound = 1ULL << 52;
    double a, f, r, s, t;
    s = (x < 0) ? (-one) : one;
    a = x * s;
    t = (a < lbound) ? x : s;
    f = (a < lbound) ? 0 : floor (a + half);
    r = (a > ubound) ? x : (t * f);
    return r;
}

uint32_t float_as_uint (float a)
{
    uint32_t r;
    memcpy (&r, &a, sizeof(r));
    return r;
}

float uint_as_float (uint32_t a)
{
    float r;
    memcpy (&r, &a, sizeof(r));
    return r;
}

float newlib_roundf (float x)
{
    uint32_t w;
    int exponent_less_127;

    w = float_as_uint(x);
    /* Extract exponent field. */
    exponent_less_127 = (int)((w & 0x7f800000) >> 23) - 127;
    if (exponent_less_127 < 23) {
        if (exponent_less_127 < 0) {
            /* Extract sign bit. */
            w &= 0x80000000;
            if (exponent_less_127 == -1) {
                /* Result is +1.0 or -1.0. */
                w |= ((uint32_t)127 << 23);
            }
        } else {
            uint32_t exponent_mask = 0x007fffff >> exponent_less_127;
            if ((w & exponent_mask) == 0) {
                /* x has an integral value. */
                return x;
            }
            w += 0x00400000 >> exponent_less_127;
            w &= ~exponent_mask;
        }
    } else {
        if (exponent_less_127 == 128) {
            /* x is NaN or infinite so raise FE_INVALID by adding */
            return x + x;
        } else {
            return x;
        }
    }
    x = uint_as_float (w);
    return x;
}

int main (void)
{
    uint32_t argi, resi, refi;
    float arg, res, ref;

    argi = 0;
    do {
        arg = uint_as_float (argi);
        ref = newlib_roundf (arg);
        res = my_roundf (arg);
        resi = float_as_uint (res);
        refi = float_as_uint (ref);
        if (resi != refi) { // check for identical bit pattern
            printf ("!!!! arg=%08x  res=%08x  ref=%08x\n", argi, resi, refi);
            return EXIT_FAILURE;
        }
        argi++;
    } while (argi);
    return EXIT_SUCCESS;
}
```

OwnerDisplayName: Roddy

Title: round() for float in C++

Body:
I need a simple floating point rounding function, thus:

double round(double);

round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1

I can find ceil() and floor() in the math.h - but not round().

Is it present in the standard C++ library under another name, or is it missing??


问:
Initializer list initialization of a member struct bitfield element causing bugs in IAR ARM
I have the following class structure in IAR:

```<code>class A
{
public:
    A(){}
    virtual ~A() {};
    virtual void load() {};
};

class C
{
public:
    C()
    {
        //C does other stuff, not relevant
    }
};

class D;

class B : public A
{
public:
    B() : invert(false) {};
    virtual ~B() {};
    void load()
    {
        //Irrelevant stuff done here
    }
private:
    C member_c;
    std::vector<D*> vector_of_d;
    struct {
        bool var_1:1;
        bool var_2:1;
        bool var_3:1;
        bool var_4:1;
        bool invert:1;
    };
};
</code>```

I am running into bugs with the assembly generated to initialize B, where it seems to be getting 'confused' about where the VTable pointer is vs where the anonymous struct bitfield is.  When it goes to set the invert bit false, it goes to the first word of the object (which is the VTable pointer) and flips a bit in the address.  When I later call load(), it follows the invalid VTable pointer and ends up finding a null pointer, which it then blindly follows.  Things obviously fall apart from there.

Here is an example of the code that would invoke this problem:

```<code>void load_A(A* to_be_loaded){
    if(to_be_loaded) to_be_loaded->load();
}

int main(){
   load_A(new B());
}
</code>```

Now the big question, is have I accidentally introduced some undefined behavior somewhere?  This is code that is being ported from GCC-ARM, where it worked fine, but now suddenly it is causing hard-faults when compiled with IAR.  My two theories are:

It's a compiler bug (I know, it's never a compiler bug)

It's non-standard behavior that GCC handled as an extension

As far as I can tell, there shouldn't be anything wrong with using an initializer list to initialize a field in an anonymous struct.  I do recognize that anonymous structs are a compiler extension, but they are documented in both IAR and GCC. Either way, IAR is not giving me any warning or error, and is generating clearly broken assembly.

Here is the assembly that it made for the B constructor

```<code>1 |    B() : invert(false) {};
2 |B::B():
3 |_ZN6BC1Ev:
4 |    0x80645e8: 0xb510         PUSH      {R4, LR}
5 |    0x80645ea: 0x4604         MOV       R4, R0
6 |    B() : invert(false) {};
7 |    0x80645ec: 0xf007 0xfb20  BL        A::subobject A() ; 0x806bc30
8 |    0x80645f0: 0x4807         LDR.N     R0, [PC, #0x1c]         ; 0x8088808 (134776840)
9 |    0x80645f2: 0x6020         STR       R0, [R4]
10|    0x80645f4: 0xf104 0x0018  ADD.W     R0, R4, #24             ; 0x18
11|    0x80645f8: 0xf00a 0xfadd  BL        C::C()              ; 0x806ebb6
12|    0x80645fc: 0xf104 0x001c  ADD.W     R0, R4, #28             ; 0x1c
13|    0x8064600: 0xf00e 0xff2e  BL        std::vector<D *>::vector() ; 0x8073460
14|    0x8064604: 0x7820         LDRB      R0, [R4]
15|    0x8064606: 0xf000 0x00ef  AND.W     R0, R0, #239            ; 0xef
16|    0x806460a: 0x7020         STRB      R0, [R4]
17|    B() : invert(false) {};
18|    0x806460c: 0x4620         MOV       R0, R4
19|    0x806460e: 0xbd10         POP       {R4, PC}
20|    0x8064610: 0x08088808     DC32      0x8088808 (134776840)
</code>```

On line 14, we load the value that R4 points to, which is the base address of our object.  It does not apply any offset to it, which means it points to the first thing in the object which is the VTable pointer.  It then continues with the assumption that it has the bitfield and unsets one bit on line 15 before putting it back into the object where it got it from on line 16.

For reference, if we change the constructor of B to not use initializer lists (shown below) it will work as expected:

```<code>class B : public A
{
public:
    B(){ invert = false; };
    virtual ~B() {};
    void load()
    {
        //Irrelevant stuff done here
    }
private:
    C member_c;
    std::vector<D*> vector_of_d;
    struct {
        bool var_1:1;
        bool var_2:1;
        bool var_3:1;
        bool var_4:1;
        bool invert:1;
    }
};
</code>```

The generated assembly is as follows, take note of the offset used in the LDRB and STRB instructions on lines 14 and 16.  This is the proper offset to access the bitfield in the object.

```<code>1 |    B(){ invert = false; };
2 |B::B():
3 |_ZN6BC1Ev:
4 |    0x80645e8: 0xb510         PUSH      {R4, LR}
5 |    0x80645ea: 0x4604         MOV       R4, R0
6 |    B(){ invert = false; };
7 |    0x80645ec: 0xf007 0xfb20  BL        A::subobject A() ; 0x806bc30
8 |    0x80645f0: 0x4807         LDR.N     R0, [PC, #0x20]         ; 0x8088808 (134776840)
9 |    0x80645f2: 0x6020         STR       R0, [R4]
10|    0x80645f4: 0xf104 0x0018  ADD.W     R0, R4, #24             ; 0x18
11|    0x80645f8: 0xf00a 0xfadd  BL        C::C()              ; 0x806ebb6
12|    0x80645fc: 0xf104 0x001c  ADD.W     R0, R4, #28             ; 0x1c
13|    0x8064600: 0xf00e 0xff2e  BL        std::vector<D *>::vector() ; 0x8073460
14|    0x8064604: 0x7820         LDRB      R0, [R4, #0x2c]
15|    0x8064606: 0xf000 0x00ef  AND.W     R0, R0, #239            ; 0xef
16|    0x806460a: 0x7020         STRB      R0, [R4, #0x2c]
17|    B(){ invert = false; };
18|    0x806460c: 0x4620         MOV       R0, R4
19|    0x806460e: 0xbd10         POP       {R4, PC}
20|    0x8064610: 0x08088808     DC32      0x8088808 (134776840)
</code>```

Side note, there is a slight change on line 8, but that's probably due to some offsets changes.

Does anyone have any insight as to what could be causing this?

答: This is a compiler bug and according to my investigations it triggers in at least EWARM 7.80.1 and 8.11.2. It does not trigger in EWARM 8.20.1. The bug triggers on all optimization levels and I can't think of another work-around than the one mentioned in the question.</p>

Body:
I have the following class structure in IAR:

class A
{
public:
    A(){}
    virtual ~A() {};
    virtual void load() {};
};

class C
{
public:
    C()
    {
        //C does other stuff, not relevant
    }
};

class D;

class B : public A
{
public:
    B() : invert(false) {};
    virtual ~B() {};
    void load()
    {
        //Irrelevant stuff done here
    }
private:
    C member_c;
    std::vector<D*> vector_of_d;
    struct {
        bool var_1:1;
        bool var_2:1;
        bool var_3:1;
        bool var_4:1;
        bool invert:1;
    };
};

I am running into bugs with the assembly generated to initialize B, where it seems to be getting 'confused' about where the VTable pointer is vs where the anonymous struct bitfield is.  When it goes to set the invert bit false, it goes to the first word of the object (which is the VTable pointer) and flips a bit in the address.  When I later call load(), it follows the invalid VTable pointer and ends up finding a null pointer, which it then blindly follows.  Things obviously fall apart from there.

Here is an example of the code that would invoke this problem:

void load_A(A* to_be_loaded){
    if(to_be_loaded) to_be_loaded->load();
}

int main(){
   load_A(new B());
}

Now the big question, is have I accidentally introduced some undefined behavior somewhere?  This is code that is being ported from GCC-ARM, where it worked fine, but now suddenly it is causing hard-faults when compiled with IAR.  My two theories are:

It's a compiler bug (I know, it's never a compiler bug)

It's non-standard behavior that GCC handled as an extension

As far as I can tell, there shouldn't be anything wrong with using an initializer list to initialize a field in an anonymous struct.  I do recognize that anonymous structs are a compiler extension, but they are documented in both IAR and GCC. Either way, IAR is not giving me any warning or error, and is generating clearly broken assembly.

Here is the assembly that it made for the B constructor

1 |    B() : invert(false) {};
2 |B::B():
3 |_ZN6BC1Ev:
4 |    0x80645e8: 0xb510         PUSH      {R4, LR}
5 |    0x80645ea: 0x4604         MOV       R4, R0
6 |    B() : invert(false) {};
7 |    0x80645ec: 0xf007 0xfb20  BL        A::subobject A() ; 0x806bc30
8 |    0x80645f0: 0x4807         LDR.N     R0, [PC, #0x1c]         ; 0x8088808 (134776840)
9 |    0x80645f2: 0x6020         STR       R0, [R4]
10|    0x80645f4: 0xf104 0x0018  ADD.W     R0, R4, #24             ; 0x18
11|    0x80645f8: 0xf00a 0xfadd  BL        C::C()              ; 0x806ebb6
12|    0x80645fc: 0xf104 0x001c  ADD.W     R0, R4, #28             ; 0x1c
13|    0x8064600: 0xf00e 0xff2e  BL        std::vector<D *>::vector() ; 0x8073460
14|    0x8064604: 0x7820         LDRB      R0, [R4]
15|    0x8064606: 0xf000 0x00ef  AND.W     R0, R0, #239            ; 0xef
16|    0x806460a: 0x7020         STRB      R0, [R4]
17|    B() : invert(false) {};
18|    0x806460c: 0x4620         MOV       R0, R4
19|    0x806460e: 0xbd10         POP       {R4, PC}
20|    0x8064610: 0x08088808     DC32      0x8088808 (134776840)

On line 14, we load the value that R4 points to, which is the base address of our object.  It does not apply any offset to it, which means it points to the first thing in the object which is the VTable pointer.  It then continues with the assumption that it has the bitfield and unsets one bit on line 15 before putting it back into the object where it got it from on line 16.

For reference, if we change the constructor of B to not use initializer lists (shown below) it will work as expected:

class B : public A
{
public:
    B(){ invert = false; };
    virtual ~B() {};
    void load()
    {
        //Irrelevant stuff done here
    }
private:
    C member_c;
    std::vector<D*> vector_of_d;
    struct {
        bool var_1:1;
        bool var_2:1;
        bool var_3:1;
        bool var_4:1;
        bool invert:1;
    }
};

The generated assembly is as follows, take note of the offset used in the LDRB and STRB instructions on lines 14 and 16.  This is the proper offset to access the bitfield in the object.

1 |    B(){ invert = false; };
2 |B::B():
3 |_ZN6BC1Ev:
4 |    0x80645e8: 0xb510         PUSH      {R4, LR}
5 |    0x80645ea: 0x4604         MOV       R4, R0
6 |    B(){ invert = false; };
7 |    0x80645ec: 0xf007 0xfb20  BL        A::subobject A() ; 0x806bc30
8 |    0x80645f0: 0x4807         LDR.N     R0, [PC, #0x20]         ; 0x8088808 (134776840)
9 |    0x80645f2: 0x6020         STR       R0, [R4]
10|    0x80645f4: 0xf104 0x0018  ADD.W     R0, R4, #24             ; 0x18
11|    0x80645f8: 0xf00a 0xfadd  BL        C::C()              ; 0x806ebb6
12|    0x80645fc: 0xf104 0x001c  ADD.W     R0, R4, #28             ; 0x1c
13|    0x8064600: 0xf00e 0xff2e  BL        std::vector<D *>::vector() ; 0x8073460
14|    0x8064604: 0x7820         LDRB      R0, [R4, #0x2c]
15|    0x8064606: 0xf000 0x00ef  AND.W     R0, R0, #239            ; 0xef
16|    0x806460a: 0x7020         STRB      R0, [R4, #0x2c]
17|    B(){ invert = false; };
18|    0x806460c: 0x4620         MOV       R0, R4
19|    0x806460e: 0xbd10         POP       {R4, PC}
20|    0x8064610: 0x08088808     DC32      0x8088808 (134776840)

Side note, there is a slight change on line 8, but that's probably due to some offsets changes.

Does anyone have any insight as to what could be causing this?


问:
Why does MySQL return duplicate information in the returned JOIN array?
I'm wondering if I'm doing something wrong, or if this is just a quirk in how everything is processed in MySQL. Here's the setup: (I can't seem to find this exact topic anywhere else)

I have two tables order and menu.

menu has an 'id' (for the item), an 'item' and three prices ('prc1' 'prc2' 'prc3') in each row.

```<code>menu +----+----------+------+------+------+
     |'id'|  'item'  |'prc1'|'prc2'|'prc3'|
     +----+----------+------+------+------+
     |  1 | 'tshirt' | 3.00 | 4.50 | 4.00 |
     |  2 | 'socks'  | 1.00 | 2.50 | 2.00 |
     +----+----------+------+------+------+
</code>```

order also has an item id to match against the order menu, ('i_id'), and an integer I use for filtering the prices later in php ('prc_id').

```<code>order +------+--------+
      |'i_id'|'prc_id'|
      +--------+------+
      |  1   |   1    | # i_id matches id - tshirt and informs to use prc1
      |  2   |   3    | # i_id matchis id - socks and uses prc3
      +--------+------+
</code>```

I use JOIN to match the orders up to the items

```<code>"SELECT order.prc_id, menu.item, menu.prc1, menu.prc2, menu.prc3
        FROM order
        LEFT JOIN menu
        ON order.i_id = menu.id"
</code>```

I then get the result back, and initially to make sure everything panned out, I printed the array:

```<code>$result = mysql_query($query)
while($row = mysql_fetch_array($result))
    {
        print_r($row);
    }
</code>```

This is the array I get back (obviously dummy info for the initial tests):

```<code>Array
 (
    [0] => 1 [prc_id] => 1         #the value (1) for 'prc_id' is given twice
    [1] => tshirt [item] => tshirt #the value (tshirt) for 'item' is given twice
    [2] => 3.00 [prc1] => 3.00     #the value (3.00) for 'prc1' is given twice
    [3] => 4.50 [prc2] => 4.50     #etc
    [4] => 4.00 [prc3] => 4.00

    [0] => 3 [prc_id] => 3
    [1] => socks [item] => socks
    [2] => 1.00 [prc1] => 1.00
    [3] => 2.50 [prc2] => 2.50
    [4] => 2.00 [prc3] => 2.00
 )
</code>```

So my question(finally, right? xD)... Why is duplicate data sent back in the array response?

Have I done something wrong? Am I overlooking something?

It's not a huge issue, it doesn't affect my end result, I'd just like to be as precise as possible.

Thank you for your time. :)

答:
If think this is a PHP print_r() problem.

print_r() return a numeric representation and the second the named store row.

EDIT:

Try your query with the Database Query Tool then you will see the original result.

ContentLicense: CC BY-SA 2.5

Body:
I'm wondering if I'm doing something wrong, or if this is just a quirk in how everything is processed in MySQL. Here's the setup: (I can't seem to find this exact topic anywhere else)

I have two tables order and menu.

menu has an 'id' (for the item), an 'item' and three prices ('prc1' 'prc2' 'prc3') in each row.

menu +----+----------+------+------+------+
     |'id'|  'item'  |'prc1'|'prc2'|'prc3'|
     +----+----------+------+------+------+
     |  1 | 'tshirt' | 3.00 | 4.50 | 4.00 |
     |  2 | 'socks'  | 1.00 | 2.50 | 2.00 |
     +----+----------+------+------+------+

order also has an item id to match against the order menu, ('i_id'), and an integer I use for filtering the prices later in php ('prc_id').

order +------+--------+
      |'i_id'|'prc_id'|
      +--------+------+
      |  1   |   1    | # i_id matches id - tshirt and informs to use prc1
      |  2   |   3    | # i_id matchis id - socks and uses prc3
      +--------+------+

I use JOIN to match the orders up to the items

"SELECT order.prc_id, menu.item, menu.prc1, menu.prc2, menu.prc3
        FROM order
        LEFT JOIN menu
        ON order.i_id = menu.id"

I then get the result back, and initially to make sure everything panned out, I printed the array:

$result = mysql_query($query)
while($row = mysql_fetch_array($result))
    {
        print_r($row);
    }

This is the array I get back (obviously dummy info for the initial tests):

Array
 (
    [0] => 1 [prc_id] => 1         #the value (1) for 'prc_id' is given twice
    [1] => tshirt [item] => tshirt #the value (tshirt) for 'item' is given twice
    [2] => 3.00 [prc1] => 3.00     #the value (3.00) for 'prc1' is given twice
    [3] => 4.50 [prc2] => 4.50     #etc
    [4] => 4.00 [prc3] => 4.00

    [0] => 3 [prc_id] => 3
    [1] => socks [item] => socks
    [2] => 1.00 [prc1] => 1.00
    [3] => 2.50 [prc2] => 2.50
    [4] => 2.00 [prc3] => 2.00
 )

So my question(finally, right? xD)... Why is duplicate data sent back in the array response?

Have I done something wrong? Am I overlooking something?

It's not a huge issue, it doesn't affect my end result, I'd just like to be as precise as possible.

Thank you for your time. :)


问:
Concatenation of list of 3-dimensional tensors along a specific axis in Keras
```<code>for i in range(y_word_max_len):
    sub_decoder_input = gather(main_decoder,(i))
    # print(sub_decoder_input)
    sub_decoder_input_repeated = RepeatVector(y_char_max_len)(sub_decoder_input)
    sub_decoder = LSTM(256,return_sequences=True,name='sub_decoder')(sub_decoder_input_repeated)
    sub_decoder_output = TimeDistributed(Dense(58,activation='softmax'),name='sub_decoder_output')(sub_decoder)
    sub_decoder_output_reshaped = Reshape((1,y_char_max_len,58))(sub_decoder_output)
    print("Sub decoder output is ",sub_decoder_output_reshaped)
</code>```

I have written the above snippet where y_word_max_len = 9

and main_decoder is a tensor of shape (None,9,256)

and y_char_max_len = 7

58 is the size of my output
after the snippet was excecuted the output was

Sub decoder output is  Tensor("reshape_2/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_3/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_4/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_5/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_6/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_7/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_8/Reshape:0", shape=(?, 1, 7,
  58),  dtype=float32)

Sub decoder output is  Tensor("reshape_9/Reshape:0", shape=(?, 1, 7,
  58),  dtype=float32)

Sub decoder output is  Tensor("reshape_10/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Now I want to concatenate all the tensors (9) thus obtained into a single resultant tensor of

shape (?,9,7,58)

how can I achieve that in Keras.
Thanks

答:
Add a Concatenate layer:

```<code>joined = Concatenate(axis=1)([sub1, sub2, sub3, sub4, sub5....])
</code>```

For that, the best is to create a list of the subtensors and use the loop to append to this list:

```<code>subTensors = []
for ..... :
    #calculations
    subTensors.append(sub_decoder_output_reshaped)

joined = Concatenate(axis=1)(subTensors)
</code>```

Body:
for i in range(y_word_max_len):
    sub_decoder_input = gather(main_decoder,(i))
    # print(sub_decoder_input)
    sub_decoder_input_repeated = RepeatVector(y_char_max_len)(sub_decoder_input)
    sub_decoder = LSTM(256,return_sequences=True,name='sub_decoder')(sub_decoder_input_repeated)
    sub_decoder_output = TimeDistributed(Dense(58,activation='softmax'),name='sub_decoder_output')(sub_decoder)
    sub_decoder_output_reshaped = Reshape((1,y_char_max_len,58))(sub_decoder_output)
    print("Sub decoder output is ",sub_decoder_output_reshaped)

I have written the above snippet where y_word_max_len = 9

and main_decoder is a tensor of shape (None,9,256)

and y_char_max_len = 7

58 is the size of my output
after the snippet was excecuted the output was

Sub decoder output is  Tensor("reshape_2/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_3/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_4/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_5/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_6/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_7/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Sub decoder output is  Tensor("reshape_8/Reshape:0", shape=(?, 1, 7,
  58),  dtype=float32)

Sub decoder output is  Tensor("reshape_9/Reshape:0", shape=(?, 1, 7,
  58),  dtype=float32)

Sub decoder output is  Tensor("reshape_10/Reshape:0", shape=(?, 1, 7,
  58), dtype=float32)

Now I want to concatenate all the tensors (9) thus obtained into a single resultant tensor of

shape (?,9,7,58)

how can I achieve that in Keras.
Thanks

Body:
Add a Concatenate layer:

joined = Concatenate(axis=1)([sub1, sub2, sub3, sub4, sub5....])

For that, the best is to create a list of the subtensors and use the loop to append to this list:

subTensors = []
for ..... :
    #calculations
    subTensors.append(sub_decoder_output_reshaped)

joined = Concatenate(axis=1)(subTensors)


问:
C# listView, how do I add items to columns 2, 3 and 4 etc?
To add items to column 1 in my listView control (Winform) I'm using listView1.Items.Add, this works fine but how do I add items to columns 2 and 3 etc?

答:
You can add items / sub-items to the ListView like:

```<code>ListViewItem item = new ListViewItem(new []{"1","2","3","4"});
listView1.Items.Add(item);
</code>```

But I suspect your problem is with the View Type. Set it in the designer to Details or do the following in code:

```<code>listView1.View = View.Details;
</code>```

OwnerDisplayName: Steve

LastEditorDisplayName: buyutec

Body:
You can add items / sub-items to the ListView like:

ListViewItem item = new ListViewItem(new []{"1","2","3","4"});
listView1.Items.Add(item);

But I suspect your problem is with the View Type. Set it in the designer to Details or do the following in code:

listView1.View = View.Details;

OwnerDisplayName: bruno conde


问:
Is there a way to keep docstrings separate from the functions they document?
I'm working on a module with many small functions but whose docstrings tend to be quite long. The docstrings make working on the module irritating as I have to constantly scroll over a long docstring to find a little bit of actual code.

Is there a way to keep docstrings separate from the functions they document? I'd really like to be able to specify the docstrings at the end of the file away from the code or, even better, in a separate file.

答:
The docstring for a function is available as the special attribute __doc__.

```<code>>>> def f(x):
...     "return the square of x"
...     return x * x
>>> f.__doc__
'return the square of x'
>>> help(f)
(help page with appropriate docstring)
>>> f.__doc__ = "Return the argument squared"
>>> help(f)
(help page with new docstring)
</code>```

That demonstrates the technique, anyway. In practice you can:

```<code>def f(x):
    return x * x

f.__doc__ = """
Return the square of the function argument.

Arguments: x - number to square

Return value: x squared

Exceptions: none

Global variables used: none

Side effects: none

Limitations: none
"""
</code>```

...or whatever you want to put in your docstrings.

Body:
The docstring for a function is available as the special attribute __doc__.

>>> def f(x):
...     "return the square of x"
...     return x * x
>>> f.__doc__
'return the square of x'
>>> help(f)
(help page with appropriate docstring)
>>> f.__doc__ = "Return the argument squared"
>>> help(f)
(help page with new docstring)

That demonstrates the technique, anyway. In practice you can:

def f(x):
    return x * x

f.__doc__ = """
Return the square of the function argument.

Arguments: x - number to square

Return value: x squared

Exceptions: none

Global variables used: none

Side effects: none

Limitations: none
"""

...or whatever you want to put in your docstrings.


问:
Python: Concatenate 2 irregular sized images by automatically detecting the sizes
Problem Statement: I have 2 images of different sizes. First image (1320 x 950) and second image (1260 x 744). I am interested in concatenating these images next to each other so that they fit on my screen monitor (screen resolution: 1920 x 1080). Tried using np.concatenate but the problem is that the images need to be of same sizes. I tried the following but I was not able to solve this issue. How could I solve the problem?

What I tried:

```<code>for i in range(File_start,File_stop,1):
    img1 = cv2.imread('Z:/04_RD/PP/img'+'_'+str(i)+'.jpg')
    img2 = cv2.imread('Z:/04_RD/GRF/GRF'+'_'+str(i)+'.jpg')

    h1, w1 = img1.shape[:2]
    h2, w2 = img2.shape[:2]

    visl = np.zeros((max(h1, h2), w1+w2,3), np.uint8)

    visl[:h1, :w1,:3] = img1
    visl[:h2, w1:w1+w2,:3] = img2

    cv2.imwrite("Final_" + str(i) + ".jpg", visl)
</code>```

But this just concatenates the image next to the other. As a result, I am unable to view it completely on the screen.

I checked on an online tool: https://www.imgonline.com.ua/eng/combine-two-images-into-one.php

This could automatically resize and place 2 images next to each other.

enter image description here

I was wondering how I could achieve this using the python code?

答:
You can resize the images using

```<code>dstimg = cv2.resize(srcimg,(x_,y_))
</code>```

where x_ and y_ is the width and height of the destination image,dstimg that you want.

This way, you can resize both images to half of your screen resolution before concatenating them together

Body:
Problem Statement: I have 2 images of different sizes. First image (1320 x 950) and second image (1260 x 744). I am interested in concatenating these images next to each other so that they fit on my screen monitor (screen resolution: 1920 x 1080). Tried using np.concatenate but the problem is that the images need to be of same sizes. I tried the following but I was not able to solve this issue. How could I solve the problem?

What I tried:

for i in range(File_start,File_stop,1):
    img1 = cv2.imread('Z:/04_RD/PP/img'+'_'+str(i)+'.jpg')
    img2 = cv2.imread('Z:/04_RD/GRF/GRF'+'_'+str(i)+'.jpg')

    h1, w1 = img1.shape[:2]
    h2, w2 = img2.shape[:2]

    visl = np.zeros((max(h1, h2), w1+w2,3), np.uint8)

    visl[:h1, :w1,:3] = img1
    visl[:h2, w1:w1+w2,:3] = img2

    cv2.imwrite("Final_" + str(i) + ".jpg", visl)

But this just concatenates the image next to the other. As a result, I am unable to view it completely on the screen.

I checked on an online tool: https://www.imgonline.com.ua/eng/combine-two-images-into-one.php

This could automatically resize and place 2 images next to each other.

enter image description here

I was wondering how I could achieve this using the python code?

Body:
You can resize the images using

dstimg = cv2.resize(srcimg,(x_,y_))

where x_ and y_ is the width and height of the destination image,dstimg that you want.

This way, you can resize both images to half of your screen resolution before concatenating them together


问:
ElasticSearch - Get different types from different indices
I have two indices: A and B.

A has the following types: car, motorbike and van.

B has the following types: bus, car and pickup.

I want to be able to have a single query which gets motorbike and van from A and car and pickup from B.

I want to use a filter to do this and currently, I have:

```<code>.filter(
   not(
      should(
         termsQuery("key", Seq("car", "bus"))
      )
   )
)
</code>```

But obviously, this will filter car for both indices. I know I can do two separate queries for each index and filter different types for each but I want to avoid this if possible.

Is it possible to do what I am trying to do in a single query?

答:
You can do something like this.</p>

```<code>GET _search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": {
                    "value": "A"
                  }
                }
              },
              {
                "terms": {
                  "_type":  ["motorbike","van"]

                }
              }
            ]
          }
        },
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": {
                    "value": "B"
                  }
                }
              },
              {
                "terms": {
                  "_type": ["car","pickup"]
                }
              }
            ]
          }
        }
      ]
    }
  }
}
</code>```

Body:
I have two indices: A and B.

A has the following types: car, motorbike and van.

B has the following types: bus, car and pickup.

I want to be able to have a single query which gets motorbike and van from A and car and pickup from B.

I want to use a filter to do this and currently, I have:

.filter(
   not(
      should(
         termsQuery("key", Seq("car", "bus"))
      )
   )
)

But obviously, this will filter car for both indices. I know I can do two separate queries for each index and filter different types for each but I want to avoid this if possible.

Is it possible to do what I am trying to do in a single query?

Body:
You can do something like this.

GET _search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": {
                    "value": "A"
                  }
                }
              },
              {
                "terms": {
                  "_type":  ["motorbike","van"]

                }
              }
            ]
          }
        },
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": {
                    "value": "B"
                  }
                }
              },
              {
                "terms": {
                  "_type": ["car","pickup"]
                }
              }
            ]
          }
        }
      ]
    }
  }
}


问:
Javascript constructor from string variable in angular
I've got a little angular (v1.5.11) app where I'm trying to instantiate an object from a string variable. This code used to work in my old setup but after changing from bower/gulp to webpack (3.8.1), I'm now getting the error below. I'm not sure whether this is caused by my new import statement or something.

A similar question (Javascript "Not a Constructor" Exception while creating objects) dicussed the problem but I wasn't able to get get any of the solutions to work in my example which is why I'm thinking it might be down to the import or the pojo structure itself?

Error:

```<code>TypeError: $window[iteratorType] is not a constructor
</code>```

Code:

MyService.js

```<code>import ListIterator from './util/listiterator.pojo.js';

MyService.$inject = ['$log', '$window'];

function MyService($log, $window) {
  ...
  // this variable is obviously dynamic but for now I made it a static string
  var iteratorType = 'ListIterator';
  var iterator = new $window[iteratorType](); //<-- breaks as $window[iteratorType] is undefined
  //var iterator = new ListIterator();  <-- this works just fine
  ...
</code>```

listiterator.pojo.js

```<code>var ListIterator = function() {
    this.executedIterations = 0;
    this.iter = null;
};
...
export default ListIterator;
</code>```

答:
If you don't want to change any of your code, you could tell webpack to provide your service. This will make it available under window scope:

```<code>rules: [{
    test: require.resolve('./util/listiterator.pojo.js'), //the correct absolute path
    use: [{
        loader: 'expose-loader',
        options: 'ListIterator'
      }
    ]
  }
]
</code>```

This is untested with your example, but works fine in my setup with Highcharts and AngularJS.

EDIT

You have to install npm i -D expose-loader of course.

Body:
I've got a little angular (v1.5.11) app where I'm trying to instantiate an object from a string variable. This code used to work in my old setup but after changing from bower/gulp to webpack (3.8.1), I'm now getting the error below. I'm not sure whether this is caused by my new import statement or something.

A similar question (Javascript "Not a Constructor" Exception while creating objects) dicussed the problem but I wasn't able to get get any of the solutions to work in my example which is why I'm thinking it might be down to the import or the pojo structure itself?

Error:

TypeError: $window[iteratorType] is not a constructor

Code:

MyService.js

import ListIterator from './util/listiterator.pojo.js';

MyService.$inject = ['$log', '$window'];

function MyService($log, $window) {
  ...
  // this variable is obviously dynamic but for now I made it a static string
  var iteratorType = 'ListIterator';
  var iterator = new $window[iteratorType](); //<-- breaks as $window[iteratorType] is undefined
  //var iterator = new ListIterator();  <-- this works just fine
  ...

listiterator.pojo.js

var ListIterator = function() {
    this.executedIterations = 0;
    this.iter = null;
};
...
export default ListIterator;

Body:
If you don't want to change any of your code, you could tell webpack to provide your service. This will make it available under window scope:

rules: [{
    test: require.resolve('./util/listiterator.pojo.js'), //the correct absolute path
    use: [{
        loader: 'expose-loader',
        options: 'ListIterator'
      }
    ]
  }
]

This is untested with your example, but works fine in my setup with Highcharts and AngularJS.

EDIT

You have to install npm i -D expose-loader of course.


问:
compare two arrays for common Items and return another array with the common items
So the problem is I have two array and have to check them for common items.Usual stuff, very easy.But the tricky thing for me is that I have to return another array with the elements that have been found to be common.I cannot not use any Collections.Thanks in advance.This is my code so far!</p>

```<code>public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}
</code>```

答:
In case someone was wondering how the "chasing" algorithm mentioned by @user3438137 looks like: </p>

```<code>int[] sorted1 = Arrays.copyOf(array1, array1.length);
Arrays.sort(sorted1);
int[] sorted2 = Arrays.copyOf(array2, array2.length);
Arrays.sort(sorted2);
int[] common = new int[Math.min(sorted1.length, sorted2.length)];
int numCommonElements = 0, firstIndex = 0; secondIndex = 0;
while (firstIndex < sorted1.length && secondIndex < sorted2.length) {
    if (sorted1[firstIndex] < sorted2[secondIndex]) firstIndex++;
    else if (sorted1[firstIndex] == sorted2[secondIndex]) {
        common[numCommonElements] = sorted1[firstIndex];
        numCommonElements++;
        firstIndex++;
        secondIndex++;
    }
    else secondIndex++;
}
// optionally trim the commonElements array to numCommonElements size
</code>```

Body:
So the problem is I have two array and have to check them for common items.Usual stuff, very easy.But the tricky thing for me is that I have to return another array with the elements that have been found to be common.I cannot not use any Collections.Thanks in advance.This is my code so far!

public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}

Body:
In case someone was wondering how the "chasing" algorithm mentioned by @user3438137 looks like:

int[] sorted1 = Arrays.copyOf(array1, array1.length);
Arrays.sort(sorted1);
int[] sorted2 = Arrays.copyOf(array2, array2.length);
Arrays.sort(sorted2);
int[] common = new int[Math.min(sorted1.length, sorted2.length)];
int numCommonElements = 0, firstIndex = 0; secondIndex = 0;
while (firstIndex < sorted1.length && secondIndex < sorted2.length) {
    if (sorted1[firstIndex] < sorted2[secondIndex]) firstIndex++;
    else if (sorted1[firstIndex] == sorted2[secondIndex]) {
        common[numCommonElements] = sorted1[firstIndex];
        numCommonElements++;
        firstIndex++;
        secondIndex++;
    }
    else secondIndex++;
}
// optionally trim the commonElements array to numCommonElements size


问:
Retrive data with PHP
I am having a project using PHP and Postgres. I tried to write a function to get all infomation from one class required from user's input. Below is the version does not work. The commented part is the one that did pretty well but I need to put it into function for reusing target.</p>

```<code>function getInfoClass($classID) {

        $query = "SELECT * FROM Class
                  WHERE ID = '{$classID}';";
        $result = pg_query($db, $query);
        return  pg_fetch_assoc($result);
    }

$row = getInfoClass($_SESSION["classID"]);
echo $row['id'];

//$query = "SELECT * FROM Class
//            WHERE ID = '{$_SESSION["classID"]}';";
//$result = pg_query($db, $query);

//while($row = pg_fetch_assoc($result)) {
//  echo $row['id'];
//}
</code>```

答: I think you might be running into scope issues here. Make sure to read the php error_log since I'm pretty sure that $db is not declared within the function. If you are using classes and its defined within the class then try $this->db. If not using classes, add it to the parameters as &$db (byReference).</p>

Title: Retrive data with PHP

Body:
I am having a project using PHP and Postgres. I tried to write a function to get all infomation from one class required from user's input. Below is the version does not work. The commented part is the one that did pretty well but I need to put it into function for reusing target.

function getInfoClass($classID) {

        $query = "SELECT * FROM Class
                  WHERE ID = '{$classID}';";
        $result = pg_query($db, $query);
        return  pg_fetch_assoc($result);
    }

$row = getInfoClass($_SESSION["classID"]);
echo $row['id'];

//$query = "SELECT * FROM Class
//            WHERE ID = '{$_SESSION["classID"]}';";
//$result = pg_query($db, $query);

//while($row = pg_fetch_assoc($result)) {
//  echo $row['id'];
//}


问:
How can I set the filename for base64 pdf in iframe?
I have a report PDF in base64, I want to show the file embedded in the HTML page. To do this I use the iFrame and works, but the problem is that I can't set the name of the PDF so that when downloaded it will be saved with the name assigned.

Can I set the filename?, if yes, how can I do it?

this is my code:

var iFrameBlock = $("").attr({
      "src": base64file_encode,
      "width": "100%",
      "height": "100%",
      "frameborder": "0"
});

$("#previewPDF").html(iFrameBlock);```
</div>
</div>

The result:
Preview of PDF</p>

<p>And when I try download the file, the name to be saved is "download.pdf"
Save dialog</p>

<p>I tried differents ways, but do not work either:</p>

<ol>
<li><p>Adding attribute <strong><em>download="filename.pdf"</em></strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
   var iFrameBlock = $("<iframe>").attr({
      "src": base64file_encode,
      "width": "100%",
      "height": "100%",
      "frameborder": "0",
      "download": "filename.pdf"
   });

   </code>```

I tried to change the value inside the iframe, but I could find the correct attribute and the Chrome denied the action.

   var iframe = $("iframe")[0];
   var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
   //here I suppose is the label of the filename
   $(iframeDocument).find("viewer-pdf-toolbar");

   ```

However, I want prevent use any other library.

Thank you for your time

答:
The iframe element can't do that, but as an alternative you can add anchor tag.

```<code>var iFrameBlock = $("<iframe>").attr({
    "id": "iframe",
    "src": base64file_encode,
    "width": "100%",
    "height": "100%",
    "frameborder": "0"
});
var aTag = $("<a>Dwonload</a>").attr({
    "href": base64file_encode,
    "download": "yourName.pdf"
});
$("#previewPDF").html(iFrameBlock);
aTag.insertAfter($("#iframe"));
</code>```

Body:
I have a report PDF in base64, I want to show the file embedded in the HTML page. To do this I use the iFrame and works, but the problem is that I can't set the name of the PDF so that when downloaded it will be saved with the name assigned.

Can I set the filename?, if yes, how can I do it?

this is my code:

var iFrameBlock = $("").attr({
      "src": base64file_encode,
      "width": "100%",
      "height": "100%",
      "frameborder": "0"
});

$("#previewPDF").html(iFrameBlock);

The result:
Preview of PDF

And when I try download the file, the name to be saved is "download.pdf"
Save dialog

I tried differents ways, but do not work either:

Adding attribute download="filename.pdf"

   var iFrameBlock = $("").attr({
      "src": base64file_encode,
      "width": "100%",
      "height": "100%",
      "frameborder": "0",
      "download": "filename.pdf"
   });

I tried to change the value inside the iframe, but I could find the correct attribute and the Chrome denied the action.

   var iframe = $("iframe")[0];
   var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
   //here I suppose is the label of the filename
   $(iframeDocument).find("viewer-pdf-toolbar");

However, I want prevent use any other library.

Thank you for your time

Body:
The iframe element can't do that, but as an alternative you can add anchor tag.

var iFrameBlock = $("<iframe>").attr({
    "id": "iframe",
    "src": base64file_encode,
    "width": "100%",
    "height": "100%",
    "frameborder": "0"
});
var aTag = $("<a>Dwonload</a>").attr({
    "href": base64file_encode,
    "download": "yourName.pdf"
});
$("#previewPDF").html(iFrameBlock);
aTag.insertAfter($("#iframe"));


问:
How to add/reference .jar files in your project when you don't have an IDE
I am new to Java (basically a LAMP developer). I got this JAVA API to parse .pst files and show all the inbox messages.

I tried executing a given .class file but it throws exceptions. I need to add/reference some .jar files provided by the API.

I don't have any IDE for Java yet. Wikihow says

When your Java project requires JAR
  libraries to function, you have to
  configure your project to include the
  libraries in its build path.
  Fortunately, Eclipse makes this
  process simple and easy to remember.
  The build used here is Eclipse Java -
  Ganymede 3.4.0.

So, what configuration do I have to do? Or is it better to get Eclipse IDE? I just have a single .class file to be executed.

A few other questions that I checked but could not get my answer -
How to add external jar libraries to an android project from the command line

How do I include external JARs in my own Project JAR

答:
```<code>javac -cp yourjar.jar YourClass.java
</code>```

&

```<code>java -cp yourjar.jar YourClass
</code>```

You need to make all required jar available in classpath , this is how you can do it

Body:
javac -cp yourjar.jar YourClass.java

&

java -cp yourjar.jar YourClass

You need to make all required jar available in classpath , this is how you can do it


问:
How safe it is to use third party FRP frameworks for long running project knowing that swift is constantly being changed?
Background:

I need to start working on project which we are hoping to maintain it for long time (Basically reusable components which will be reused in multiple projects). I was exploring the Reactive Programming and the benefits Reactive Programming brings to the table is way to high to ignore it.

I started exploring various FRP frameworks available and RxSwift, ReactiveCocoa were few such examples. But looking at the community support and swift implementation, RxSwift was obviously the choice.

Now RxSwift4 came with some breaking changes as RxSwift3 wasn't compatible with Swift4. Now community did a great job to bridge the changes smooth, though but things like DelegateProxy implemented in RxSwift3 started breaking in RxSwift4. So for those who used RxSwift3 it wasn't just a pod update but involved loads of changes as well. On following the RxSwift Git hub issue realized that its because of Swift4 changes which lead to this break.

Question:

Now its a very common risk that we take on using all third party frameworks, but with most of the frameworks I used, if broke they would have break a feature or two in app but if I write a complete app in RxSwift and future updates break, finding a replaceable library and replacing it would be a enormous job.

Here is why?

For example, if you use Alamofire, usually you will have your own Network layer in app which would expose certain API to app and app quite frankly wont worry about the library used under the hood. So replacing it is quite a easy task. But with RxSwift all asynchronous tools like delegates, blocks,notifications are already wrapped in RxSwift components like Observables,Subjects,Units etc to which we cant write a wrapper of our own and if Current RxSwift version breaks in future update we will be left with no other solution than to literally fix them one by one, as replacing library would mean complete re writing of project.

I know its a kind of opinion based question, but the problem is there is no much guiding opinion on web for the same. I would really appreciate, if somebody who used FRP frameworks in their project post the best practice to use them so that dependency on framework will be minimal and allow us to shift to new FRP framework easily in future.

EDIT:

The mention of Alamofire above is just to show how easy it is to wrap other frameworks that we use in our app only and has nothing to do with RxSwift in itself. So please don't get carried away by that :)

答: My short opinion-based answer is that it is safe enough starting from Swift3 because backwards-compatibility is guaranteed starting from Swift3 onwards. I use RxSwift and a bunch of derived frameworks (RxCoreData, RxCloudKit, RxGesture, RxCoreMotion and RaspSwift) extensively for about a year now, never encountered anything particularly troublesome. But then again, you mentioned some frameworks which I did not use that gave compatibility troubles. So apparently there might be unpleasant surprises, which are usually fixed quick enough by the open-source community.</p>


问:
scrollToIndex doesn't scroll the list in React-virtualized list
With react-virtualized, when you scroll the list and set the same scrollToIndex, it doesn't scroll back to the same index.

Is there a way to reset the list back to the position?

答:
As @brianvaughn also said, you List doesn't scroll to the index back again because to the props to the react-virtualized list component haven't changed.

Since, By default all react-virtualized components use shallowCompare to avoid re-rendering unless props or state has changed. The components won't re-render until an update has happened.

The solution to this is to let react-virtualized know that something external has changed. This can be done a couple of different ways.

Also its mentioned in the documentation that you have two ways to let react-virtualized know that something has changed

Pass-thru props

The shallowCompare method will detect changes to any props, even if they aren't declared as propTypes. This means you can also pass through additional properties that affect cell rendering to ensure changes are detected. So you could pass additional props that change when you fire an event that for the virtualized list doesn't change anything.

```<code><List
  {...listProps}
  sortBy={sortBy}
/>
</code>```

Public methods

Grid and Collection components can be forcefully re-rendered using forceUpdate. For Table and List, you'll need to call forceUpdateGrid to ensure that the inner Grid is also updated.

So whenever you wish to update the scrollToIndex if, its value hasn't changed from the previous value you could call forceUpdateGrid on the List. This method can come in handy in a lot of other situations as well

Having said that, it may not be the best option always as there is another option to force scroll event if the scrollToIndex hasn't changed, which is the scrollToRow  option. However it requires the row you want to scroll to be visible. Its its not, you won't be able to use it.

scrollToRow (index: number)

Ensure row is visible. This method can be used to safely scroll back
  to a cell that a user has scrolled away from even if it was previously
  scrolled to.

Body:
As @brianvaughn also said, you List doesn't scroll to the index back again because to the props to the react-virtualized list component haven't changed.

Since, By default all react-virtualized components use shallowCompare to avoid re-rendering unless props or state has changed. The components won't re-render until an update has happened.

The solution to this is to let react-virtualized know that something external has changed. This can be done a couple of different ways.

Also its mentioned in the documentation that you have two ways to let react-virtualized know that something has changed

Pass-thru props

The shallowCompare method will detect changes to any props, even if they aren't declared as propTypes. This means you can also pass through additional properties that affect cell rendering to ensure changes are detected. So you could pass additional props that change when you fire an event that for the virtualized list doesn't change anything.

<List
  {...listProps}
  sortBy={sortBy}
/>

Public methods

Grid and Collection components can be forcefully re-rendered using forceUpdate. For Table and List, you'll need to call forceUpdateGrid to ensure that the inner Grid is also updated.

So whenever you wish to update the scrollToIndex if, its value hasn't changed from the previous value you could call forceUpdateGrid on the List. This method can come in handy in a lot of other situations as well

Having said that, it may not be the best option always as there is another option to force scroll event if the scrollToIndex hasn't changed, which is the scrollToRow  option. However it requires the row you want to scroll to be visible. Its its not, you won't be able to use it.

scrollToRow (index: number)

Ensure row is visible. This method can be used to safely scroll back
  to a cell that a user has scrolled away from even if it was previously
  scrolled to.