问:
How to get all elements from a list without the last element?
The following Groovy code

```<code>    lines = ['0','1','2','3','4','5']
    println lines[1..lines.size()-1]
    println lines[1..-1]
    println lines[1..<lines.size()-1]
    println lines[1..<-1]
    println lines[1..<-2]
    println lines[1..-2]
</code>```

produces this output:

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

Since -1 is the index of the last element in the list, the first two make sense (ranges in Groovy include the end element instead of omitting it as everywhere else in Java :-( )

Line #3 is the desired output (list without first and last element).

I'm worried about the output #4: Why do I get [1, 0] for 1..-1?

Also [1, 2, 3, 4, 5] for the range 1..<-2 seems wrong.

Why does that happen?

Body:
The following Groovy code

    lines = ['0','1','2','3','4','5']
    println lines[1..lines.size()-1]
    println lines[1..-1]
    println lines[1..<lines.size()-1]
    println lines[1..<-1]
    println lines[1..<-2]
    println lines[1..-2]

produces this output:

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

Since -1 is the index of the last element in the list, the first two make sense (ranges in Groovy include the end element instead of omitting it as everywhere else in Java :-( )

Line #3 is the desired output (list without first and last element).

I'm worried about the output #4: Why do I get [1, 0] for 1..-1?

Also [1, 2, 3, 4, 5] for the range 1..<-2 seems wrong.

Why does that happen?

Body:
Since Groovy 2.4 you can use the init() method:

lines = ['0','1','2','3','4','5']
assert lines.init() == ['0','1','2','3','4']


来源: stackexchange

问:
How can I get a number with a thounds separator on top?

SELECT count(*) FROM table A
```

let's say the result is 8689. How can I convert it to 8'689 on the SQL Server?

答:
Try This way:-

```<code>select replace(convert(varchar,convert(Money,  count(*)),1),'.00','')
from table_name
</code>```

and be sure you really need this approach, formatting the application is the usual and best as SqlZim said.

UPDATE:-

for setting the separator on top, Try the next:-

```<code>select replace( replace(convert(varchar,convert(Money,  count(*)),1),'.00',''),',','''')
from table_name
</code>```

ContentLicense: CC BY-SA 3.0

Body:
SELECT count(*) FROM table A

let's say the result is 8689. How can I convert it to 8'689 on the SQL Server?

Body:
Try This way:-

select replace(convert(varchar,convert(Money,  count(*)),1),'.00','')
from table_name

and be sure you really need this approach, formatting the application is the usual and best as SqlZim said.

UPDATE:-

for setting the separator on top, Try the next:-

select replace( replace(convert(varchar,convert(Money,  count(*)),1),'.00',''),',','''')
from table_name


问:
link to ios app in desktop browser
I've an link to an app in apples appstore. It works well when following this link with an iOS device. But if I follow it with browser on my desktop (PC or Mac), it just leads me to the itunes page and not to the app.

With android apps it works better, I will be lead to the playstore app and can install it then to my android device.

How usually this should be handled for iOS apps?

答: Each download of iOS app includes user's iTunes credentials, so directly, through web browser you can not download the app. Only redirect to iTunes web page or, if iTunes installed on your desktop, it opens the link to the app where you can download it.</p>

Title: link to ios app in desktop browser


问:
document.getElementById('textbox').focus() not working after submit form
I am trying to implement a simple form, and I am trying to set the focus on the first textbox in the form after submit, it's just not working. I could not use the code snippet on this site because I am using localStorage, and it didn't allow me to use it)

Here's my code on Codepen: http://codepen.io/anon/pen/ZemVpz

Here's how my HTML looks like for a quick reference:

document.getElementById('formBookmark').addEventListener('submit', addBookmark);

function addBookmark(e) {
    var siteName = document.getElementById('txtSiteName').value;
    var siteUrl = document.getElementById('txtSiteUrl').value;
    if (!validate(siteName, siteUrl)) {
        alert("Please fill the blank fields");
        return;
    }

    var newBookmark = {
        siteName: siteName,
        siteUrl: siteUrl
    }

    var bookmarks = getlocalBookmarks() || [];

    bookmarks.push(newBookmark);
    localStorage.setItem('tf-bookmarks',JSON.stringify(bookmarks));
    //trying to set focus here
    document.getElementById(formBookmark).reset();
    document.getElementById("txtSiteName").focus();

    fetchBookmarks();
    e.preventDefault();

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<form id="formBookmark">
                <div class="form-group">
                    <label for="txtSiteName">Site Name:</label>
                    <input type="text" name="txtSiteName" id="txtSiteName" class="form-control" placeholder="Google" />
                </div>
                <div class="form-group">
                    <label for="txtSiteUrl">Site Url:</label>
                    <input type="text" name="txtSiteUrl" id="txtSiteUrl" class="form-control" placeholder="http://google.com"/>
                </div>
                <button class="btn btn-success" id="btnAddLink" type="submit">Add Bookmark</button>
            </form></code>```

I can use body onload event to do this, but what if I have more than one form on the page. Why that line of code to set focus through JS isn't workin?

Thank you.

答:
Don't worry, it's just a small typo - you forgot to add quotes around 'formBookmark' here:

```<code>//trying to set focus here
document.getElementById(formBookmark).reset();
document.getElementById("txtSiteName").focus();
</code>```

Don't forget to use 'Developer Tools' console to quickly catch bugs like this.
Just for completeness on Chrome 'Developer Tools' can be found here:

and now console clearly shows how your code crashes on .reset() call just 1 line before you're trying to .focus():

Body:
I am trying to implement a simple form, and I am trying to set the focus on the first textbox in the form after submit, it's just not working. I could not use the code snippet on this site because I am using localStorage, and it didn't allow me to use it)

Here's my code on Codepen: http://codepen.io/anon/pen/ZemVpz

Here's how my HTML looks like for a quick reference:

document.getElementById('formBookmark').addEventListener('submit', addBookmark);

function addBookmark(e) {
    var siteName = document.getElementById('txtSiteName').value;
    var siteUrl = document.getElementById('txtSiteUrl').value;
    if (!validate(siteName, siteUrl)) {
        alert("Please fill the blank fields");
        return;
    }

    var newBookmark = {
        siteName: siteName,
        siteUrl: siteUrl
    }

    var bookmarks = getlocalBookmarks() || [];

    bookmarks.push(newBookmark);
    localStorage.setItem('tf-bookmarks',JSON.stringify(bookmarks));
    //trying to set focus here
    document.getElementById(formBookmark).reset();
    document.getElementById("txtSiteName").focus();

    fetchBookmarks();
    e.preventDefault();

}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<form id="formBookmark">

                    Site Name:
                    <input type="text" name="txtSiteName" id="txtSiteName" class="form-control" placeholder="Google" />

                    Site Url:
                    <input type="text" name="txtSiteUrl" id="txtSiteUrl" class="form-control" placeholder="http://google.com"/>

                <button class="btn btn-success" id="btnAddLink" type="submit">Add Bookmark</button>
            </form>

I can use body onload event to do this, but what if I have more than one form on the page. Why that line of code to set focus through JS isn't workin?

Thank you.

Body:
Don't worry, it's just a small typo - you forgot to add quotes around 'formBookmark' here:

//trying to set focus here
document.getElementById(formBookmark).reset();
document.getElementById("txtSiteName").focus();

Don't forget to use 'Developer Tools' console to quickly catch bugs like this.
Just for completeness on Chrome 'Developer Tools' can be found here:

and now console clearly shows how your code crashes on .reset() call just 1 line before you're trying to .focus():


问:
DotNetOpenAuth WebServerClient.ProcessUserAuthorization() always returns null
I am trying to add implementation of refresh tokens into my API. I'm trying to use WebServerClient.RefreshAuthorization(), but that requires the IAuthorizationState parameter. The only way I can figure out how to get that is through WebServerClient.ProcessUserAuthorization(). The problem is, that method is always returning null, so I can't refresh my token.

```<code>var state = this.WebServerClient.ProcessUserAuthorization();
this.WebServerClient.RefreshAuthorization(state);
</code>```

Is there a different method I can use on my API that the client can call to refresh their access token? Or is there a different way to get the IAuthorizationState of the client? Or anything is sounds like I'm doing wrong?

答:
"Facebook has recently shut down API v2.2, and with v2.3 the return format of the access token has changed"

FacebookApplication.VerifyAuthentication(_httpContext, GenerateLocalCallbackUri()) return null on Facebook

Body:
I am trying to add implementation of refresh tokens into my API. I'm trying to use WebServerClient.RefreshAuthorization(), but that requires the IAuthorizationState parameter. The only way I can figure out how to get that is through WebServerClient.ProcessUserAuthorization(). The problem is, that method is always returning null, so I can't refresh my token.

var state = this.WebServerClient.ProcessUserAuthorization();
this.WebServerClient.RefreshAuthorization(state);

Is there a different method I can use on my API that the client can call to refresh their access token? Or is there a different way to get the IAuthorizationState of the client? Or anything is sounds like I'm doing wrong?


问:
Google not displaying meta description
I've recently hosted my website nepalride.com. I have included meta description in all pages but google is not not showing them. You can see here:
https://www.google.com.np/?gws_rd=cr&ei=U-zcWIKnHIKYvQSChZCwCw#q=nepalride.com&*

I've used my meta description like:

```<code><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Nepal Ride|Tested and Reconditioned Bikes and Cars near you</title>
<meta name="description" content="Browse from over 1000+ genuine and tested Second hand Bikes and Cars from over 100+ recondition houses in Nepal."/>
<meta name="keyword" content="used bikes,used cars,used bike,used cars,second hand bike,second hand bikes,second car,second hand cars,second hand scooter,second hand scooters,used scooters,2nd hand bikes,second hand online,second hand bikes for sale,second hand shop,nepalride"/>
<meta name="viewport" content="width=device-width">.
</code>```

Can anyone tell me what am i doing wrong?

答: For Google to show what's in your meta description, it needs to appear in the page also. Here is a link to a similiar question i once ask:How to add description to SERP</p>

Title: Google not displaying meta description

Body:
I've recently hosted my website nepalride.com. I have included meta description in all pages but google is not not showing them. You can see here:
https://www.google.com.np/?gws_rd=cr&ei=U-zcWIKnHIKYvQSChZCwCw#q=nepalride.com&*

I've used my meta description like:

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Nepal Ride|Tested and Reconditioned Bikes and Cars near you</title>
<meta name="description" content="Browse from over 1000+ genuine and tested Second hand Bikes and Cars from over 100+ recondition houses in Nepal."/>
<meta name="keyword" content="used bikes,used cars,used bike,used cars,second hand bike,second hand bikes,second car,second hand cars,second hand scooter,second hand scooters,used scooters,2nd hand bikes,second hand online,second hand bikes for sale,second hand shop,nepalride"/>
<meta name="viewport" content="width=device-width">.

Can anyone tell me what am i doing wrong?


问:
byte swapping and C++/C
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

```<code>int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}
</code>```

Best,
U.

答:
Whatever the format is it will obviously be consistent across machines (it would be kind of funny if you couldn't open a file on another machine).

Therefore both byte ordering and data type sizes have to defined in the format and when you want to read such format, you need to work with these byte orders and data type sizes.

ContentLicense: CC BY-SA 2.5

Title: byte swapping and C++/C

Body:
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}

Best,
U.


问:
How to serialize an Object into a list of URL query parameters?
Without knowing the keys of a JavaScript Object, how can I turn something like...

```<code>var obj = {
   param1: 'something',
   param2: 'somethingelse',
   param3: 'another'
}

obj[param4] = 'yetanother';
</code>```

...into...

```<code>var str = 'param1=something&param2=somethingelse&param3=another&param4=yetanother';
</code>```

...?

答:
```<code>Object.toparams = function ObjecttoParams(obj)
{
  var p = [];
  for (var key in obj)
  {
    p.push(key + '=' + encodeURIComponent(obj[key]));
  }
  return p.join('&');
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Without knowing the keys of a JavaScript Object, how can I turn something like...

var obj = {
   param1: 'something',
   param2: 'somethingelse',
   param3: 'another'
}

obj[param4] = 'yetanother';

...into...

var str = 'param1=something&param2=somethingelse&param3=another&param4=yetanother';

...?


问:
How to add a right button when specific UIViewController get loaded in Swift 3
I have two different UIStorboards and I am using a UINavigationController to load the pages.

I have a total of three UIViewControllers. Two of them are on the first UIStoryboard and the third one is on the second UIStoryboard.

1) Navigation controller

2) Main Controller

3) Value Screen Controller.

I want to add right button on navigation bar only when value screen controller get loaded. It should not be available on Main view controller.
I tried with this solution but not worked.

答:
Each UIViewController has its own UINavigationItems. So you can just add this right button in your Value Screen Controller by adding this line:

```<code>self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: <#T##UIBarButtonSystemItem#>, target: <#T##Any?#>, action: <#T##Selector?#>)
</code>```

You can place it in func viewDidLoad() if you want it to be place as soon as the UIViewController's view is loaded.

Body:
Each UIViewController has its own UINavigationItems. So you can just add this right button in your Value Screen Controller by adding this line:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: <#T##UIBarButtonSystemItem#>, target: <#T##Any?#>, action: <#T##Selector?#>)

You can place it in func viewDidLoad() if you want it to be place as soon as the UIViewController's view is loaded.


问:
Can I override auto increment ID with Alice Fixtures?
I am using Symfony2 with Doctrine and I'm using the Alice Fixture bundle to generate my fixtures for testing.

In one case I need to create a fixture where the id is 148 for a specific test. All of our ids are configured to auto_increment, so I am currently creating 147 dummy records just to create the one I need.

I was hoping to use this definition to force the id to be set to 148:

```<code> invoiceClassNoClass (extends invoiceClass):
    id: 148
    sortOrder: 1
    label: 'No Class'
</code>```

Unfortunately this does not work. From a google search I read a brief comment stating that I first need to add a setId method to my entity. I tried that but it did not make a difference. In reality I do not want to add as setId method if I do not need to, as it violates our integrity rules where we never allow the setting of an id.

Perhaps there is reflection class that could be used? Perhaps this is built into Alice and I do not know about it?

答:
I also ran into this issue since I wanted some ids to be the same every run since I want to refer them in my debug apps using the UUID strategy.

What I have done:

1) Wrote a command that wraps hautelook:fixtures:load:

```<code>protected function execute(InputInterface $input, OutputInterface $output)
{
    $container     = $this->getContainer();
    $entityManager = $container->get('doctrine.orm.default_entity_manager');

    $metadata = $entityManager->getClassMetaData(App::class);
    $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
    $metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

    $application = new Application($kernel);
    $application->setAutoExit(false);

    $this->loadFixtures($application, $output);
}
</code>```

Do the $metadata-stuff for all classes you want to have custom ids (App::class).

```<code>protected function loadFixtures(Application $application, OutputInterface $output)
{
    $loadFixturesInput = new ArrayInput(array(
        'command' => 'hautelook:fixtures:load',
        '--no-interaction' => 'true',
        '--verbose' => '3'
    ));

    $application->run($loadFixturesInput, $output);
}
</code>```

2) I created a template to generate the id like doctrine would.

```<code>id (template):
    id (unique):   '<uuid()>'
</code>```

3) In my custom entity fixture, now I can do the following:

```<code>app_custom (extends id):
    id:    'whatever-i-want'
    title: 'My custom entity'
</code>```

4) And if I don't want to use a custom id, I just don't overwrite the id field:

```<code>app_another (extends id):
    title: 'Just another app with an id I do not care about'
</code>```

Proof:

Body:
I am using Symfony2 with Doctrine and I'm using the Alice Fixture bundle to generate my fixtures for testing.

In one case I need to create a fixture where the id is 148 for a specific test. All of our ids are configured to auto_increment, so I am currently creating 147 dummy records just to create the one I need.

I was hoping to use this definition to force the id to be set to 148:

 invoiceClassNoClass (extends invoiceClass):
    id: 148
    sortOrder: 1
    label: 'No Class'

Unfortunately this does not work. From a google search I read a brief comment stating that I first need to add a setId method to my entity. I tried that but it did not make a difference. In reality I do not want to add as setId method if I do not need to, as it violates our integrity rules where we never allow the setting of an id.

Perhaps there is reflection class that could be used? Perhaps this is built into Alice and I do not know about it?

Body:
I also ran into this issue since I wanted some ids to be the same every run since I want to refer them in my debug apps using the UUID strategy.

What I have done:

1) Wrote a command that wraps hautelook:fixtures:load:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $container     = $this->getContainer();
    $entityManager = $container->get('doctrine.orm.default_entity_manager');

    $metadata = $entityManager->getClassMetaData(App::class);
    $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
    $metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

    $application = new Application($kernel);
    $application->setAutoExit(false);

    $this->loadFixtures($application, $output);
}

Do the $metadata-stuff for all classes you want to have custom ids (App::class).

protected function loadFixtures(Application $application, OutputInterface $output)
{
    $loadFixturesInput = new ArrayInput(array(
        'command' => 'hautelook:fixtures:load',
        '--no-interaction' => 'true',
        '--verbose' => '3'
    ));

    $application->run($loadFixturesInput, $output);
}

2) I created a template to generate the id like doctrine would.

id (template):
    id (unique):   '<uuid()>'

3) In my custom entity fixture, now I can do the following:

app_custom (extends id):
    id:    'whatever-i-want'
    title: 'My custom entity'

4) And if I don't want to use a custom id, I just don't overwrite the id field:

app_another (extends id):
    title: 'Just another app with an id I do not care about'

Proof:


问:
Getting file resource from Jar in Hadoop
I am trying to run a Hadoop application from a jar:

```<code>hadoop jar myJarFile.jar my.class.path.Here /path/to/input /path/to/output
</code>```

In one of the classes in myJarFile.jar, I am attempting to read a resource from the classpath thus:

```<code>public void init() {
    Configuration conf  = new Configuration();
    conf.addResource("resources/myConf.xml");
    log.info("Data element=" + conf.get("data.element"));
    ....
</code>```

In myJarFile.jar, resource/myConf exists:

```<code>[prompt] jar myJarFile.jar
my/class/path/Here.class
...
resources/myConf.xml
</code>```

and the configuration file contains the name/value pair in the proper (Hadoop-style) format. However, whenever I try to run this, it fails to find the myConf.xml file, even though it should be on the classpath.

What am I missing?

答:
OK - turned out my original code actually works (except for some later bugs...) But my deployment script had accidentally omitted the actual xml file, and I missed it because there was a similarly-named properties file.

Thanks for the advice.

Body:
I am trying to run a Hadoop application from a jar:

hadoop jar myJarFile.jar my.class.path.Here /path/to/input /path/to/output

In one of the classes in myJarFile.jar, I am attempting to read a resource from the classpath thus:

public void init() {
    Configuration conf  = new Configuration();
    conf.addResource("resources/myConf.xml");
    log.info("Data element=" + conf.get("data.element"));
    ....

In myJarFile.jar, resource/myConf exists:

[prompt] jar myJarFile.jar
my/class/path/Here.class
...
resources/myConf.xml

and the configuration file contains the name/value pair in the proper (Hadoop-style) format. However, whenever I try to run this, it fails to find the myConf.xml file, even though it should be on the classpath.

What am I missing?


问:
Observable for mutiple responses in angular 2
So, I have this service which first calls a function from another module which basically returns an list of urls from an external api. This service then must http.get from all the urls in that list (every url returns a json object of same format) then return a single observable which I can then use in an angular component. Here's what my service code looks like:

```<code>    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import { Client } from 'external-api';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';

    let client = new Client();

    @Injectable()
    export class GbDataService {
      constructor(private _http: Http) {

      }

        getGBData(): Observable<any> {
        client.fetchUrls("").then(resp=> {
        resp.forEach(url => {
          //this._http.get(url).map(res => res.json);
          // Create a single observable for every http response

        });
        }).catch(function(err){
            console.log(err.message);
        });
        //return observable
      };
   }
</code>```

http.get returns and Observable<Response> type but I couldn't find a way to create and return one Observable for all http.get responses. How can this be done ? Should I create an observable array then push() all the get response I get to the array?

EDIT: It doesn't really matters to me if responses are emitted one by one or all at once BUT there must be only a single Obeservable which emits the responses of all the http.get requests.

Further Edit: This is my fetchURLs method:

```<code>  fetchURLs(): Promise<any> {
    return new Promise((resolve, reject) => {
      let _repos: Array<any>;
      //scrapeTrendingRepos() is from https://github.com/rhysd/node-github-trend
      scraper.scrapeTrendingRepos("").then(repos => {
        repos.forEach(repo => {
          let url = `https:api.github.com/repos/${repo.owner}/${repo.name}`;
          _repos.push(url);
        });
        resolve(_repos);
      }).catch(err => {
        reject(err);
      });
    })
  };
</code>```

Have I implemented Promises in fetchURLs() right??

答:
if client.fetchUrls("") return a native Promise you may want to use  snorkpete solution.

if not try to create an observable:

```<code>getGBData(): Observable<any> {

   return Observable.create(observer => {
        client.fetchUrls("").then(resp=> {
        resp.forEach(url => {
          this._http.get(url).map(res => res.json).subscribe(data=>{
            observer.next(data);
          });

        });
        }).catch(function(err){
            console.log(err.message);
            observer.error(err);
        });
  });
}
</code>```

Body:
So, I have this service which first calls a function from another module which basically returns an list of urls from an external api. This service then must http.get from all the urls in that list (every url returns a json object of same format) then return a single observable which I can then use in an angular component. Here's what my service code looks like:

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import { Client } from 'external-api';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';

    let client = new Client();

    @Injectable()
    export class GbDataService {
      constructor(private _http: Http) {

      }

        getGBData(): Observable<any> {
        client.fetchUrls("").then(resp=> {
        resp.forEach(url => {
          //this._http.get(url).map(res => res.json);
          // Create a single observable for every http response

        });
        }).catch(function(err){
            console.log(err.message);
        });
        //return observable
      };
   }

http.get returns and Observable<Response> type but I couldn't find a way to create and return one Observable for all http.get responses. How can this be done ? Should I create an observable array then push() all the get response I get to the array?

EDIT: It doesn't really matters to me if responses are emitted one by one or all at once BUT there must be only a single Obeservable which emits the responses of all the http.get requests.

Further Edit: This is my fetchURLs method:

  fetchURLs(): Promise<any> {
    return new Promise((resolve, reject) => {
      let _repos: Array<any>;
      //scrapeTrendingRepos() is from https://github.com/rhysd/node-github-trend
      scraper.scrapeTrendingRepos("").then(repos => {
        repos.forEach(repo => {
          let url = `https:api.github.com/repos/${repo.owner}/${repo.name}`;
          _repos.push(url);
        });
        resolve(_repos);
      }).catch(err => {
        reject(err);
      });
    })
  };

Have I implemented Promises in fetchURLs() right??

Body:
if client.fetchUrls("") return a native Promise you may want to use  snorkpete solution.

if not try to create an observable:

getGBData(): Observable<any> {

   return Observable.create(observer => {
        client.fetchUrls("").then(resp=> {
        resp.forEach(url => {
          this._http.get(url).map(res => res.json).subscribe(data=>{
            observer.next(data);
          });

        });
        }).catch(function(err){
            console.log(err.message);
            observer.error(err);
        });
  });
}


问:
Oracle db query - multiple questions regarding join and returning only latest date
I have 2 tables, Inventory and Transactions
In Inventory i have columns Part_id, Location_Id and Zone_id (all VARCHAR)
In Transactions i have columns Part_id, Code and Date (Part_ID and Code are VARCHAR and Date is TIMESTAMP with local timezone)

I would like to see all Part_id, Location_id and Zone_Id from Inventory table and a column which would return latest date for Code 'Pick' for that Part_Id from transactions table if exists and if not, return a blank for that Part_ID.
Problem is that Tranasactions can match the Part_Id in Inventory with other Codes. So just going for inventory.part_id = transactions.part_id will not work.
And when there is no record for a Part_id with code Pick, how to get that returned...

```<code>Inventory:                       Transactions:

│Part_ID│Location_ID│Zone_ID│    │Part_ID│Code   │Date
│a001   │A          │Z      │    │a001   │Pick   │01/01/2017│
│b002   │B          │X      │    │b002   │Check  │01/02/2017│
│c003   │C          │Y      │    │c003   │Receive│05/02/2017│
│d004   │D          │Q      │    │d004   │Pick   │09/02/2017│
                                 │a001   │Pick   │11/02/2017│

Wanted result:

│Part_ID│Location_ID│Zone_ID│LatestDateofPick│
│a001   │A          │Z      │11/02/2017      │
│b002   │B          │X      │                │
│c003   │C          │Y      │                │
│d004   │D          │Q      │09/02/2017      │
</code>```

I'm just a beginner with SQL so i'm kinda in square one with this, please be merciful. :)
Thanks for helping me out on this one!

答:
You will need something like this to get what you are after

```<code>select t.Part_ID,
    i.Location_ID,
    i.Zone_ID,
    case when t.Code <> 'Pick' then null else max(t.Date) end as LatestDateOfPick
from Transactions t
join Inventory  i on t.Part_ID = i.Part_ID
group by t.Part_ID,i.Location_ID,i.Zone_ID,t.Code
</code>```

This will pull the max date only when the Code it "Pick" otherwise it will leave it NULL

Body:
I have 2 tables, Inventory and Transactions
In Inventory i have columns Part_id, Location_Id and Zone_id (all VARCHAR)
In Transactions i have columns Part_id, Code and Date (Part_ID and Code are VARCHAR and Date is TIMESTAMP with local timezone)

I would like to see all Part_id, Location_id and Zone_Id from Inventory table and a column which would return latest date for Code 'Pick' for that Part_Id from transactions table if exists and if not, return a blank for that Part_ID.
Problem is that Tranasactions can match the Part_Id in Inventory with other Codes. So just going for inventory.part_id = transactions.part_id will not work.
And when there is no record for a Part_id with code Pick, how to get that returned...

Inventory:                       Transactions:

│Part_ID│Location_ID│Zone_ID│    │Part_ID│Code   │Date
│a001   │A          │Z      │    │a001   │Pick   │01/01/2017│
│b002   │B          │X      │    │b002   │Check  │01/02/2017│
│c003   │C          │Y      │    │c003   │Receive│05/02/2017│
│d004   │D          │Q      │    │d004   │Pick   │09/02/2017│
                                 │a001   │Pick   │11/02/2017│

Wanted result:

│Part_ID│Location_ID│Zone_ID│LatestDateofPick│
│a001   │A          │Z      │11/02/2017      │
│b002   │B          │X      │                │
│c003   │C          │Y      │                │
│d004   │D          │Q      │09/02/2017      │

I'm just a beginner with SQL so i'm kinda in square one with this, please be merciful. :)
Thanks for helping me out on this one!

Body:
You will need something like this to get what you are after

select t.Part_ID,
    i.Location_ID,
    i.Zone_ID,
    case when t.Code <> 'Pick' then null else max(t.Date) end as LatestDateOfPick
from Transactions t
join Inventory  i on t.Part_ID = i.Part_ID
group by t.Part_ID,i.Location_ID,i.Zone_ID,t.Code

This will pull the max date only when the Code it "Pick" otherwise it will leave it NULL


问:
Best way to validate string input for a limited number of options
I am trying to validate input in MySQL and would like to restrict the input of string values for an attribute to belong to the set {'type1', 'type2', 'type3', 'type4', 'type5'}. I've already opted to use an ENUM{'type1', 'type2', 'type3', 'type4', 'type5'} datatype. While this seems to prevent insertion of invalid data, it does not provide a descriptive enough error message to the user to reasonably correct the input. The error message is:

Data truncated for column 'type' at row 1

Which doesn't indicate that I'm looking for one of the enum values. What I'm considering adding is a BEFORE INSERT trigger that checks if the string is valid and fields and error if not. However, I'm pretty unfamiliar with SQL syntax and my implementation seems clunky:

```<code>IF (NEW.type <> 'Type1' OR
    NEW.type <> 'Type2' OR
    NEW.type <> 'Type3' OR
    NEW.type <> 'Type4' OR
    NEW.type <> 'Type5')
THEN
    SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = "Please ensure 'type' is one of the following: Type1, Type2, Type3, Type4, or Type5";
END IF;
</code>```

Is there a better way to achieve what I'm looking for (i.e. if input belongs to a 'ListOfTypes' instead of using so many ORs), since this can get very clunky with a larger number of valid types. Is this type of double validation even necessary or prudent? I recognize this would prevent me from using indices as inputs, which is one benefit of the ENUM datatype. I apologize if this question has an obvious answer. Thanks!

答:
Well if you do not want to use ENUMs, what about using NOT IN (...) syntax:

```<code>IF (NEW.type <b>NOT IN</b> ('Type1','Type2','Type3','Type4','Type5'))
THEN
    SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = "Please ensure 'type' is one of the following: Type1, Type2, Type3, Type4, or Type5";
END IF;</code>```

Body:
I am trying to validate input in MySQL and would like to restrict the input of string values for an attribute to belong to the set {'type1', 'type2', 'type3', 'type4', 'type5'}. I've already opted to use an ENUM{'type1', 'type2', 'type3', 'type4', 'type5'} datatype. While this seems to prevent insertion of invalid data, it does not provide a descriptive enough error message to the user to reasonably correct the input. The error message is:

Data truncated for column 'type' at row 1

Which doesn't indicate that I'm looking for one of the enum values. What I'm considering adding is a BEFORE INSERT trigger that checks if the string is valid and fields and error if not. However, I'm pretty unfamiliar with SQL syntax and my implementation seems clunky:

IF (NEW.type <> 'Type1' OR
    NEW.type <> 'Type2' OR
    NEW.type <> 'Type3' OR
    NEW.type <> 'Type4' OR
    NEW.type <> 'Type5')
THEN
    SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = "Please ensure 'type' is one of the following: Type1, Type2, Type3, Type4, or Type5";
END IF;

Is there a better way to achieve what I'm looking for (i.e. if input belongs to a 'ListOfTypes' instead of using so many ORs), since this can get very clunky with a larger number of valid types. Is this type of double validation even necessary or prudent? I recognize this would prevent me from using indices as inputs, which is one benefit of the ENUM datatype. I apologize if this question has an obvious answer. Thanks!

Body:
Well if you do not want to use ENUMs, what about using NOT IN (...) syntax:

IF (NEW.type NOT IN ('Type1','Type2','Type3','Type4','Type5'))
THEN
    SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = "Please ensure 'type' is one of the following: Type1, Type2, Type3, Type4, or Type5";
END IF;


问:
Integrity error when trying to save twice the same object using save_formset
I am out of ideas and I need some help about a problem that I encounter when I try to save the same object. Let me explain.

I have a model, let's call it Pizza. And Topping which has a foreign key to Pizza:

I have implemented an Admin view PizzaAdmin and I have added a tabular inline of Topping

so from PizzaAdmin, I can add several toppings.

I have override the save_formset method where I call a helper to perform a third-party API call.
From the API response, I need to save some data to my toppings.

```<code>def save_formset(self, request, form, formset, change):
    super(PizzaAdmin, self).save_formset(request, form, formset, change)

    helper = ApiHelper(instance=form.instance)
    helper.sync()
</code>```

This helper makes a call to an API, parse the response and associate an ID for each toppings of Pizza.

```<code>class ApiHelper(...):
    def sync(self):
        # parse response

        for topping in self.instance.toppings.all():
            if ....:
                topping.some_id = ...
                topping.save()
</code>```

When I reach the topping.save(), I got this error: IntegrityError

I do not want to create a new Topping but update its property some_id.

After futher investigation, I realised that save_formset is called by save_related which is called by changeform_view which as the decorator @transaction.atomic

Is there a way to force the commit inside an atomic transaction ?

Please advise. Thanks a lot.

*** UPDATE: 2017-03-30 ***

I have found transaction.on_commit() which allows me to perform actions after the commit:

```<code>class PizzaAdmin(admin.ModelAdmin)
    def save_formset(self, request, form, formset, change):
        super(PizzaAdmin, self).save_formset(request, form, formset, change)
        transaction.on_commit(lambda: sync_toppings(instance=form.instance))

def sync_toppings(instance):
    helper = ApiHelper(instance=form.instance)
    helper.sync()
</code>```

Inside sync() method, I have replace my queryset using this logic:

```<code>toppings_qs = Topping.objects.filter(pizza=self.instance)
</code>```

I still have an IntegrityError when I try to update the topping through the queryset.

I do not understand why. Please help.

答:
I have found my mistake!!!
This is what I did:

```<code>def save(self, **kwargs):
    self.is_negative = True
    super(Topping, self).save(self, **kwargs)
</code>```

Notice the self in save of the super() :(

My fix:

```<code>def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    self.is_negative = True
    super(Topping, self).save(force_insert, force_update, using, update_fields)
</code>```

Body:
I am out of ideas and I need some help about a problem that I encounter when I try to save the same object. Let me explain.

I have a model, let's call it Pizza. And Topping which has a foreign key to Pizza:

I have implemented an Admin view PizzaAdmin and I have added a tabular inline of Topping

so from PizzaAdmin, I can add several toppings.

I have override the save_formset method where I call a helper to perform a third-party API call.
From the API response, I need to save some data to my toppings.

def save_formset(self, request, form, formset, change):
    super(PizzaAdmin, self).save_formset(request, form, formset, change)

    helper = ApiHelper(instance=form.instance)
    helper.sync()

This helper makes a call to an API, parse the response and associate an ID for each toppings of Pizza.

class ApiHelper(...):
    def sync(self):
        # parse response

        for topping in self.instance.toppings.all():
            if ....:
                topping.some_id = ...
                topping.save()

When I reach the topping.save(), I got this error: IntegrityError

I do not want to create a new Topping but update its property some_id.

After futher investigation, I realised that save_formset is called by save_related which is called by changeform_view which as the decorator @transaction.atomic

Is there a way to force the commit inside an atomic transaction ?

Please advise. Thanks a lot.

*** UPDATE: 2017-03-30 ***

I have found transaction.on_commit() which allows me to perform actions after the commit:

class PizzaAdmin(admin.ModelAdmin)
    def save_formset(self, request, form, formset, change):
        super(PizzaAdmin, self).save_formset(request, form, formset, change)
        transaction.on_commit(lambda: sync_toppings(instance=form.instance))

def sync_toppings(instance):
    helper = ApiHelper(instance=form.instance)
    helper.sync()

Inside sync() method, I have replace my queryset using this logic:

toppings_qs = Topping.objects.filter(pizza=self.instance)

I still have an IntegrityError when I try to update the topping through the queryset.

I do not understand why. Please help.

Body:
I have found my mistake!!!
This is what I did:

def save(self, **kwargs):
    self.is_negative = True
    super(Topping, self).save(self, **kwargs)

Notice the self in save of the super() :(

My fix:

def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    self.is_negative = True
    super(Topping, self).save(force_insert, force_update, using, update_fields)


问:
Stargazer producing various latex errors
I am using stargazer to output regression results from r to latex. When I run the output in latex I see the results, but get many Package array errors. Here is my code. In R I use stargazer as follows:

```<code>stargazer(fe1, fe2, fe3,
               title="Between regression",
               align=TRUE,
               df = FALSE,
               dep.var.labels=c('depLabel'),
               covariate.labels = c('1st', '2nd', '3rd', '4th') )
</code>```

This produces many errors in latexthat look like:

```<code>Package array Error: Illegal pream-token (D): `c' used. ...5pt}}lD{.}{.}{-3} D{.}{.}{-3} D{.}{.}{-3} }
Package array Error: Illegal pream-token (.): `c' used. ...5pt}}lD{.}{.}{-3} D{.}{.}{-3} D{.}{.}{-3} }
Package array Error: Illegal pream-token (-3): `c' used. ...5pt}}lD{.}{.}{-3} D{.}{.}{-3} D{.}{.}{-3} }
</code>```

and also many Missing $ inserted errors. Is there perhaps any package I need to add to my latex preamble? Or any other common workaround?

Edit  Here are the last lines of the dput of fe1:

```<code>"31495", "31496", "31497", "31498", "31499", "31500"), class = c("pindex",
"data.frame"))), assign = c(0L, 1L, 1L), args = structure(list(
    model = "within", effect = "time", random.method = "swar",
    random.dfcor = NULL, inst.method = "bvk"), .Names = c("model",
"effect", "random.method", "random.dfcor", "inst.method")), aliased = structure(c(FALSE,
FALSE), .Names = c("X1Dq", "X1DT")), call = plm(formula = Y1 ~
    X1, data = pdata1, effect = "time", model = "within")), .Names = c("coefficients",
"vcov", "residuals", "df.residual", "formula", "model", "assign",
"args", "aliased", "call"), class = c("plm", "panelmodel"))
</code>```

答: I found the way to solve it by digging in the documentation: make sure to add \usepackage{dcolumn} in the latex preamble. Then I don't get any errors when compiling in latex.

Body:
I am using stargazer to output regression results from r to latex. When I run the output in latex I see the results, but get many Package array errors. Here is my code. In R I use stargazer as follows:

stargazer(fe1, fe2, fe3,
               title="Between regression",
               align=TRUE,
               df = FALSE,
               dep.var.labels=c('depLabel'),
               covariate.labels = c('1st', '2nd', '3rd', '4th') )

This produces many errors in latexthat look like:

Package array Error: Illegal pream-token (D): `c' used. ...5pt}}lD{.}{.}{-3} D{.}{.}{-3} D{.}{.}{-3} }
Package array Error: Illegal pream-token (.): `c' used. ...5pt}}lD{.}{.}{-3} D{.}{.}{-3} D{.}{.}{-3} }
Package array Error: Illegal pream-token (-3): `c' used. ...5pt}}lD{.}{.}{-3} D{.}{.}{-3} D{.}{.}{-3} }

and also many Missing $ inserted errors. Is there perhaps any package I need to add to my latex preamble? Or any other common workaround?

Edit  Here are the last lines of the dput of fe1:

"31495", "31496", "31497", "31498", "31499", "31500"), class = c("pindex",
"data.frame"))), assign = c(0L, 1L, 1L), args = structure(list(
    model = "within", effect = "time", random.method = "swar",
    random.dfcor = NULL, inst.method = "bvk"), .Names = c("model",
"effect", "random.method", "random.dfcor", "inst.method")), aliased = structure(c(FALSE,
FALSE), .Names = c("X1Dq", "X1DT")), call = plm(formula = Y1 ~
    X1, data = pdata1, effect = "time", model = "within")), .Names = c("coefficients",
"vcov", "residuals", "df.residual", "formula", "model", "assign",
"args", "aliased", "call"), class = c("plm", "panelmodel"))


问:
how to prepare transactional dataset for association rule mining in RapidMiner?
I have a dataset like this:

```<code>abelia,fl,nc
esculentus,ct,dc,fl,il,ky,la,md,mi,ms,nc,sc,va,pr,vi
abelmoschus moschatus,hi,pr*
</code>```

dataset link:

My dataset haven't any attribute declaration. I want apply association rules on my dataset. I want to be like this dataset.

```<code>plant   fl  nc  ct  dc  .....
abelia  1   1   0   0
.....
</code>```

答:
ELKI contains a parser that can read the input as is. Maybe Rapidminer does so, too - or you should write a parser for this format! With the ELKI parameters

```<code>-dbc.in /tmp/plants.data
-dbc.parser SimpleTransactionParser -parser.colsep ,
-algorithm itemsetmining.associationrules.AssociationRuleGeneration
-itemsetmining.minsupp 0.10
-associationrules.interestingness Lift
-associationrules.minmeasure 7.0
-resulthandler ResultWriter -out /tmp/rules
</code>```

we can find all association rules with support >= 10%, Lift >= 7.0, and write them to the folder /tmp/rules (there is currently no visualization of association rules in ELKI):

For example, this finds the rules

```<code>sc, va, ga: 3882 --> nc, al: 3529 : 7.065536626573297
va, nj: 4036 --> md, pa: 3528 : 7.206260507764794
</code>```

So plants that occur in South Carolina, Virigina, and Georgia will also occur in North Carolina and Alabama. NC is not much of a surprise, given that it is inbetween of SC and VA, but Alabama is interesting.

The second rule is Virigina and New Jersey imply Maryland (inbetween the two) and Pennsylvania. Also a very plausible rule, supported by 3528 cases.

Body:
I have a dataset like this:

abelia,fl,nc
esculentus,ct,dc,fl,il,ky,la,md,mi,ms,nc,sc,va,pr,vi
abelmoschus moschatus,hi,pr*

dataset link:

My dataset haven't any attribute declaration. I want apply association rules on my dataset. I want to be like this dataset.

plant   fl  nc  ct  dc  .....
abelia  1   1   0   0
.....

Body:
ELKI contains a parser that can read the input as is. Maybe Rapidminer does so, too - or you should write a parser for this format! With the ELKI parameters

-dbc.in /tmp/plants.data
-dbc.parser SimpleTransactionParser -parser.colsep ,
-algorithm itemsetmining.associationrules.AssociationRuleGeneration
-itemsetmining.minsupp 0.10
-associationrules.interestingness Lift
-associationrules.minmeasure 7.0
-resulthandler ResultWriter -out /tmp/rules

we can find all association rules with support >= 10%, Lift >= 7.0, and write them to the folder /tmp/rules (there is currently no visualization of association rules in ELKI):

For example, this finds the rules

sc, va, ga: 3882 --> nc, al: 3529 : 7.065536626573297
va, nj: 4036 --> md, pa: 3528 : 7.206260507764794

So plants that occur in South Carolina, Virigina, and Georgia will also occur in North Carolina and Alabama. NC is not much of a surprise, given that it is inbetween of SC and VA, but Alabama is interesting.

The second rule is Virigina and New Jersey imply Maryland (inbetween the two) and Pennsylvania. Also a very plausible rule, supported by 3528 cases.


问:
box resizes when zoom
I'm having some troubles with box i created.
I don't know how to prevent box from resizing when i zoom in or out.
This is really bothering me since this makes my avatar not fit in.

Picture:

code:

```<code><div class="header-profile">
    <div class="container">
        <div class="profile-picture-position">
            <img src="/blog/uploads/',$_SESSION['avatar'],'" class="img-thumbnail" alt="Cinque Terre" width="160" height="160"/>
        </div>
    </div>
</div>

.header-profile
{
    display: block;
    position: absolute;
    height: 22%;
    width: 100%;
    box-shadow: inset 0 0 1px 1px rgba(0,0,0,0.2);
    background-color: #1DA1F2 !important
}
</code>```

container is bootstrap

答:
Actually, your box is staying at the same size. It's the header div that gets resized because it covers %22 of the height even if you zoom in or out. You can

1) make box size relative too.

2) make header div size absolute

to fix their proportion when the page is zoomed in or out.

Title: box resizes when zoom

Body:
I'm having some troubles with box i created.
I don't know how to prevent box from resizing when i zoom in or out.
This is really bothering me since this makes my avatar not fit in.

Picture:

code:

.header-profile
{
    display: block;
    position: absolute;
    height: 22%;
    width: 100%;
    box-shadow: inset 0 0 1px 1px rgba(0,0,0,0.2);
    background-color: #1DA1F2 !important
}

container is bootstrap


问:
Fill div with image without stretching
I have an image with high resolution (width: 5540px, height: 2680px), and I need
this image to cover an entire div (this div goes full width and 80% of height). This image is displayed on screens with resolutions of 768px till 1600px.

When I use background-size: cover, the image goes full width but the bottom part is cut off.

When I use background-size: contain, the image is resized to fit the height but the width isn't entirely filled.

When I user background-size: 100%, the image fill the entire div, but gets stretch out.

Is there any way to do that or do I need to resize the image (for example, resize image to 1600px (width) because this image is only displayed on screens with width from 768px to 1600px)?

答:
Since the image is wider than it is high, set the height to 100% and the width to auto:

```<code>background-size: auto 100%;
</code>```

Basic example:

body,
html {
  margin: 0;
}

div {
  height: 100vh;
  width: 100vw;
  background: url('http://lorempizza.com/1000/600') scroll no-repeat center;

  /* Set it to be 100% height, with an auto width */
  background-size: auto 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

If it was the other way around, with the height being larger that the width, you'd just switch them:

```<code>background-size: 100% auto;
</code>```

Title: Fill div with image without stretching

Body:
Since the image is wider than it is high, set the height to 100% and the width to auto:

background-size: auto 100%;

Basic example:

body,
html {
  margin: 0;
}

div {
  height: 100vh;
  width: 100vw;
  background: url('http://lorempizza.com/1000/600') scroll no-repeat center;

  /* Set it to be 100% height, with an auto width */
  background-size: auto 100%;
}

<div></div>

If it was the other way around, with the height being larger that the width, you'd just switch them:

background-size: 100% auto;


问:
Subject vs BehaviorSubject vs ReplaySubject in Angular
I've been looking to understand those 3:

Subject

BehaviorSubject

ReplaySubject

I would like to use them and know when and why, what are the benefits of using them and although I've read the documentation, watched tutorials and searched google I've failed to make any sense of this.

So what are their purpose? A real-world case would be most appreciated it does not have to even code.

I would prefer a clean explanation not just "a+b => c you are subscribed to ...."

Thank you

答:
It really comes down to behavior and semantics. With a

Subject - a subscriber will only get published values that were emitted after the subscription. Ask yourself, is that what you want? Does the subscriber need to know anything about previous values? If not, then you can use this, otherwise choose one of the others. For example, with component-to-component communication. Say you have a component that publishes events for other components on a button click. You can use a service with a subject to communicate.

BehaviorSubject - the last value is cached. A subscriber will get the latest value upon initial subscription. The semantics for this subject is to represent a value that changes over time. For example a logged in user. The initial user might be an anonymous user. But once a user logs in, then the new value is the authenticated user state.

The BehaviorSubject is initialized with an initial value. This is sometimes important to coding preference. Say for instance you initialize it with a null. Then in your subscription, you need to do a null check. Maybe OK, or maybe annoying.

ReplaySubject - it can cache up to a specified number of emissions. Any subscribers will get all the cached values upon subscription. When would you need this behavior? Honestly, I have not had any need for such behavior, except for the following case:

If you initialize a ReplaySubject with a buffer size of 1, then it actually behaves just like a BehaviorSubject. The last value is always cached, so it acts like a value changing over time. With this, there is no need for a null check like in the case of the BehaviorSubject initialized with a null. In this instance, no value is ever emitted to the subscriber until the first publishing.

So it really comes down to the behavior you are expecting (as for which one to use). Most of the time you will probably want to use a BehaviorSubject because what you really want to represent is that "value over time" semantic. But I personally don't see anything wrong with the substitution of ReplaySubject initialized with 1.

What you want to avoid is using the vanilla Subject when what you really need is some caching behavior. Take for example you are writing a routing guard or a resolve. You fetch some data in that guard and set it in a service Subject. Then in the routed component you subscribe to the service subject to try to get that value that was emitted in the guard. OOPs. Where's the value? It was already emitted, DUH. Use a "caching" subject!

See also:

What are RxJS Subject's and the benefits of using them?


问:
Oracle table of Objects in memory
I've got the following type:

```<code> create or replace type autocontrole2.DifferentStatesSAC as object (
  AUTOCONTROLE_STATUS_CODE_ID NUMBER(2),
  DATUM_BEGIN DATE,
  DATUM_EIND DATE)
</code>```

With the following SQL, the error is "ORA 06531 - reference to uninitialized collection"

```<code>declare
    type TableDifferentStatesSAC is table of autocontrole2.DifferentStatesSAC;
    StatutenSAC TableDifferentStatesSAC;
begin
    StatutenSAC(1).AUTOCONTROLE_STATUS_CODE_ID := 6;
    StatutenSAC(1).DATUM_BEGIN := sysdate;
    StatutenSAC(1).DATUM_EIND := sysdate;
end;
</code>```

With the following SQL, the error is "wrong number of types or arguments in call to DifferentStatesSAC()":

```<code>declare
    type TableDifferentStatesSAC is table of autocontrole2.DifferentStatesSAC;
    StatutenSAC TableDifferentStatesSAC := autocontrole2.DifferentStatesSAC;
begin
    StatutenSAC(1).AUTOCONTROLE_STATUS_CODE_ID := 6;
    StatutenSAC(1).DATUM_BEGIN := sysdate;
    StatutenSAC(1).DATUM_EIND := sysdate;
end;
</code>```

I want to create a 'table' in memory that contains an object with 3 values.

any ideas how I can add objects to this table?

答:
You need to initialize the nested table:

```<code>SQL> DECLARE
  2     TYPE TableDifferentStatesSAC IS TABLE OF DifferentStatesSAC;
  3     StatutenSAC TableDifferentStatesSAC;
  4  BEGIN
  5     /* calling the constructor */
  6     StatutenSAC := TableDifferentStatesSAC();
  7     /* adding room for elements */
  8     StatutenSAC.extend();
  9     /* filling first element */
 10     StatutenSAC(1) := DifferentStatesSAC(6, SYSDATE, SYSDATE);
 11  END;
 12  /

PL/SQL procedure successfully completed
</code>```

You can also fill the table with a single command:

```<code>SQL> DECLARE
  2     TYPE TableDifferentStatesSAC IS TABLE OF DifferentStatesSAC;
  3     StatutenSAC TableDifferentStatesSAC;
  4  BEGIN
  5     /* calling the constructor */
  6     StatutenSAC := TableDifferentStatesSAC(
  7                       DifferentStatesSAC(6, SYSDATE, SYSDATE)
  8                    );
  9  END;
 10  /

PL/SQL procedure successfully completed
</code>```

Find out more in the online documentation.

Title: Oracle table of Objects in memory

Body:
I've got the following type:

 create or replace type autocontrole2.DifferentStatesSAC as object (
  AUTOCONTROLE_STATUS_CODE_ID NUMBER(2),
  DATUM_BEGIN DATE,
  DATUM_EIND DATE)

With the following SQL, the error is "ORA 06531 - reference to uninitialized collection"

declare
    type TableDifferentStatesSAC is table of autocontrole2.DifferentStatesSAC;
    StatutenSAC TableDifferentStatesSAC;
begin
    StatutenSAC(1).AUTOCONTROLE_STATUS_CODE_ID := 6;
    StatutenSAC(1).DATUM_BEGIN := sysdate;
    StatutenSAC(1).DATUM_EIND := sysdate;
end;

With the following SQL, the error is "wrong number of types or arguments in call to DifferentStatesSAC()":

declare
    type TableDifferentStatesSAC is table of autocontrole2.DifferentStatesSAC;
    StatutenSAC TableDifferentStatesSAC := autocontrole2.DifferentStatesSAC;
begin
    StatutenSAC(1).AUTOCONTROLE_STATUS_CODE_ID := 6;
    StatutenSAC(1).DATUM_BEGIN := sysdate;
    StatutenSAC(1).DATUM_EIND := sysdate;
end;

I want to create a 'table' in memory that contains an object with 3 values.

any ideas how I can add objects to this table?

Body:
You need to initialize the nested table:

SQL> DECLARE
  2     TYPE TableDifferentStatesSAC IS TABLE OF DifferentStatesSAC;
  3     StatutenSAC TableDifferentStatesSAC;
  4  BEGIN
  5     /* calling the constructor */
  6     StatutenSAC := TableDifferentStatesSAC();
  7     /* adding room for elements */
  8     StatutenSAC.extend();
  9     /* filling first element */
 10     StatutenSAC(1) := DifferentStatesSAC(6, SYSDATE, SYSDATE);
 11  END;
 12  /

PL/SQL procedure successfully completed

You can also fill the table with a single command:

SQL> DECLARE
  2     TYPE TableDifferentStatesSAC IS TABLE OF DifferentStatesSAC;
  3     StatutenSAC TableDifferentStatesSAC;
  4  BEGIN
  5     /* calling the constructor */
  6     StatutenSAC := TableDifferentStatesSAC(
  7                       DifferentStatesSAC(6, SYSDATE, SYSDATE)
  8                    );
  9  END;
 10  /

PL/SQL procedure successfully completed

Find out more in the online documentation.


问:
How to write a fibonacci codes in objective c?
I want to display fibonacci numbers from a given number. For example the input number is 100, then display all fibonacci sequence of numbers.</p>

答:
You can use this method to display fibonacci series from a given number.   </p>

```<code> - (void) displayFibonacciNumbers:(int) n {
        NSMutableArray *fibSeries = [NSMutableArray new];
        int total = 0;
        int prev = 1;
        for (int x=1; x<n; x++){
            total = total + prev;
            prev = total - prev;
            [fibSeries addObject:[NSNumber numberWithInt:total]];
        }
        NSLog(@"Fibonacci numbers are: %@", fibSeries);
    }
</code>```

Body:
You can use this method to display fibonacci series from a given number.

 - (void) displayFibonacciNumbers:(int) n {
        NSMutableArray *fibSeries = [NSMutableArray new];
        int total = 0;
        int prev = 1;
        for (int x=1; x<n; x++){
            total = total + prev;
            prev = total - prev;
            [fibSeries addObject:[NSNumber numberWithInt:total]];
        }
        NSLog(@"Fibonacci numbers are: %@", fibSeries);
    }


问:
Regex How to match word across different paragraphs
Its been driving me crazy because I think this should be a simple problem :(

Here is the situation, I would like to create a regex that would extract the text right below "This is a sentence". In this case, its "3.43" and "3.42" For example:

```<code>This is a sentence 1023 hello:
3.43

This is a sentence 245 byebye:

3.42
</code>```

I wrote the regex:

```<code>y = re.compile(r'This is a sentence.*\n(.*)|\n(.*)').search(mytext).groups()
</code>```

However this gives me the output "None" for both cases in pycharm. The weird thing is, regex101 shows that it is able to capture the text in both cases. See link below.

https://regex101.com/r/mYDALr/2/

Any idea why the output in Pycharm is "None?"

To add on, is there a way to print just "3.42" or "3.43" depending on the case? I am not sure how to do that so I just decided to use .groups(). I am aware that we can print .group(1) or .group(2) but in my case, I would not know whether the first case or the second case will happen so I would not know which to print.

Any help will be greatly appreciated!

Edited:
Ive used the solutions provided but now the problem is, i would like to search for the regex string in different documents but the extracted text from for example file A and file B are of different encoding? see example below. So the regex works for file A but does not work for file B. When i print a line in file B it outputs the weird string when u print(copied_line).

答:
```<code>>>> test = """This is a sentence 1023 hello:
... 3.43
...
... This is a sentence 245 byebye:
...
... 3.42"""
>>> import re
>>> re.findall(r'(?:This is a sentence.*)\n+(.*)', test)
['3.43', '3.42']
>>> re.findall(r'(?:This is a sentence.*)\s+(.*)', test)
['3.43', '3.42']
</code>```

I'd recommend the \s over \n for cross-platform line endings support.

Body:
Its been driving me crazy because I think this should be a simple problem :(

Here is the situation, I would like to create a regex that would extract the text right below "This is a sentence". In this case, its "3.43" and "3.42" For example:

This is a sentence 1023 hello:
3.43

This is a sentence 245 byebye:

3.42

I wrote the regex:

y = re.compile(r'This is a sentence.*\n(.*)|\n(.*)').search(mytext).groups()

However this gives me the output "None" for both cases in pycharm. The weird thing is, regex101 shows that it is able to capture the text in both cases. See link below.

https://regex101.com/r/mYDALr/2/

Any idea why the output in Pycharm is "None?"

To add on, is there a way to print just "3.42" or "3.43" depending on the case? I am not sure how to do that so I just decided to use .groups(). I am aware that we can print .group(1) or .group(2) but in my case, I would not know whether the first case or the second case will happen so I would not know which to print.

Any help will be greatly appreciated!

Edited:
Ive used the solutions provided but now the problem is, i would like to search for the regex string in different documents but the extracted text from for example file A and file B are of different encoding? see example below. So the regex works for file A but does not work for file B. When i print a line in file B it outputs the weird string when u print(copied_line).

Body:
>>> test = """This is a sentence 1023 hello:
... 3.43
...
... This is a sentence 245 byebye:
...
... 3.42"""
>>> import re
>>> re.findall(r'(?:This is a sentence.*)\n+(.*)', test)
['3.43', '3.42']
>>> re.findall(r'(?:This is a sentence.*)\s+(.*)', test)
['3.43', '3.42']

I'd recommend the \s over \n for cross-platform line endings support.


问:
Can I add a wrapper to my layout that has a pure CSS dynamic sticky footer?
After countless hours trying to find a way to implement a sticky footer with fluid height without resorting to using javascript, I finally found a way. No matter how much content I add to the .footer, it remains stuck to the bottom of the viewport, regardless of whether there is enough in the .content div to push it down. None of the javascript solutions I tried worked as smoothly as this, and I'd like to keep using this method if possible.

My problem is that due to an issue with various mobile browsers not accepting the overflow-x:hidden; rule on the body tag, I'm now having to add a wrapper to my layout. This fixes the mobile browser issue, but unfortunately stops the .footer from sticking to the bottom of the viewport when the .content div is empty.

I have of course tried to move several of the CSS rules from the body to the wrapper to see if this works, but I haven't had any success. Is there a way around this?

Here are two jsFiddle examples to show the problem, one with a .wrapper and one without.

Example 1: Without wrapper (Sticky footer works) – https://jsfiddle.net/v5h2f5wd/

Example 2: With wrapper (Sticky footer does not work) – https://jsfiddle.net/v5h2f5wd/1/

Code from Example 2:

```<code><div class="wrapper">
    <header class="header"></header>
        <div class="content">
            <button>Click here to insert content into footer.</button>
        </div>
    <footer class="footer"></footer>
</div>

html {
    position:relative;
    height:100%;
}

body {
    position:relative;
    width:100%;
    min-height:100%;
    margin:0;
    padding:0;
    overflow-x:hidden;
    background-color:#eee;
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
}

.header {
    position:absolute;
    width:100%;
    height:55px;
    background-color:#fff;
}

.content {
    -webkit-box-flex:1;
    -webkit-flex:1;
    -ms-flex:1;
    flex:1;
    width:100%;
    height:auto;
    background-color:pink;
}

button {
    margin:65px 0 0 10px;
}

.footer {
    width:100%;
    background-color:#fff;
    padding:25px 0;
}
</code>```

答:
This is pretty simple with flexbox. No need for positioning at all.

* {
  margin: 0;
  padding: 0;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

.wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
}

header {
  background: pink;
}

footer {
  background: red;
  padding: 1em;
}

main {
  flex: 1;
  background: lightgreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <header>HEADER</header>
  <main>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique facere consequatur officiis cupiditate sed blanditiis magni sequi ducimus cum illum repellat ab nostrum excepturi aperiam dolor repudiandae mollitia, eius deleniti.</p>
  </main>
  <footer>FOOTER</footer>
  </div</code>```

Body:
After countless hours trying to find a way to implement a sticky footer with fluid height without resorting to using javascript, I finally found a way. No matter how much content I add to the .footer, it remains stuck to the bottom of the viewport, regardless of whether there is enough in the .content div to push it down. None of the javascript solutions I tried worked as smoothly as this, and I'd like to keep using this method if possible.

My problem is that due to an issue with various mobile browsers not accepting the overflow-x:hidden; rule on the body tag, I'm now having to add a wrapper to my layout. This fixes the mobile browser issue, but unfortunately stops the .footer from sticking to the bottom of the viewport when the .content div is empty.

I have of course tried to move several of the CSS rules from the body to the wrapper to see if this works, but I haven't had any success. Is there a way around this?

Here are two jsFiddle examples to show the problem, one with a .wrapper and one without.

Example 1: Without wrapper (Sticky footer works) – https://jsfiddle.net/v5h2f5wd/

Example 2: With wrapper (Sticky footer does not work) – https://jsfiddle.net/v5h2f5wd/1/

Code from Example 2:

            <button>Click here to insert content into footer.</button>

html {
    position:relative;
    height:100%;
}

body {
    position:relative;
    width:100%;
    min-height:100%;
    margin:0;
    padding:0;
    overflow-x:hidden;
    background-color:#eee;
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
}

.header {
    position:absolute;
    width:100%;
    height:55px;
    background-color:#fff;
}

.content {
    -webkit-box-flex:1;
    -webkit-flex:1;
    -ms-flex:1;
    flex:1;
    width:100%;
    height:auto;
    background-color:pink;
}

button {
    margin:65px 0 0 10px;
}

.footer {
    width:100%;
    background-color:#fff;
    padding:25px 0;
}

Body:
This is pretty simple with flexbox. No need for positioning at all.

* {
  margin: 0;
  padding: 0;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

.wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
}

header {
  background: pink;
}

footer {
  background: red;
  padding: 1em;
}

main {
  flex: 1;
  background: lightgreen;
}

<div class="wrapper">
  <header>HEADER</header>
  <main>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Similique facere consequatur officiis cupiditate sed blanditiis magni sequi ducimus cum illum repellat ab nostrum excepturi aperiam dolor repudiandae mollitia, eius deleniti.</p>
  </main>
  <footer>FOOTER</footer>
  </div


问:
Div background-color change upon drop-down
I knew javaScript but I'm not used to it as I'm more focus on creating UI design. So decided to take up some short courses and then I've encountered this problem. There should be dropdown which consist of 4 items to choose: red, blue, green, yellow. If a user choose a color let's say yellow, the div box underneath will become yellow. I used Bootstrap for this by the way.

My code goes something like this ` Dropdown 1

```<code><ul class="dropdown-menu">
    <li id="red"><a href="#">Red</a>
    </li>
    <li><a href="#">Blue</a>
    </li>
    <li><a href="#">Green</a>
    </li>
    <li><a href="#">Yellow</a>
    </li>
</ul>
</code>```

`
Full code resides here
http://jsfiddle.net/0c4dbr9t/7/

答:
Using simple javascript:

 Dropdown 1

Red

Blue

Green

Yellow

 Some Text

```

Body:
I knew javaScript but I'm not used to it as I'm more focus on creating UI design. So decided to take up some short courses and then I've encountered this problem. There should be dropdown which consist of 4 items to choose: red, blue, green, yellow. If a user choose a color let's say yellow, the div box underneath will become yellow. I used Bootstrap for this by the way.

My code goes something like this ` Dropdown 1

Red

Blue

Green

Yellow

`
Full code resides here
http://jsfiddle.net/0c4dbr9t/7/

Body:
Using simple javascript:

<div class="btn-group"> <a class="btn " href="#">Dropdown 1</a>
 <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>

    <ul class="dropdown-menu">
        <li id="red"><a href="#">Red</a>
        </li>
        <li><a href="#">Blue</a>
        </li>
        <li><a href="#">Green</a>
        </li>
        <li><a href="#">Yellow</a>
        </li>
    </ul>
</div>

<div id ="box"> Some Text <div>
<script>
var menu = document.querySelector("ul.dropdown-menu");
menu.onclick = function(evt) {
  console.log(evt.target.innerText)
 document.getElementById("box").style.backgroundColor = evt.target.innerText;
}
</script>


问:
Adding onClick function to items in ActionBar (Android)
I have created a dropdown list in my android action bar with 2 items inside it. I want to be able to add onClick functions to these 2 items so that I can make them open another activity. Below is the xml code where I set up one of the items in the dropdown list:

```<code> <item
    android:id="@+id/action_home"
    android:title="@string/home"
    app:showAsAction="never" />
</code>```

I then have the ActionBar.java class:

```<code>public class ActionBar extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_home:
            Intent i = new Intent(ActionBar.this, MainActivity.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);

    }
}
}
</code>```

Whenever I click this 'action_home' item in my actionbar nothing happens, but I need it to open my homepage (MainActivity).

I also have the following code in all of my activities java classes in order to make the actionbar appear:

```<code>@Override
public boolean onCreateOptionsMenu (Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}
</code>```

Any help would be greatly appreciated!

答:
Try This.

```<code>   @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}
</code>```

Click handle here.

```<code>    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.new_game:
        // Do your code
        return true;
    case R.id.help:
          // Do your code
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}
</code>```

Body:
I have created a dropdown list in my android action bar with 2 items inside it. I want to be able to add onClick functions to these 2 items so that I can make them open another activity. Below is the xml code where I set up one of the items in the dropdown list:

 <item
    android:id="@+id/action_home"
    android:title="@string/home"
    app:showAsAction="never" />

I then have the ActionBar.java class:

public class ActionBar extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_home:
            Intent i = new Intent(ActionBar.this, MainActivity.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);

    }
}
}

Whenever I click this 'action_home' item in my actionbar nothing happens, but I need it to open my homepage (MainActivity).

I also have the following code in all of my activities java classes in order to make the actionbar appear:

@Override
public boolean onCreateOptionsMenu (Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

Any help would be greatly appreciated!

Body:
Try This.

   @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

Click handle here.

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.new_game:
        // Do your code
        return true;
    case R.id.help:
          // Do your code
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}


问:
byte swapping and C++/C
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

```<code>int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}
</code>```

Best,
U.

答:
This doesn't depends only on the machine you are working on. If the Fortran infrastructure writes integers in big endian instead of little endian, you'll have to deal with that no matter what the OS is.

I'd suggest you to use ntohl() and ntohs() function, which are clearer than your exchanging routine.

Title: byte swapping and C++/C

Body:
I did a post on comp.lang.c++ and got this

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/afc946826945bdb1/90850f6a0e0edd2d#90850f6a0e0edd2d

but that is still not the answer.

I have a little confusion for a binary read operation.

I am trying to read a binary file with the stream functions. This is a result file of a commercial program(ANSYS), and I know the structure of the file, at least from the manual.

The file is structured as records and the program is written in fortran. So the structure is like

record Length (int)
dummy integer
data (could be int, double)
dummy integer

The first record is a 100 integer block, where this corresponds to data in the above representation.

If I start reading the file and read the first value which is the record length (an integer), I have to swap the bytes to get the correct value of 100.

I did not understand why I have to swap the bytes, because this file is generated on the same machine and they should be using the same system specific routines so that should not be a problem, but it does not seem that is the case. There is  sth else going on. I could not understand this. Can the software be forcing to swap the bytes which I would have hard time to understand the reason?

Any comments are appreciated.

Here is a naive test case

int main () {
  ifstream myfile;
  char intBuffer[4];
  myfile.open ("truss.rst", ios::binary);
  myfile.read(intBuffer, sizeof(int));
  //cout << *((int*)intBuffer) << endl;
  // if I do not use this portion-
  // I do not get what I want
  char *cptr, tmp;
  tmp = intBuffer[0];
  intBuffer[0] = intBuffer[3];
  intBuffer[3] = tmp;
  tmp = intBuffer[1];
  intBuffer[1] = intBuffer[2];
  intBuffer[2] = tmp;
  // -----------------------------
  cout << *((int*)intBuffer) << endl;

  myfile.close();
  return 0;
}

Best,
U.


问:
using multiple return statements in a c++ function
I was wondering if it might be sort of advantageous for a c++ compiler if there's only one return statement in a function. one of my ex-bosses once told me so but I don't get the point if there would be any difference between declaring a return variable or simply having multiple return statements, e.g. in a switch-case statement.

So my question is: is there any difference, maybe in quality, performance or stack memory savings?

答:
This issue might be related to return value optimisation - Compiler wont create the returned variable as a local variable and do a assignmen/copy construction as the function hits the return statement, rather it will build the variable in the memory address of the variable to which the value would be assigned.

You can have multiple return statements and it should not matter, if you are returning the same variable. However if you have multiple variables in your function and you return then differently depending on the code flow the compiler cannot perform such optimisation.

Lets have the following assignment

```<code>string str;
str = make_name(2);
</code>```

Compiler might perform RVO in the following code

```<code>string make_name(int num){
    string result = "Simon";
    if (num & 1){
        result.append(" Hrabec");
        return result;
    } else {
        result.append(" John");
        return result;
    }
}
</code>```

However in this code the compiler cannot say which variable should build in the location of the variable that is having a new value assigned. During the function evaluation both can live at the same time, being updated and the decision which one should be returned can be made at the end.

```<code>string make_name(int num){
    string result1 = "Simon Hrabec";
    string result2 = "Simon John";
    if (num & 1){
        return result1;
    } else {
        return result2;
    }
}
</code>```

However I do not imply to use such programming style.

Body:
This issue might be related to return value optimisation - Compiler wont create the returned variable as a local variable and do a assignmen/copy construction as the function hits the return statement, rather it will build the variable in the memory address of the variable to which the value would be assigned.

You can have multiple return statements and it should not matter, if you are returning the same variable. However if you have multiple variables in your function and you return then differently depending on the code flow the compiler cannot perform such optimisation.

Lets have the following assignment

string str;
str = make_name(2);

Compiler might perform RVO in the following code

string make_name(int num){
    string result = "Simon";
    if (num & 1){
        result.append(" Hrabec");
        return result;
    } else {
        result.append(" John");
        return result;
    }
}

However in this code the compiler cannot say which variable should build in the location of the variable that is having a new value assigned. During the function evaluation both can live at the same time, being updated and the decision which one should be returned can be made at the end.

string make_name(int num){
    string result1 = "Simon Hrabec";
    string result2 = "Simon John";
    if (num & 1){
        return result1;
    } else {
        return result2;
    }
}

However I do not imply to use such programming style.


问:
Ruby on Rails - Emoji not saved in MySQL
I'm working on a Rails app where users can upload photos to their profiles. Every photo has a title, which is supposed to support emoji. Despite changing encoding of the table to utf8mb4 and modifying database.yml when i try to save a photo with emoji in its title MySQL returns an error 'incorrect string value'.

The app is working on Rails 5.0.0.1 with Ruby 2.3.0, MySQL is working on version 5.7.16.

Migration file:

```<code>class CreateUserPhotos < ActiveRecord::Migration[5.0]
  def change
    create_table :user_photos do |t|
      t.string  :title
      t.string  :filename, null: false
      t.integer :visibility, null: false, default: 0
      t.belongs_to :user, foreign_key: true, index: true

      t.timestamps
    end

    reversible do |dir|
      dir.up do
        execute "ALTER TABLE `user_photos` CHANGE `title` `title` VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
      end

      dir.down do
        execute "ALTER TABLE `user_photos` CHANGE `title` `title` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci;"
      end
    end
  end
end
</code>```

database.yml file:

```<code>production:
  adapter: mysql2
  encoding: utf8mb4
  reconnect: false
  database: app_db
  pool: 5
  username: app_user
  password: app_password
  host: localhost
  socket: /var/run/mysqld/mysqld.sock
  collation: utf8mb4_unicode_ci
</code>```

答:
Try to set table's collation to utf8mb4_bin instead of utf8mb4_unicode_ci:

```<code>ALTER TABLE user_photos CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
</code>```

And also change collation property value in database.yml

Body:
I'm working on a Rails app where users can upload photos to their profiles. Every photo has a title, which is supposed to support emoji. Despite changing encoding of the table to utf8mb4 and modifying database.yml when i try to save a photo with emoji in its title MySQL returns an error 'incorrect string value'.

The app is working on Rails 5.0.0.1 with Ruby 2.3.0, MySQL is working on version 5.7.16.

Migration file:

class CreateUserPhotos < ActiveRecord::Migration[5.0]
  def change
    create_table :user_photos do |t|
      t.string  :title
      t.string  :filename, null: false
      t.integer :visibility, null: false, default: 0
      t.belongs_to :user, foreign_key: true, index: true

      t.timestamps
    end

    reversible do |dir|
      dir.up do
        execute "ALTER TABLE `user_photos` CHANGE `title` `title` VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
      end

      dir.down do
        execute "ALTER TABLE `user_photos` CHANGE `title` `title` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci;"
      end
    end
  end
end

database.yml file:

production:
  adapter: mysql2
  encoding: utf8mb4
  reconnect: false
  database: app_db
  pool: 5
  username: app_user
  password: app_password
  host: localhost
  socket: /var/run/mysqld/mysqld.sock
  collation: utf8mb4_unicode_ci

Body:
Try to set table's collation to utf8mb4_bin instead of utf8mb4_unicode_ci:

ALTER TABLE user_photos CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin

And also change collation property value in database.yml


问:
Python: Conversion of a matrix to ordered form
I am new to Python. I have a matrix in Python as this:

```<code>4 4 4 4 1
4 4 4 4 1
1 1 1 1 7
</code>```

I want to convert it to a matrix as this:

```<code>    1   2   3   4   5   6   7
1   1   0   0   4   0   0   0
2   1   0   0   4   0   0   0
3   4   0   0   0   0   0   1
</code>```

The new matrix has number of columns as the maximum number in the original matrix. The number of rows are the same as number of rows in the actual matrix. The value in new matrix is the count of occurrence of each item.

For ex: 1 appears 4 times in third row of original matrix, so our new matrix has value 4 for [3][1], and so on.

How can I convert this? Thx in advance!

答:
Try this,</p>

```<code>a=[[4,4,4,4,1],[4,4,4,4,1],[1,1,1,1,7]]
m =0
for row in a:
   m = max([max(row),m])
b =[]
for row in a:
   r =[]
   i= 1 #set to zero if 0 is included
   while i<=m:
      c = row.count(i)
      r.append(c)
      i +=1
   b.append(r)
print b
</code>```

Body:
I am new to Python. I have a matrix in Python as this:

4 4 4 4 1
4 4 4 4 1
1 1 1 1 7

I want to convert it to a matrix as this:

    1   2   3   4   5   6   7
1   1   0   0   4   0   0   0
2   1   0   0   4   0   0   0
3   4   0   0   0   0   0   1

The new matrix has number of columns as the maximum number in the original matrix. The number of rows are the same as number of rows in the actual matrix. The value in new matrix is the count of occurrence of each item.

For ex: 1 appears 4 times in third row of original matrix, so our new matrix has value 4 for [3][1], and so on.

How can I convert this? Thx in advance!

Body:
Try this,

a=[[4,4,4,4,1],[4,4,4,4,1],[1,1,1,1,7]]
m =0
for row in a:
   m = max([max(row),m])
b =[]
for row in a:
   r =[]
   i= 1 #set to zero if 0 is included
   while i<=m:
      c = row.count(i)
      r.append(c)
      i +=1
   b.append(r)
print b


问:
php search table by id
Im trying to display all the information from a single row in my database table by the id.

When I click search it shows the entire table and the search really doesnt do anything..

Any help would be appreciated. Thank you :)

im using php/mysql

```<code><?php

session_start();
include('connect.php');
if(isset($_POST['search']))
{
$q = $_POST['srch_query'];

?>

<form method="post" action="">
<input type="text" name="srch_query" value="<?php echo $q ?>" required>
<input type="submit" name="search" value="Search">
</form>

<?php

$search = $db->prepare("SELECT species, tree_desc, age, city, state, location FROM tree_info");
$search->execute();
if($search->rowcount()==0){ echo "No product found!"; }
else
{
    echo "Search Result:</br>";?>
    <table border="1" cellspacing="0" cellpadding="4">
        <thead>
            <tr>
                <th>Species</th>
                <th>Description</th>
                <th>Age</th>
                <th>City</th>
                <th>State</th>
                <th>Location</th>
            </tr>
        </thead>

        <tbody>

    <?php foreach($search as $s)
        { ?>

            <tr class="record">
                <td><?php echo $s['species']; ?></td>
                <td><?php echo $s['tree_desc']; ?></td>
                <td><?php echo $s['age']; ?></td>
                <td><?php echo $s['city']; ?></td>
                <td><?php echo $s['state']; ?></td>
                <td><?php echo $s['location']; ?></td>
            </tr>

    <?php   }
}
} ?>

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

答:
You should use $q in your query to filter your resultset. Currently you only send the var to the server, without doing anything with it.

```<code>$search = $db->prepare("SELECT species, tree_desc, age, city, state, location FROM tree_info WHERE tree_id=:id");
$search->execute([':id' => (int) $q]);
</code>```

Title: php search table by id

Body:
Im trying to display all the information from a single row in my database table by the id.

When I click search it shows the entire table and the search really doesnt do anything..

Any help would be appreciated. Thank you :)

im using php/mysql

<?php

session_start();
include('connect.php');
if(isset($_POST['search']))
{
$q = $_POST['srch_query'];

?>

<form method="post" action="">
<input type="text" name="srch_query" value="<?php echo $q ?>" required>
<input type="submit" name="search" value="Search">
</form>

<?php

$search = $db->prepare("SELECT species, tree_desc, age, city, state, location FROM tree_info");
$search->execute();
if($search->rowcount()==0){ echo "No product found!"; }
else
{
    echo "Search Result:
";?>

                Species
                Description
                Age
                City
                State
                Location

    <?php foreach($search as $s)
        { ?>

                <?php echo $s['species']; ?>
                <?php echo $s['tree_desc']; ?>
                <?php echo $s['age']; ?>
                <?php echo $s['city']; ?>
                <?php echo $s['state']; ?>
                <?php echo $s['location']; ?>

    <?php   }
}
} ?>

Body:
You should use $q in your query to filter your resultset. Currently you only send the var to the server, without doing anything with it.

$search = $db->prepare("SELECT species, tree_desc, age, city, state, location FROM tree_info WHERE tree_id=:id");
$search->execute([':id' => (int) $q]);


问:
Copy contents of one List into another List (not reference)
I have two List :

```<code>List<Object> listA = new ArrayList<Object>();
List<Object> newListB = new ArrayList<Object>();
</code>```

How can i copy the contents of listA into newListB such as if i change one of the elements in my copied list, i dont want to change it in my original list.

答:
Try something like this.

```<code> List<Object> listA = new ArrayList<Object>();
    List<Object > newListB = new ArrayList<Object>();

    for (Object object : listA ) {
      newListB .add(object .clone());
    }
</code>```

working example of same is as below

```<code>public static void main(String[] args){
        TestClass test = new TestClass(1);
        List<TestClass> listA = new ArrayList<TestClass>();
        listA.add(test);
            List<TestClass> newListB = new ArrayList<TestClass>();

            for (TestClass test1: listA ) {
                TestClass classSome = new TestClass();
                classSome = (TestClass)test1.clone();
              newListB.add(classSome );
            }

        System.out.println("listA id ="+listA.get(0).id);
        System.out.println("newListB id ="+newListB .get(0).id);

        newListB .get(0).setId(15);

        System.out.println("listA id ="+listA.get(0).id);
        System.out.println("newListB id ="+newListB .get(0).id);
    }
</code>```

And TestClass will be as below

```<code>class TestClass implements Cloneable{
        int id;
        public TestClass(){

        }
        public TestClass(int id){
            this.id = id;
        }

        public int getId(){
            return this.id;
        }

        public void setId(int id){
             this.id=id;
        }

        @Override
         public Object clone() {
                try {
                     return (TestClass)super.clone();
                 }
                 catch (CloneNotSupportedException e) {
                 return null;
                    // This should never happen
                 }
            }
    }
</code>```

Body:
I have two List :

List<Object> listA = new ArrayList<Object>();
List<Object> newListB = new ArrayList<Object>();

How can i copy the contents of listA into newListB such as if i change one of the elements in my copied list, i dont want to change it in my original list.

Body:
Try something like this.

 List<Object> listA = new ArrayList<Object>();
    List<Object > newListB = new ArrayList<Object>();

    for (Object object : listA ) {
      newListB .add(object .clone());
    }

working example of same is as below

public static void main(String[] args){
        TestClass test = new TestClass(1);
        List<TestClass> listA = new ArrayList<TestClass>();
        listA.add(test);
            List<TestClass> newListB = new ArrayList<TestClass>();

            for (TestClass test1: listA ) {
                TestClass classSome = new TestClass();
                classSome = (TestClass)test1.clone();
              newListB.add(classSome );
            }

        System.out.println("listA id ="+listA.get(0).id);
        System.out.println("newListB id ="+newListB .get(0).id);

        newListB .get(0).setId(15);

        System.out.println("listA id ="+listA.get(0).id);
        System.out.println("newListB id ="+newListB .get(0).id);
    }

And TestClass will be as below

class TestClass implements Cloneable{
        int id;
        public TestClass(){

        }
        public TestClass(int id){
            this.id = id;
        }

        public int getId(){
            return this.id;
        }

        public void setId(int id){
             this.id=id;
        }

        @Override
         public Object clone() {
                try {
                     return (TestClass)super.clone();
                 }
                 catch (CloneNotSupportedException e) {
                 return null;
                    // This should never happen
                 }
            }
    }