问:
Responsive design vertical align issue
I have created a page with two divs. The idea of the page is that div on the left should not have scroll bar, so it's position is set to fixed. Only div on the right should have scroll bar. It does work on desktop size, but in responsive design I want both divs have a width of 100%. So they should be aligned one after another. And the problem is that I don't know what property should I use to achieve this vertical align (with my code second div is climbing on top of first). Any ideas?

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  position: fixed;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30%;
    float: left;
  }

  .secondDiv {
    width: 100%;
    height: 70%;
    float: left;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="firstDiv">

  </div>

  <div class="secondDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.</p>
  </div>
</body>

</html></code>```

答:
remove position:fixed to firstDiv and make it float:left and in media query make firstDiv height to 30vh instead of 30%

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  float: left;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30vh;
  }

  .secondDiv {
    width: 100%;
    height: 70%;
    float: left;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="firstDiv">

  </div>

  <div class="secondDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.</p>
  </div>
</body>

</html></code>```

Title: Responsive design vertical align issue

Body:
I have created a page with two divs. The idea of the page is that div on the left should not have scroll bar, so it's position is set to fixed. Only div on the right should have scroll bar. It does work on desktop size, but in responsive design I want both divs have a width of 100%. So they should be aligned one after another. And the problem is that I don't know what property should I use to achieve this vertical align (with my code second div is climbing on top of first). Any ideas?

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  position: fixed;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30%;
    float: left;
  }

  .secondDiv {
    width: 100%;
    height: 70%;
    float: left;
  }
}

<!DOCTYPE html>

  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.

Body:
remove position:fixed to firstDiv and make it float:left and in media query make firstDiv height to 30vh instead of 30%

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  float: left;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30vh;
  }

  .secondDiv {
    width: 100%;
    height: 70%;
    float: left;
  }
}

<!DOCTYPE html>
<html>
<head>
  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="firstDiv">

  </div>

  <div class="secondDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.</p>
  </div>
</body>

</html>


来源: stackexchange

问:
The total number of locks exceeds the lock table size
I'm running a report in MySQL. One of the queries involves inserting a large amount of rows into a temp table. When I try to run it, I get this error:

Error code 1206: The number of locks exceeds the lock table size.

The queries in question are:

```<code>create temporary table SkusBought(
customerNum int(11),
sku int(11),
typedesc char(25),
key `customerNum` (customerNum)
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into skusBought
select t1.* from
    (select customer, sku, typedesc from transactiondatatransit
    where (cat = 150 or cat = 151)
    AND daysfrom07jan1 > 731
group by customer, sku
union
select customer, sku, typedesc from transactiondatadelaware
    where (cat = 150 or cat = 151)
    AND daysfrom07jan1 > 731
group by customer, sku
union
select customer, sku, typedesc from transactiondataprestige
    where (cat = 150 or cat = 151)
    AND daysfrom07jan1 > 731
group by customer, sku) t1
join
(select customernum from topThreetransit group by customernum) t2
on t1.customer = t2.customernum;
</code>```

I've read that changing the configuration file to increase the buffer pool size will help, but that does nothing. What would be the way to fix this, either as a temporary workaround or a permanent fix?

EDIT: changed part of the query. Shouldn't affect it, but I did a find-replace all and didn't realize it screwed that up. Doesn't affect the question.

EDIT 2: Added typedesc to t1. I changed it in the query but not here.

答:
in windows: if you have mysql workbench. Go to server status. find the location of running server file in my case it was:

```<code>C:\ProgramData\MySQL\MySQL Server 5.7
</code>```

open my.ini file and find the buffer_pool_size. Set the value high. default value is 8M.
This is how i fixed this problem

ContentLicense: CC BY-SA 4.0

Body:
I'm running a report in MySQL. One of the queries involves inserting a large amount of rows into a temp table. When I try to run it, I get this error:

Error code 1206: The number of locks exceeds the lock table size.

The queries in question are:

create temporary table SkusBought(
customerNum int(11),
sku int(11),
typedesc char(25),
key `customerNum` (customerNum)
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into skusBought
select t1.* from
    (select customer, sku, typedesc from transactiondatatransit
    where (cat = 150 or cat = 151)
    AND daysfrom07jan1 > 731
group by customer, sku
union
select customer, sku, typedesc from transactiondatadelaware
    where (cat = 150 or cat = 151)
    AND daysfrom07jan1 > 731
group by customer, sku
union
select customer, sku, typedesc from transactiondataprestige
    where (cat = 150 or cat = 151)
    AND daysfrom07jan1 > 731
group by customer, sku) t1
join
(select customernum from topThreetransit group by customernum) t2
on t1.customer = t2.customernum;

I've read that changing the configuration file to increase the buffer pool size will help, but that does nothing. What would be the way to fix this, either as a temporary workaround or a permanent fix?

EDIT: changed part of the query. Shouldn't affect it, but I did a find-replace all and didn't realize it screwed that up. Doesn't affect the question.

EDIT 2: Added typedesc to t1. I changed it in the query but not here.

Body:
in windows: if you have mysql workbench. Go to server status. find the location of running server file in my case it was:

C:\ProgramData\MySQL\MySQL Server 5.7

open my.ini file and find the buffer_pool_size. Set the value high. default value is 8M.
This is how i fixed this problem

ContentLicense: CC BY-SA 3.0


问:
Rendering React components with promises inside the render method
I have a component which gets a collection of items as props and maps them to a collection of components which are rendered as children of a parent component. We use images stored in WebSQL as byte arrays. Within the map function I get an image Id from the item and make an async call to the DAL in order to get the byte array for the image. My problem is that I cannot propagate the promise in to React, since it was not designed to deal with promises in rendering (not as far as I can tell anyway). I come from a C# background, so I guess I'm looking for something like the await keyword for resync-ing branched code.

The map function looks something like this (simplified):

```<code>var items = this.props.items.map(function (item) {
        var imageSrc = Utils.getImageUrlById(item.get('ImageId')); // <-- this contains an async call
        return (
            <MenuItem text={item.get('ItemTitle')}
                      imageUrl={imageSrc} />
       );
    });
</code>```

and the getImageUrlById method looks like this:

```<code>getImageUrlById(imageId) {
    return ImageStore.getImageById(imageId).then(function (imageObject) { //<-- getImageById returns a promise
       var completeUrl = getLocalImageUrl(imageObject.StandardConImage);
       return completeUrl;
    });
}
</code>```

This doesn't work, but I don't know what I need to modify to make this work. I tried adding another promise to the chain, but then I get an error because my render function return a promise instead of legal JSX. I was thinking that maybe I need to leverage one of the React life-cycle methods to fetch the data, but since I need the props to already be there, I can't figure out where I can do this.

答:
Or you can use react-promise :

Install the package :

```<code>npm i react-promise
</code>```

And your code will look something like so :

```<code>import Async from 'react-promise'

var items = this.props.items.map(function (item) {
    var imageSrc = Utils.getImageUrlById(item.get('ImageId')); // <-- this contains an async call
    return (
        <Async promise={imageSrc} then={(val) => <MenuItem text={item.get('ItemTitle')} imageUrl={val}/>} />
    );
});
</code>```

Edit: Oct 2019

The last build of react-promise provide a hook called usePromise:

import usePromise from 'react-promise';

const ExampleWithAsync = (props) => {
  const {value, loading} = usePromise<string>(prom)
  if (loading) return null
  return
{value}
}
}
```

Full docs: react-promise

Body:
I have a component which gets a collection of items as props and maps them to a collection of components which are rendered as children of a parent component. We use images stored in WebSQL as byte arrays. Within the map function I get an image Id from the item and make an async call to the DAL in order to get the byte array for the image. My problem is that I cannot propagate the promise in to React, since it was not designed to deal with promises in rendering (not as far as I can tell anyway). I come from a C# background, so I guess I'm looking for something like the await keyword for resync-ing branched code.

The map function looks something like this (simplified):

var items = this.props.items.map(function (item) {
        var imageSrc = Utils.getImageUrlById(item.get('ImageId')); // <-- this contains an async call
        return (
            <MenuItem text={item.get('ItemTitle')}
                      imageUrl={imageSrc} />
       );
    });

and the getImageUrlById method looks like this:

getImageUrlById(imageId) {
    return ImageStore.getImageById(imageId).then(function (imageObject) { //<-- getImageById returns a promise
       var completeUrl = getLocalImageUrl(imageObject.StandardConImage);
       return completeUrl;
    });
}

This doesn't work, but I don't know what I need to modify to make this work. I tried adding another promise to the chain, but then I get an error because my render function return a promise instead of legal JSX. I was thinking that maybe I need to leverage one of the React life-cycle methods to fetch the data, but since I need the props to already be there, I can't figure out where I can do this.

Body:
Or you can use react-promise :

Install the package :

npm i react-promise

And your code will look something like so :

import Async from 'react-promise'

var items = this.props.items.map(function (item) {
    var imageSrc = Utils.getImageUrlById(item.get('ImageId')); // <-- this contains an async call
    return (
        <Async promise={imageSrc} then={(val) => <MenuItem text={item.get('ItemTitle')} imageUrl={val}/>} />
    );
});

Edit: Oct 2019

The last build of react-promise provide a hook called usePromise:

import usePromise from 'react-promise';

const ExampleWithAsync = (props) => {
  const {value, loading} = usePromise<string>(prom)
  if (loading) return null
  return <div>{value}</div>}
}

Full docs: react-promise


答:
You simply need to add margin-top:30%; to your .secondDiv style (the one inside the media tag). Also, the float style is unnecessary.

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  position: fixed;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30%;
  }

  .secondDiv {
    margin-top:30%;
    width: 100%;
    height: 70%;

  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="firstDiv">

  </div>

  <div class="secondDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.</p>
  </div>
</body>

</html></code>```

Title: Responsive design vertical align issue

Body:
You simply need to add margin-top:30%; to your .secondDiv style (the one inside the media tag). Also, the float style is unnecessary.

body {
  margin: 0;
  padding: 0;
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
}

.firstDiv {
  background-image: url('http://s7d4.scene7.com/is/image/roomandboard/ramsey_939528_15e1_g?$str_g$&size=960,607&scl=1');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.3);
  position: fixed;
}

.secondDiv {
  background-color: white;
  float: right;
}

p {
  line-height: 200%;
  margin: 0;
  padding: 0 20px 0px 20px;
}

@media screen and (max-width: 1020px) {
  .firstDiv {
    width: 100%;
    height:30%;
  }

  .secondDiv {
    margin-top:30%;
    width: 100%;
    height: 70%;

  }
}

<!DOCTYPE html>
<html>
<head>
  <title>Idea</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
  <div class="firstDiv">

  </div>

  <div class="secondDiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a nibh in neque condimentum porta. Nunc consequat fermentum iaculis. Maecenas convallis efficitur nulla, eleifend commodo justo pellentesque quis. Fusce eu arcu nec orci lacinia convallis a vel ex. In vehicula efficitur magna eget lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque lacinia ante vitae nisl dignissim tempus. Nullam vitae sapien et lorem efficitur ullamcorper quis non massa. Vestibulum eu ornare sapien. Morbi molestie urna eros, sed egestas ipsum tincidunt in. Vivamus nec ullamcorper ante. Donec ut dui a mauris volutpat suscipit vitae pharetra diam. Maecenas euismod augue arcu, quis consectetur ligula elementum ac.</p>
  </div>
</body>

</html>


问:
Best way to import Observable from rxjs
In my angular 2 app I have a service that uses the Observable class from the rxjs library.

```<code>import { Observable } from 'rxjs';
</code>```

At the moment I am just using Observable so that I can use the toPromise() function.

I read in another StackOverflow question somewhere that importing in this way and also importing from rxjs/Rx will import a whole lot of unnecessary stuff from the rxjs library that will increase the page load times and/or the code base.

My question is, what is the best way to import Observable so I can use the toPromise() function without having to import everything else?

答:
Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

```<code>import {map} from 'rxjs/operators';
</code>```

2) Others

```<code>import {Observable,of, from } from 'rxjs';
</code>```

Instead of chaining we need to pipe . For example

Old syntax :

```<code>source.map().switchMap().subscribe()
</code>```

New Syntax:

```<code>source.pipe(map(), switchMap()).subscribe()
</code>```

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize

Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. <s>I hope tree-shaking will optimize and pick only needed funcionts( need to verify )</s> As mentioned in comments , tree-shaking can not help. So this is not optimized way.

```<code>public cache = new Rx.BehaviorSubject('');
</code>```

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

```<code> Observable, Observer, BehaviorSubject, Subject, ReplaySubject
</code>```

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

```<code>import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';
</code>```

These are usually accompanied with Observable directly. For example

```<code>Observable.from()
Observable.of()
</code>```

Other such keywords which can be imported using this syntax:

```<code>concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of,
range, throw, timer, using, zip
</code>```

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

```<code>import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';
</code>```

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

```<code>Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));
</code>```

Other such keywords using this syntax:

```<code>audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay,
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck,
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take,
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip
</code>```

FlatMap:
flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.

Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.

Title: Best way to import Observable from rxjs

Body:
In my angular 2 app I have a service that uses the Observable class from the rxjs library.

import { Observable } from 'rxjs';

At the moment I am just using Observable so that I can use the toPromise() function.

I read in another StackOverflow question somewhere that importing in this way and also importing from rxjs/Rx will import a whole lot of unnecessary stuff from the rxjs library that will increase the page load times and/or the code base.

My question is, what is the best way to import Observable so I can use the toPromise() function without having to import everything else?

Body:
Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

import {map} from 'rxjs/operators';

2) Others

import {Observable,of, from } from 'rxjs';

Instead of chaining we need to pipe . For example

Old syntax :

source.map().switchMap().subscribe()

New Syntax:

source.pipe(map(), switchMap()).subscribe()

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize

Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. <s>I hope tree-shaking will optimize and pick only needed funcionts( need to verify )</s> As mentioned in comments , tree-shaking can not help. So this is not optimized way.

public cache = new Rx.BehaviorSubject('');

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

 Observable, Observer, BehaviorSubject, Subject, ReplaySubject

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';

These are usually accompanied with Observable directly. For example

Observable.from()
Observable.of()

Other such keywords which can be imported using this syntax:

concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of,
range, throw, timer, using, zip

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));

Other such keywords using this syntax:

audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay,
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck,
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take,
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip

FlatMap:
flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.

Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.


问:
Get Image from the Storage Folder in View - Laravel 5.4
I'm trying to show the default.jpg avatar picture in my Laravel 5.4 profile.blade.php.

I created a link between the public folder and the storage folder with: php artisan storage:link.

The file is stored:

I check in the source code of my webpage which showed the src="/public/storage/uploads/avatar/default.jpg"

But still no image could be found. Could someone explain to me what I am missing?

答:
You can get file from storage folder directly so you need to create symbolic link between a folder in your storage directory and public directory.

```<code>ln -s path/to/public/storage/uploads/avatar/ /path/to/laravel/public/avatar
</code>```

Then you will able to get it directly in blade :

```<code><img src="{{ asset('/avatar/default.jpg') }}">
</code>```

Body:
You can get file from storage folder directly so you need to create symbolic link between a folder in your storage directory and public directory.

ln -s path/to/public/storage/uploads/avatar/ /path/to/laravel/public/avatar

Then you will able to get it directly in blade :

<img src="{{ asset('/avatar/default.jpg') }}">


问:
Xamarin Studio can't see XIBs in shared project for macOS
I'm using an approach described here for my app.

Currently, I was able to setup such structure for Android and iOS platforms. In general, I have the global core (.NET lib), platform specific core (platform specific Class Library), and some extension (platform specific Class Library).
The problem appears when I try to configure in same way structure for macOS platform. I was able to create platform specific class Library with components that should be reused in apps (for now this is just 1 class with the xib file). But, when I want to use this package in macOS target I got runtime error specific to macOS platform:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[NSNib _initWithNibNamed:bundle:options: ] could not load the nibName: MainView in bundle (null).'

That's strange, because I set up in same way structure for iOS app, and within the iOS target, it's work just great: all source files, xib files, resources are visible and could be freely used from the package.
Note:
I found few issues like described above and some solutions that could resolve this blocking point:

rename xib file - doesn't work

put xib file in rootDir - doesn't work

make sure that BuildAction for file is "InterfaceDefinition" - doesn't work (it always set to InterfaceDefinition)

recreate files - doesn't work

clean all, remove file, reboot, create new - doesn't work

put files in resource dir - doesn't work

force include into package - doesn't work

check that class in VB is correct - doesn't work (was always correct)

check Xcode folder with autogenerated files - doesn't work (in general all files was always there, few times autogenerated h and m files were missed -> I receive another error, but when manually create them -> I faced again with such error)

manually specify bundle for resource - doesn't work (this is strange because for iOS lib all resources are available within the null (main) bundle) - I try to explicitly specify bundle - doesn't work.

So, how to prepare class library within some source files, xib, other resources, so it can be freely accessed from any project that uses this package? Or maybe some steps described above was incorrect?

答:
According to Chris Hamonds from Xamarin Forum here is the answer:

I believe this is a bug we've fixed but is not in the latest builds in our channel. I can reproduce with our Alpha build but installing a build from: https://jenkins.mono-project.com/view/Xamarin.MaciOS/job/xamarin-macios-builds-master/


问:
fopen does not return
I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

```<code>printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);
</code>```

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance,
Souvik

答:
Here's a few reasons:

You've corrupted memory somewhere, and all bets are off as to what's happening (run your program through valgrind)

You're calling this code inside a signal handler, fopen() is not signal async safe, so really anything could happen (a deadlock due to the FILE* internal mutex is common though)

The file is a fifo , in which cases opening the file will block until someone opens the file at the other end(read/writing)

The file is on a stale NFS mount.

The file is a character/block special file with semantics that open blocks until something interesting happens,

ContentLicense: CC BY-SA 2.5

Title: fopen does not return

Body:
I used 'fopen' in a C program to open a file in readonly mode (r). But in my case I observed that fopen call does not return. It does not return NULL or valid pointer - execution gets blocked at fopen call. The patch of file is absolutely correct (I have already verified that) and there is no permission related issues. Can anybody please tell what could be the reason for this kind if behavior. Any kind of help is really appreciable. Is there anything related to gcc or glibc?

EDIT

Here is the sample code

printf("%s %d\n",__FUNCTION__,__LINE__);
if ((fp = fopen(argv[1], "r")) == NULL) {
   printf("%s %d\n",__FUNCTION__,__LINE__);
   return;
}
printf("%s %d\n",__FUNCTION__,__LINE__);

When I run this code, I only get the first print (before calling fopen) and after that program just halts. So fopen does not complete it's operation. The file is a simple configuration file with '.conf' extension and this file can be opened by all other means like vi, cat etc. There should not be any NFS related issue. Filesystem is ext3.

Thanks in advance,
Souvik


问:
Error when running if function on mysql results
I'm trying to set permissions in a MySQL table, But i get the error:

```<code>Warning: mysqli::query() expects parameter 1 to be string, object given in
/public/sites/staffpaneel.mc-wonderland.nl/index.php on line 656

Catchable fatal error: Object of class mysqli_result could not be converted
to string in /public/sites/staffpaneel.mc-wonderland.nl/index.php on line 679
</code>```

Does anyone has i fix for this, I've tried a lot of things but nothing worked

```<code>    <?php
    //Perms
    $PermissiesUitlezen = mysqli_query($conn, "SELECT * FROM `RankPermissies` WHERE RankID ° '".$sqlDataIngelogd['RankID']."'");
    $sqlDataPermissies = mysqli_fetch_assoc($PermissiesUitlezen);

if ($conn->query($PermissiesUitlezen) === TRUE) {
    if ($sqlDataPermissies['AccountMakenMag'] == 1) {
        AccountMakenMag();
    }
    if ($sqlDataPermissies['AccountsMag'] == 1) {
        AccountsMag();
    }
    if ($sqlDataPermissies['MeldingMakenMag'] == 1) {
        MeldingMakenMag();
    }
    if ($sqlDataPermissies['RankAanmakenMag'] == 1) {
        RankAanmakenMag();
    }
    if ($sqlDataPermissies['RanksMag'] == 1) {
        RanksMag();
    }
    if ($sqlDataPermissies['StoringMakenMag'] == 1) {
        StoringMakenMag();
    }
    if ($sqlDataPermissies['StoringenMag'] == 1) {
        StoringenMag();
    }
} else {
    echo "Fout: " . $PermissiesUitlezen . "<br>" . $conn->error;
}
    ?>
</code>```

答:
can you change your query from

```
SELECT * FROM `RankPermissies` WHERE RankID ° '".$sqlDataIngelogd['RankID']."'
```

to

```
SELECT * FROM `RankPermissies` WHERE RankID = '".$sqlDataIngelogd['RankID']."'
```

Then check.

Body:
I'm trying to set permissions in a MySQL table, But i get the error:

Warning: mysqli::query() expects parameter 1 to be string, object given in
/public/sites/staffpaneel.mc-wonderland.nl/index.php on line 656

Catchable fatal error: Object of class mysqli_result could not be converted
to string in /public/sites/staffpaneel.mc-wonderland.nl/index.php on line 679

Does anyone has i fix for this, I've tried a lot of things but nothing worked

    <?php
    //Perms
    $PermissiesUitlezen = mysqli_query($conn, "SELECT * FROM `RankPermissies` WHERE RankID ° '".$sqlDataIngelogd['RankID']."'");
    $sqlDataPermissies = mysqli_fetch_assoc($PermissiesUitlezen);

if ($conn->query($PermissiesUitlezen) === TRUE) {
    if ($sqlDataPermissies['AccountMakenMag'] == 1) {
        AccountMakenMag();
    }
    if ($sqlDataPermissies['AccountsMag'] == 1) {
        AccountsMag();
    }
    if ($sqlDataPermissies['MeldingMakenMag'] == 1) {
        MeldingMakenMag();
    }
    if ($sqlDataPermissies['RankAanmakenMag'] == 1) {
        RankAanmakenMag();
    }
    if ($sqlDataPermissies['RanksMag'] == 1) {
        RanksMag();
    }
    if ($sqlDataPermissies['StoringMakenMag'] == 1) {
        StoringMakenMag();
    }
    if ($sqlDataPermissies['StoringenMag'] == 1) {
        StoringenMag();
    }
} else {
    echo "Fout: " . $PermissiesUitlezen . "
" . $conn->error;
}
    ?>

Body:
can you change your query from

SELECT * FROM `RankPermissies` WHERE RankID ° '".$sqlDataIngelogd['RankID']."'

to

SELECT * FROM `RankPermissies` WHERE RankID = '".$sqlDataIngelogd['RankID']."'

Then check.


问:
Cross-Domain Fonts not loading
I have a website set up on Digital Ocean at http://sugarcoated.co. The domain was bought through Hover.

The IP address for this site is 45.55.209.201

When I load the IP address http://45.55.209.201 in the browser, all fonts load fine, but when I load http://sugarcoated.co, I get the CORS error message.

Access to Font at
  'http://45.55.209.201/wp-content/themes/sugarcoated/css/fonts/montserrat/montserrat-regular-webfont.woff2'
  from origin 'http://sugarcoated.co' has been blocked by CORS policy:
  No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://sugarcoated.co' is therefore not allowed
  access.

I'm new to server configs and am not sure which setting I could have possibly missed.

In hover I have set up the domain like so:

In Digital Ocean, my DNS records are as follows:

答:
To browsers, http://sugarcoated.co and http://45.55.209.201 are totally separate origins.

As explained at https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy and https://en.wikipedia.org/wiki/Same-origin_policy, the  same-origin policy browsers follow at the core of the web security model prevents requests for certain classes of resources cross-origin.

Fonts are one of the resource classes prevented by default from being requested cross-origin.

For browsers to permit font requests cross-origin, the server the fonts are coming from must send an Access-Control-Allow-Origin response header that allows it.

So for browsers to allow http://sugarcoated.co to use fonts from http://45.55.209.201, the response from http://45.55.209.201/wp-content/themes/sugarcoated/css/fonts/… must include either a Access-Control-Allow-Origin: http://sugarcoated.co response header to allow just http://sugarcoated.co  to use the fonts or else Access-Control-Allow-Origin: * to allow any origin to use the fonts.

Either that or you just need to change http://45.55.209.201 to http://sugarcoated.co throughout the source of your documents that need to fonts or else just use a relative URL like /wp-content/themes/sugarcoated/css/fonts/montserrat/montserrat-regular-webfont.woff2 rather than an absolute URL containing the hostname.

It doesn’t matter that underneath, http://sugarcoated.co and http://45.55.209.201 are actually the same server. The browser has no way of knowing that. For browsers to consider them as the same origin, the host parts must exactly match, character-for-character.

Title: Cross-Domain Fonts not loading


问:
Adding gradle task to a subproject in method
I have a project with a bunch of subprojects. Some of the subprojects are utility projects, and some of the projects are actual applications.

The "application" subprojects should all produce a jar file with a given main class etc. To solve this I've put the following in the parent build.gradle:

```<code>def configureApplication(project, mainClass) {
    project.jar { ... }
}
</code>```

and from each subproject's build.gradle, I call configureApplication(project, "my.main.Class")

Now I want to add a deploy task to all application subproject's so that I can deploy all applications using ./gradlew deploy. I've tried to mimic the above approach by putting this in the parent build.gradle:

```<code>def configureDeploy(project) {
    project {
        task deploy {
            println "Deploying!"
        }
    }
}
</code>```

But I'm running in to:

```<code>Could not find method call() for arguments [build_51pn93...closure3@334ebcaa] on project ':subproj'.
</code>```

I've tried about a hundred other variations for the past hour without success.

Question: How do add tasks to some of the subprojects without repeating myself in each subproject's build.gradle? (Also, is using methods in the parent build.gradle a reasonable way of achieving this, or is there a more gradle idiomatic way of doing it?)

答:
I would strongly suggest creating a custom groovy class in your buildSrc with configurable parameters. And then configure them in gradle.

```<code>class DeployTask extends DefaultTask {

    def deploymentName, targets, source, deploymentPlan

    @TaskAction
    def deploy() {
       // your stuff using above variables
    }

}
</code>```

You can use a subprojects{} in main build.gradle to specify everything there instead of repeating yourself.

```<code>subprojects { project ->

    if (project.name.contains('application1')) {

        task deploy (type: package.DeployTask) {
            source          = ""
            deploymentName  = ""
            targettype      = ""
        }

    }

    if (project.name.contains('application2')) {

        task deploy (type: package.DeployTask) {
            source          = ""
            deploymentName  = ""
            targettype      = ""
        }

    }

}
</code>```

or simply add it to the projects itself.

This is going to iterate through all subprojects specified in settings.gradle and create a task deploy for each subproject that met the above condition.

I See @Michael Easter did actually explain it already in a separate answer, and I Agree I have my apps deployed to Weblogic in exactly same way.

Body:
I have a project with a bunch of subprojects. Some of the subprojects are utility projects, and some of the projects are actual applications.

The "application" subprojects should all produce a jar file with a given main class etc. To solve this I've put the following in the parent build.gradle:

def configureApplication(project, mainClass) {
    project.jar { ... }
}

and from each subproject's build.gradle, I call configureApplication(project, "my.main.Class")

Now I want to add a deploy task to all application subproject's so that I can deploy all applications using ./gradlew deploy. I've tried to mimic the above approach by putting this in the parent build.gradle:

def configureDeploy(project) {
    project {
        task deploy {
            println "Deploying!"
        }
    }
}

But I'm running in to:

Could not find method call() for arguments [build_51pn93...closure3@334ebcaa] on project ':subproj'.

I've tried about a hundred other variations for the past hour without success.

Question: How do add tasks to some of the subprojects without repeating myself in each subproject's build.gradle? (Also, is using methods in the parent build.gradle a reasonable way of achieving this, or is there a more gradle idiomatic way of doing it?)

Body:
I would strongly suggest creating a custom groovy class in your buildSrc with configurable parameters. And then configure them in gradle.

class DeployTask extends DefaultTask {

    def deploymentName, targets, source, deploymentPlan

    @TaskAction
    def deploy() {
       // your stuff using above variables
    }

}

You can use a subprojects{} in main build.gradle to specify everything there instead of repeating yourself.

subprojects { project ->

    if (project.name.contains('application1')) {

        task deploy (type: package.DeployTask) {
            source          = ""
            deploymentName  = ""
            targettype      = ""
        }

    }

    if (project.name.contains('application2')) {

        task deploy (type: package.DeployTask) {
            source          = ""
            deploymentName  = ""
            targettype      = ""
        }

    }

}

or simply add it to the projects itself.

This is going to iterate through all subprojects specified in settings.gradle and create a task deploy for each subproject that met the above condition.

I See @Michael Easter did actually explain it already in a separate answer, and I Agree I have my apps deployed to Weblogic in exactly same way.


问:
Ajax post Spring MVC controller?
I am experimenting with Spring Boot and wanted to do an Ajax POST to a Spring Controller. I was testing it from POSTMAN but then I keep getting this error. It seems like instead of posting to my Controller, its looking for a view named jsondata.jsp. How can I fix that issue?</p>

```<code>{
    "timestamp": 1499255141424,
    "status": 404,
    "error": "Not Found",
    "message": "/WEB-INF/view/jsondata.jsp",
    "path": "/jsondata"
}

IndexController.java
package com.example.demo;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

    @Controller
    public class IndexController {

        @Autowired
        private WelcomeService service;
        @RequestMapping("/")
        public String home(Map<String, Object> model) {
            String msg = service.retrieveWelcomeMessage();
            model.put("message",msg);
            return "index";
        }

        @RequestMapping("/next")
        public String next(Map<String, Object> model) {
            model.put("message", "You are in new page !!");
            return "next";
        }

        @RequestMapping(value = "/jsondata", method = RequestMethod.POST,consumes = "application/json")
        public String getfeeddata(@RequestBody String info,Map<String, Object> model)
        {
            model.put("info", info);
            return "next";
        }

        @Component
        class WelcomeService {

            public String retrieveWelcomeMessage() {
                //Complex Method
                 String msgType="";
                 RestTemplate restTemplate = new RestTemplate();
               String consumeJSONString = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", String.class);
               Gson gson = new GsonBuilder().create();
                Quote r = gson.fromJson(consumeJSONString, Quote.class);
                msgType=r.getValue().getQuote();
                return msgType;
            }

        }

    }

MVCConfiguration.java
    package com.example.demo;

    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    import org.springframework.web.servlet.view.JstlView;

    @Configuration
    @EnableWebMvc
    @ComponentScan
    public class MvcConfiguration extends WebMvcConfigurerAdapter
    {
        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/view/");
            resolver.setSuffix(".jsp");
            resolver.setViewClass(JstlView.class);
            registry.viewResolver(resolver);
        }
    }

View
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $('#submit').click(function ()
            {
                var info =[];
                info.push("JsonPostdata");
                $.ajax({
                    type: "post",
                    url: "/jsondata",
                    data: JSON.stringify(info),
                    success: function(msg){
                        console.log("success");
                    }
                });
            });

        });
    </script>
</head>
    <div>
        <div>
            <h1>Spring Boot JSP Example</h1>
            <form >
              <input type="submit" id ="submit" value="Not clicked">

            </form>
            <h2>Hello ${message}</h2>

            Click on this <strong><a href="next">link</a></strong> to visit another page.
        </div>
    </div>

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

答:
This is how an application/json method should look like.

```<code>@RequestMapping(value = "jsondata", method = RequestMethod.POST, headers="Content-Type=application/json")
public @ResponseBody String post(@RequestBody String string) {
            //process your "string" here
            //instead of string you can use other object or array of objects also.
            return string;
}
</code>```

What you are trying to do is adding string to a model. Then if you return a string "next" then controller will look for next.jsp. and that you don't want right?

Title: Ajax post Spring MVC controller?

Body:
I am experimenting with Spring Boot and wanted to do an Ajax POST to a Spring Controller. I was testing it from POSTMAN but then I keep getting this error. It seems like instead of posting to my Controller, its looking for a view named jsondata.jsp. How can I fix that issue?

{
    "timestamp": 1499255141424,
    "status": 404,
    "error": "Not Found",
    "message": "/WEB-INF/view/jsondata.jsp",
    "path": "/jsondata"
}

IndexController.java
package com.example.demo;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

    @Controller
    public class IndexController {

        @Autowired
        private WelcomeService service;
        @RequestMapping("/")
        public String home(Map<String, Object> model) {
            String msg = service.retrieveWelcomeMessage();
            model.put("message",msg);
            return "index";
        }

        @RequestMapping("/next")
        public String next(Map<String, Object> model) {
            model.put("message", "You are in new page !!");
            return "next";
        }

        @RequestMapping(value = "/jsondata", method = RequestMethod.POST,consumes = "application/json")
        public String getfeeddata(@RequestBody String info,Map<String, Object> model)
        {
            model.put("info", info);
            return "next";
        }

        @Component
        class WelcomeService {

            public String retrieveWelcomeMessage() {
                //Complex Method
                 String msgType="";
                 RestTemplate restTemplate = new RestTemplate();
               String consumeJSONString = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", String.class);
               Gson gson = new GsonBuilder().create();
                Quote r = gson.fromJson(consumeJSONString, Quote.class);
                msgType=r.getValue().getQuote();
                return msgType;
            }

        }

    }

MVCConfiguration.java
    package com.example.demo;

    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    import org.springframework.web.servlet.view.JstlView;

    @Configuration
    @EnableWebMvc
    @ComponentScan
    public class MvcConfiguration extends WebMvcConfigurerAdapter
    {
        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/view/");
            resolver.setSuffix(".jsp");
            resolver.setViewClass(JstlView.class);
            registry.viewResolver(resolver);
        }
    }

View
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

Spring Boot JSP Example

            <form >
              <input type="submit" id ="submit" value="Not clicked">

            </form>

Hello ${message}

            Click on this link to visit another page.

Body:
This is how an application/json method should look like.

@RequestMapping(value = "jsondata", method = RequestMethod.POST, headers="Content-Type=application/json")
public @ResponseBody String post(@RequestBody String string) {
            //process your "string" here
            //instead of string you can use other object or array of objects also.
            return string;
}

What you are trying to do is adding string to a model. Then if you return a string "next" then controller will look for next.jsp. and that you don't want right?


问:
JOIN query to retrieve multiple column referencing to a single column from another table
Below is my database diagram which includes three tables and their relations -  PersonalInfo,Subjects,Students

Currently, Students table have below values.

I'm trying to query data to be displayed as below.

What I tried

```<code>SELECT FullName, SubjectName AS 'Subject1', SubjectName AS 'Subject2',
SubjectName AS 'Subject3', SubjectName AS 'Subject4',SubjectName AS 'Subject5'
FROM Subjects JOIN Students ON Students.Subject1 =Subjects.Id
JOIN PersonalInfo ON PersonalInfo.Id=Students.StudId
</code>```

Getting below output which is wrong. It's showing only name of the first subject.

Could anyone guide me the right way.

答:
You have to join multiple time for each subjects. There is a confusion in 'Sudent' and 'PersonalInfo' table ids and Foreign keys. So please join it according to the design. Below query will give you all the subject names as you required. Please consider the query as a logic. IT may contain syntax error as I typed it here

```<code>Select SUB1.SubejctName as Subject1,SUB2.SubejctName as Subject2,SUB3.SubejctName as Subject3,SUB4.SubejctName as Subject4,SUB5.SubejctName as Subject5, from Students S
    inner join Subjects SUB1 on SUB1.id=S.Subject1
    inner join Subjects SUB2 on SUB2.id=S.Subject2
    inner join Subjects SUB3 on SUB3.Id=S.Subject3
    inner join Subjects SUB4 on SUB4.id=S.Subject4
    inner join Subjects SUB5 on SUB5.Id=S.Subject5
</code>```

Todo - Join with PersonalInfo table to show student name.

Body:
Below is my database diagram which includes three tables and their relations -  PersonalInfo,Subjects,Students

Currently, Students table have below values.

I'm trying to query data to be displayed as below.

What I tried

SELECT FullName, SubjectName AS 'Subject1', SubjectName AS 'Subject2',
SubjectName AS 'Subject3', SubjectName AS 'Subject4',SubjectName AS 'Subject5'
FROM Subjects JOIN Students ON Students.Subject1 =Subjects.Id
JOIN PersonalInfo ON PersonalInfo.Id=Students.StudId

Getting below output which is wrong. It's showing only name of the first subject.

Could anyone guide me the right way.

Body:
You have to join multiple time for each subjects. There is a confusion in 'Sudent' and 'PersonalInfo' table ids and Foreign keys. So please join it according to the design. Below query will give you all the subject names as you required. Please consider the query as a logic. IT may contain syntax error as I typed it here

Select SUB1.SubejctName as Subject1,SUB2.SubejctName as Subject2,SUB3.SubejctName as Subject3,SUB4.SubejctName as Subject4,SUB5.SubejctName as Subject5, from Students S
    inner join Subjects SUB1 on SUB1.id=S.Subject1
    inner join Subjects SUB2 on SUB2.id=S.Subject2
    inner join Subjects SUB3 on SUB3.Id=S.Subject3
    inner join Subjects SUB4 on SUB4.id=S.Subject4
    inner join Subjects SUB5 on SUB5.Id=S.Subject5

Todo - Join with PersonalInfo table to show student name.


问:
HTTP Ajax Request via HTTPS Page
I am having a site with some pages on HTTPS connection. From these HTTPS pages, I have to use a HTTP Ajax request for some errors retrieval like blank fields. But this error messages are not coming. Is there any solution to it or I have to make that AJAX request to file on HTTPS connection?</p>

答:
Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup

I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.

So you can open a new http-page with window.open(...) and have that making the request for you

XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser

You put this proxy script on any http page

```<code>onmessage = evt => {
  const port = evt.ports[0]

  fetch(...evt.data).then(res => {
    // the response is not clonable
    // so we make a new plain object
    const obj = {
      bodyUsed: false,
      headers: [...res.headers],
      ok: res.ok,
      redirected: res.redurected,
      status: res.status,
      statusText: res.statusText,
      type: res.type,
      url: res.url
    }

    port.postMessage(obj)

    // Pipe the request to the port (MessageChannel)
    const reader = res.body.getReader()
    const pump = () => reader.read()
    .then(({value, done}) => done
      ? port.postMessage(done)
      : (port.postMessage(value), pump())
    )

    // start the pipe
    pump()
  })
}
</code>```

Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)

```<code>window.popup = window.open(http://.../proxy.html)
</code>```

create your utility function

```<code>function xfetch(...args) {
  // tell the proxy to make the request
  const ms = new MessageChannel
  popup.postMessage(args, '*', [ms.port1])

  // Resolves when the headers comes
  return new Promise((rs, rj) => {

    // First message will resolve the Response Object
    ms.port2.onmessage = ({data}) => {
      const stream = new ReadableStream({
        start(controller) {

          // Change the onmessage to pipe the remaning request
          ms.port2.onmessage = evt => {
            if (evt.data === true) // Done?
              controller.close()
            else // enqueue the buffer to the stream
              controller.enqueue(evt.data)
          }
        }
      })

      // Construct a new response with the
      // response headers and a stream
      rs(new Response(stream, data))
    }
  })
}
</code>```

And make the request like you normally do with the fetch api

```<code>xfetch('http://httpbin.org/get')
  .then(res => res.text())
  .then(console.log)
</code>```

Title: HTTP Ajax Request via HTTPS Page

Body:
Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup

I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.

So you can open a new http-page with window.open(...) and have that making the request for you

XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser

You put this proxy script on any http page

onmessage = evt => {
  const port = evt.ports[0]

  fetch(...evt.data).then(res => {
    // the response is not clonable
    // so we make a new plain object
    const obj = {
      bodyUsed: false,
      headers: [...res.headers],
      ok: res.ok,
      redirected: res.redurected,
      status: res.status,
      statusText: res.statusText,
      type: res.type,
      url: res.url
    }

    port.postMessage(obj)

    // Pipe the request to the port (MessageChannel)
    const reader = res.body.getReader()
    const pump = () => reader.read()
    .then(({value, done}) => done
      ? port.postMessage(done)
      : (port.postMessage(value), pump())
    )

    // start the pipe
    pump()
  })
}

Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)

window.popup = window.open(http://.../proxy.html)

create your utility function

function xfetch(...args) {
  // tell the proxy to make the request
  const ms = new MessageChannel
  popup.postMessage(args, '*', [ms.port1])

  // Resolves when the headers comes
  return new Promise((rs, rj) => {

    // First message will resolve the Response Object
    ms.port2.onmessage = ({data}) => {
      const stream = new ReadableStream({
        start(controller) {

          // Change the onmessage to pipe the remaning request
          ms.port2.onmessage = evt => {
            if (evt.data === true) // Done?
              controller.close()
            else // enqueue the buffer to the stream
              controller.enqueue(evt.data)
          }
        }
      })

      // Construct a new response with the
      // response headers and a stream
      rs(new Response(stream, data))
    }
  })
}

And make the request like you normally do with the fetch api

xfetch('http://httpbin.org/get')
  .then(res => res.text())
  .then(console.log)


问:
What is the default location of the heap dump in elasticsearch?
I had ES running in a 3Node cluster . Recently i had seen the OutofMemory exceptions in my logs . My ES has XX:+HeapDumpOnOutOfMemoryError enabled which will create a heap dump when OutofMemoryError occurs. Even i checked with ps -ef | grep elastic command i got response like this

```<code>elastic+ 2527 1 11 08:47 ? 00:03:59 /usr/bin/java -Xms1720m -Xmx1720m -Djava.awt.headless=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -XX:+DisableExplicitGC -Dfile.encoding=UTF-8 -Djna.nosys=true -Dmapper.allow_dots_in_name=true -Des.path.home=/usr/share/elasticsearch -cp /usr/share/elasticsearch/lib/elasticsearch-2.4.1.jar:/usr/share/elasticsearch/lib/* org.elasticsearch.bootstrap.Elasticsearch start -d -p /var/run/elasticsearch/elasticsearch.pid --default.path.home=/usr/share/elasticsearch --default.path.logs=/var/log/elasticsearch --default.path.data=/var/lib/elasticsearch --default.path.conf=/etc/elasticsearch
</code>```

My error is like this

```<code>[2017-06-27 06:29:36,325][DEBUG][action.search            ] [data] [content-2017][3], node[GDyfoO1ySQ-FgKGFmuJxJg], [P], v[61], s[STARTED], a[id=PN-9iOlNTICPLABsgyd3Qw]: Failed to execute [org.elasticsearch.action.search.SearchRequest@3fbfc52e] lastShard [true]
RemoteTransportException[[data][10.0.x.x:9300][indices:data/read/search[phase/query]]]; nested: QueryPhaseExecutionException[Query Failed [Failed to execute main query]]; nested: OutOfMemoryError[Java heap space];
Caused by: QueryPhaseExecutionException[Query Failed [Failed to execute main query]]; nested: OutOfMemoryError[Java heap space];
        at org.elasticsearch.search.query.QueryPhase.execute(QueryPhase.java:409)
        at org.elasticsearch.search.query.QueryPhase.execute(QueryPhase.java:113)
        at org.elasticsearch.search.SearchService.loadOrExecuteQueryPhase(SearchService.java:372)
        at org.elasticsearch.search.SearchService.executeQueryPhase(SearchService.java:385)
        at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:368)
        at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:365)
        at org.elasticsearch.transport.TransportRequestHandler.messageReceived(TransportRequestHandler.java:33)
        at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:77)
        at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:376)
        at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.OutOfMemoryError: Java heap space
</code>```

I checked all the .hprof files in my server by giving find . -type f -name \*.hprof this command but didnt find any files

Want to know the if heap dump will be generated for the above exception if it is where the location will be for that ?

THANKS

答:
Isn't your command a typo
find . -type f -name \*.hprof instead of find . -type f -name \*.hrpf

Check pwdx <processid> -> U will get the path where the process started from. There's a chance it gets created in that path too.

Search in all the paths like '/etc/elasticsearch', '/var/log/elasticsearch', /usr/share/elasticsearch.. etc (paths from your command output)

-XX:HeapDumpPath=<Path> should be included

Body:
I had ES running in a 3Node cluster . Recently i had seen the OutofMemory exceptions in my logs . My ES has XX:+HeapDumpOnOutOfMemoryError enabled which will create a heap dump when OutofMemoryError occurs. Even i checked with ps -ef | grep elastic command i got response like this

elastic+ 2527 1 11 08:47 ? 00:03:59 /usr/bin/java -Xms1720m -Xmx1720m -Djava.awt.headless=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -XX:+DisableExplicitGC -Dfile.encoding=UTF-8 -Djna.nosys=true -Dmapper.allow_dots_in_name=true -Des.path.home=/usr/share/elasticsearch -cp /usr/share/elasticsearch/lib/elasticsearch-2.4.1.jar:/usr/share/elasticsearch/lib/* org.elasticsearch.bootstrap.Elasticsearch start -d -p /var/run/elasticsearch/elasticsearch.pid --default.path.home=/usr/share/elasticsearch --default.path.logs=/var/log/elasticsearch --default.path.data=/var/lib/elasticsearch --default.path.conf=/etc/elasticsearch

My error is like this

[2017-06-27 06:29:36,325][DEBUG][action.search            ] [data] [content-2017][3], node[GDyfoO1ySQ-FgKGFmuJxJg], [P], v[61], s[STARTED], a[id=PN-9iOlNTICPLABsgyd3Qw]: Failed to execute [org.elasticsearch.action.search.SearchRequest@3fbfc52e] lastShard [true]
RemoteTransportException[[data][10.0.x.x:9300][indices:data/read/search[phase/query]]]; nested: QueryPhaseExecutionException[Query Failed [Failed to execute main query]]; nested: OutOfMemoryError[Java heap space];
Caused by: QueryPhaseExecutionException[Query Failed [Failed to execute main query]]; nested: OutOfMemoryError[Java heap space];
        at org.elasticsearch.search.query.QueryPhase.execute(QueryPhase.java:409)
        at org.elasticsearch.search.query.QueryPhase.execute(QueryPhase.java:113)
        at org.elasticsearch.search.SearchService.loadOrExecuteQueryPhase(SearchService.java:372)
        at org.elasticsearch.search.SearchService.executeQueryPhase(SearchService.java:385)
        at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:368)
        at org.elasticsearch.search.action.SearchServiceTransportAction$SearchQueryTransportHandler.messageReceived(SearchServiceTransportAction.java:365)
        at org.elasticsearch.transport.TransportRequestHandler.messageReceived(TransportRequestHandler.java:33)
        at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:77)
        at org.elasticsearch.transport.TransportService$4.doRun(TransportService.java:376)
        at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.OutOfMemoryError: Java heap space

I checked all the .hprof files in my server by giving find . -type f -name \*.hprof this command but didnt find any files

Want to know the if heap dump will be generated for the above exception if it is where the location will be for that ?

THANKS


问:
selenium WebDriverException driver unexpectedly exited
I am trying to use selenium in python and for some reason I cannot modify the PATH so I can only specify the location of browser driver. However, I tried several drivers and none of them worked.

Environment: Windows 7, Anaconda3-python3.6.1, selenium3.4.3, chrome59.0.3071.115 (Official Build) (64-bit), chromedriver2.30 (win32).

Here are a part of the code I have tried and the corresponding error.

```<code>from selenium import webdriver
driver = webdriver.Chrome("I:\chromedriver.exe")
</code>```

Traceback (most recent call last):

File "", line 1, in  driver = webdriver.Chrome("I:\chromedriver.exe")

File "C:\Users\yz\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in init
    self.service.start()

File "C:\Users\yz\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 96, in start
    self.assert_process_still_running()

File "C:\Users\yz\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 109, in assert_process_still_running
    % (self.path, return_code)

WebDriverException: Service I:\chromedriver.exe unexpectedly exited. Status code was: 1

答:
Here is the Answer to your Question:

While working with Selenium 3.4.3, chromedriver v2.30 and Google Chrome 59.0 to initiate the WebDriver instance we need to pass the absolute path of the chromedriver through the argument executable_path as follows:

```<code>from selenium import webdriver
driver = webdriver.Chrome(executable_path= r"C:\\Utility\\BrowserDrivers\\chromedriver.exe")
</code>```

Let me know if this Answers your Question.

Body:
I am trying to use selenium in python and for some reason I cannot modify the PATH so I can only specify the location of browser driver. However, I tried several drivers and none of them worked.

Environment: Windows 7, Anaconda3-python3.6.1, selenium3.4.3, chrome59.0.3071.115 (Official Build) (64-bit), chromedriver2.30 (win32).

Here are a part of the code I have tried and the corresponding error.

from selenium import webdriver
driver = webdriver.Chrome("I:\chromedriver.exe")

Traceback (most recent call last):

File "", line 1, in  driver = webdriver.Chrome("I:\chromedriver.exe")

File "C:\Users\yz\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in init
    self.service.start()

File "C:\Users\yz\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 96, in start
    self.assert_process_still_running()

File "C:\Users\yz\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 109, in assert_process_still_running
    % (self.path, return_code)

WebDriverException: Service I:\chromedriver.exe unexpectedly exited. Status code was: 1

Body:
Here is the Answer to your Question:

While working with Selenium 3.4.3, chromedriver v2.30 and Google Chrome 59.0 to initiate the WebDriver instance we need to pass the absolute path of the chromedriver through the argument executable_path as follows:

from selenium import webdriver
driver = webdriver.Chrome(executable_path= r"C:\\Utility\\BrowserDrivers\\chromedriver.exe")

Let me know if this Answers your Question.


问:
Vulkan buffer memory management - When do we need staging buffers?
I read a lot of articles on Vulkan memory management and all of them recommend using staging buffers for transferring to the GPU.
But we can already create memory that is device local and host visible, host coherent. It is readable from GPU as well as writable from CPU.

Here is what I thought would be reasonable - Create one big buffer bound to a memory which is device local, host visible and coherent. Now for all dynamic buffers, we just keep using memory from this buffer and bind the buffer at that offset.

But in most examples, they create one host visible buffer and one gpu visible and use the copyBuffer operation for transferring. What is the advantage of this over using just one buffer which is accessible to both cpu and gpu? I am only talking about buffers, not textures.

答:
Create one big buffer bound to a memory which is device local, host visible and coherent.

Not all devices will have such a memory heap. So if you want to be portable you need to account for that.

If the memory you want/have to put a buffer in is not host visible then there is no other option than to use a staging buffer.


问:
Passing a list generated with Javascript to a Spring controller
My app is being built with Spring Boot using a MVC pattern, and as template viewer I use Thymeleaf.

I'm generating a dynamic list with Javascript in a form, which I need to collect as a List with the controller.

I have tried to solve it with a @RequestParam, but generating the list with Javascript, as far as I'm concerned, I can't set the Thymeleaf tags.

This is the list:

```<code><ul id="addItemList">
   <li class="list-group-item" id="group" name="group" value="Outdoors">Outdoors</li>
   <li class="list-group-item" id="group" name="group" value="Entertainment">Entertainment</li>
</ul>
</code>```

Any indication on which approach I should take, would be much appreciated.

Thanks in advance.

答:
Follow the process:

Get the list from controller using ajax

Parse the data then generate li with the retrieved values and update the html of id addItemList

Body:
My app is being built with Spring Boot using a MVC pattern, and as template viewer I use Thymeleaf.

I'm generating a dynamic list with Javascript in a form, which I need to collect as a List with the controller.

I have tried to solve it with a @RequestParam, but generating the list with Javascript, as far as I'm concerned, I can't set the Thymeleaf tags.

This is the list:

Outdoors

Entertainment

Any indication on which approach I should take, would be much appreciated.

Thanks in advance.


问:
how do you write java statements that opens a new binary file named binout.txt and assigns a reference to the connection to binobj
can someone please help me with this:

how do you write java statements that opens a new binary file named binout.txt and assigns a reference to the connection to binobj.

it would be greatly appreciated

答:
Try

```<code>FileOutputStream binobj = new FileOutputStream("binout.txt");
</code>```

Is this homework/

Body:
Try

FileOutputStream binobj = new FileOutputStream("binout.txt");

Is this homework/


问:
jQuery UI : How can I set the resizing limit, aspect ratio when I increase/decrease the size of the div
I have a div tag, it is ( div tag ) resizable and inside that I have a h1 tag ( or it would be any tag ).

The Problem :

I am having 2 problems :

The aspect ratio is not working properly as I want means "when I increase/decrease the size of the div its height gets larger" so how can I set it properly and

I want to fix the smallest width on resizing means "if on decreasing the size it reached to 27px it stop decreasing."

Code

```<code>$('.draggable_element').each(function() {
        $(this).resizable({
        autoHide: true,
      handles: 's,e,w',
      aspectRatio: 1/9
    });
})
</code>```

Here is my jsFiddle

UPDATE :

I think I have not properly explained my first problem to know what's the first problem please visit to my fiddle link try to resize (increase/decrease) the div from left side or right side the height of the div will automatically increase that the problem

答:
The aspectRatio should be Boolean. You can set the size using Width and Height.

Alternatively you could also try to change the ratio to '9/1': aspectRatio: 9/1, should do the work too...

Set 'minWidth: 27'.

```<code>$(this).resizable({
  autoHide: true,
  handles: 's,e,w',
  aspectRatio: true,
  minWidth: 27
});
</code>```

Body:
I have a div tag, it is ( div tag ) resizable and inside that I have a h1 tag ( or it would be any tag ).

The Problem :

I am having 2 problems :

The aspect ratio is not working properly as I want means "when I increase/decrease the size of the div its height gets larger" so how can I set it properly and

I want to fix the smallest width on resizing means "if on decreasing the size it reached to 27px it stop decreasing."

Code

$('.draggable_element').each(function() {
        $(this).resizable({
        autoHide: true,
      handles: 's,e,w',
      aspectRatio: 1/9
    });
})

Here is my jsFiddle

UPDATE :

I think I have not properly explained my first problem to know what's the first problem please visit to my fiddle link try to resize (increase/decrease) the div from left side or right side the height of the div will automatically increase that the problem

Body:
The aspectRatio should be Boolean. You can set the size using Width and Height.

Alternatively you could also try to change the ratio to '9/1': aspectRatio: 9/1, should do the work too...

Set 'minWidth: 27'.

$(this).resizable({
  autoHide: true,
  handles: 's,e,w',
  aspectRatio: true,
  minWidth: 27
});


问:
Run tests on multiple browsers (Sequentially)
I'm currently testing with Chrome(driver) only. I want to test it with Firefox and Safari too. One after the other, it cannot be in parallel.

Here's my gulp task to start the tests:

```<code>gulp.task('test', function() {
  return gulp.src('*test/features/*').pipe(cucumber({
    'steps': '*test/features/steps/*.js'
  }));
});
</code>```

A simple feature file:

```<code>Feature: UI
    Testing UI

    Scenario: Check the title of the page
        When I open the homepage
        Then I should see "Test - IntApp" in the title
</code>```

And the step file:

```<code>const chrome = require('selenium-webdriver/chrome');
const webdriver = require('selenium-webdriver');
const assert = require('assert');

module.exports = function () {
    let options = new chrome.Options();
    options.addArguments('start-maximized');

    var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();

    this.When('I open the homepage', function (done) {
        driver.get('http://intapp.dev/').then(done);
    });

    this.Then('I should see "Test - IntApp" in the title', function (done) {
        driver.getTitle().then(function(title) {
          assert.equal(title, "Test - IntApp");
        }).then(done);
    });

    this.registerHandler('AfterFeatures', function (features) {
        return driver.quit();
    });
};
</code>```

I was thinking that maybe I could pass the browser's name as parameter somehow from the gulp task, but it doesn't seem to be possible.

答:
I was thinking that maybe I could pass the browser's name as parameter
  somehow from the gulp task, but it doesn't seem to be possible.

Just remember that each browser has it's own driver, each driver needs to be created/initialized in it's own way.

If you go in the direction you planed,
you could keep all browser handles (after you create them) in an array, and just pull the one you want by it's name.

Body:
I'm currently testing with Chrome(driver) only. I want to test it with Firefox and Safari too. One after the other, it cannot be in parallel.

Here's my gulp task to start the tests:

gulp.task('test', function() {
  return gulp.src('*test/features/*').pipe(cucumber({
    'steps': '*test/features/steps/*.js'
  }));
});

A simple feature file:

Feature: UI
    Testing UI

    Scenario: Check the title of the page
        When I open the homepage
        Then I should see "Test - IntApp" in the title

And the step file:

const chrome = require('selenium-webdriver/chrome');
const webdriver = require('selenium-webdriver');
const assert = require('assert');

module.exports = function () {
    let options = new chrome.Options();
    options.addArguments('start-maximized');

    var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();

    this.When('I open the homepage', function (done) {
        driver.get('http://intapp.dev/').then(done);
    });

    this.Then('I should see "Test - IntApp" in the title', function (done) {
        driver.getTitle().then(function(title) {
          assert.equal(title, "Test - IntApp");
        }).then(done);
    });

    this.registerHandler('AfterFeatures', function (features) {
        return driver.quit();
    });
};

I was thinking that maybe I could pass the browser's name as parameter somehow from the gulp task, but it doesn't seem to be possible.


问:
Extract statusCode from json response in Laravel
Working in Laravel 5.4

After deleting an image (in my ImageRepository) I send a Json response back to my Controller (where I called the ImageRepository). Now I simply want to check what status code I am getting back to further build on that.

```<code>return Response::json([
    'error' => false,
    'code'  => 200,
    'message' => 'Image was deleted!'
], 200);
</code>```

When I receive this response in my Controller and I dd(); it I see this:

```<code>JsonResponse {#461 ▼
  #data: "{"error":false,"code":200,"message":"Image was deleted!"}"
  #callback: null
  #encodingOptions: 0
  +headers: ResponseHeaderBag {#459 ▶}
  #content: "{"error":false,"code":200,"message":"Image was deleted!"}"
  #version: "1.0"
  #statusCode: 200
  #statusText: "OK"
  #charset: null
  +original: array:3 [▶]
  +exception: null
}
</code>```

I only need to extract the statusCode so that I can send the correct notification to the user (image deleted, image not found, imaage ...)

Can't believe I cannot find a solution for this anywhere.

Thanks

答:
https://laravel.com/api/5.8/Illuminate/Http/RedirectResponse.html

```<code>$response->status();
</code>```

Get the status code for the response.

It will return the status code

Body:
Working in Laravel 5.4

After deleting an image (in my ImageRepository) I send a Json response back to my Controller (where I called the ImageRepository). Now I simply want to check what status code I am getting back to further build on that.

return Response::json([
    'error' => false,
    'code'  => 200,
    'message' => 'Image was deleted!'
], 200);

When I receive this response in my Controller and I dd(); it I see this:

JsonResponse {#461 ▼
  #data: "{"error":false,"code":200,"message":"Image was deleted!"}"
  #callback: null
  #encodingOptions: 0
  +headers: ResponseHeaderBag {#459 ▶}
  #content: "{"error":false,"code":200,"message":"Image was deleted!"}"
  #version: "1.0"
  #statusCode: 200
  #statusText: "OK"
  #charset: null
  +original: array:3 [▶]
  +exception: null
}

I only need to extract the statusCode so that I can send the correct notification to the user (image deleted, image not found, imaage ...)

Can't believe I cannot find a solution for this anywhere.

Thanks

Body:
https://laravel.com/api/5.8/Illuminate/Http/RedirectResponse.html

$response->status();

Get the status code for the response.

It will return the status code


问:
NSFileManager createFile Failed
```<code>NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath;

if (str_FolderName!=nil){
    filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/%@",str_FolderName,str_FileName]];
} else {
    filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",str_FileName]];
}

NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *data;

if ([fileManager fileExistsAtPath: filePath])
{
    //file is exist
    data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

} else {
    BOOL Success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    // sometime return YES, sometime return NO <<< this is my question
    if(Success == YES){
        data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    }else{
        data = [[NSMutableDictionary alloc] init];
    }
}

for (uint32_t u32_Cnt=0;u32_Cnt<arr_Keys.count;u32_Cnt++) {
    [data setValue:[NSString stringWithFormat:@"%@",[marr_Data objectAtIndex:u32_Cnt]] forKey:[arr_Keys objectAtIndex:u32_Cnt]];
}

if ([data writeToFile:filePath atomically: YES])
{
    NSLog(@"[Save OK]");

    return DEF_PASS;
} else {
    NSLog(@"[Save Fail]");  <<<<   now happened
}
</code>```

If I have checked file is not exist, then i want to create file as filepath

My device sometime success, sometime failed

Filepath is as below:

@"/var/mobile/Containers/Data/Application/xxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx/Documents/mfolder/myfile"

Someone could help me?

答:
I update some of your code. I put proper allocation of NSFilemanager and its work for me. You can have issue in file path or filemanager object.

```<code> NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath;

    if (str_FolderName!=nil){
        filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/%@",str_FolderName,str_FileName]];
    }else{
        filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",str_FileName]];
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSMutableDictionary *data;
    if ([fileManager fileExistsAtPath: filePath])
    {
        //file is exist
        data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

    }
    else
    {
        if (str_FolderName!=nil){
            NSString *strDicPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",str_FolderName]];
            // You need to create director before creating file.
            if (![[NSFileManager defaultManager] fileExistsAtPath:strDicPath])
            {
                NSError *error;
                [[NSFileManager defaultManager] createDirectoryAtPath:strDicPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
            }

        }
        BOOL Success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        // sometime return YES, sometime return NO <<< this is my question
        if(Success == YES){
            data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
        }else{
            data = [[NSMutableDictionary alloc] init];
        }
    }
</code>```

I also check this code in simulator and device both.

For writing string into file:

```<code>NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
</code>```

Title: NSFileManager createFile Failed

Body:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath;

if (str_FolderName!=nil){
    filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/%@",str_FolderName,str_FileName]];
} else {
    filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",str_FileName]];
}

NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *data;

if ([fileManager fileExistsAtPath: filePath])
{
    //file is exist
    data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

} else {
    BOOL Success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    // sometime return YES, sometime return NO <<< this is my question
    if(Success == YES){
        data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    }else{
        data = [[NSMutableDictionary alloc] init];
    }
}

for (uint32_t u32_Cnt=0;u32_Cnt<arr_Keys.count;u32_Cnt++) {
    [data setValue:[NSString stringWithFormat:@"%@",[marr_Data objectAtIndex:u32_Cnt]] forKey:[arr_Keys objectAtIndex:u32_Cnt]];
}

if ([data writeToFile:filePath atomically: YES])
{
    NSLog(@"[Save OK]");

    return DEF_PASS;
} else {
    NSLog(@"[Save Fail]");  <<<<   now happened
}

If I have checked file is not exist, then i want to create file as filepath

My device sometime success, sometime failed

Filepath is as below:

@"/var/mobile/Containers/Data/Application/xxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx/Documents/mfolder/myfile"

Someone could help me?

Body:
I update some of your code. I put proper allocation of NSFilemanager and its work for me. You can have issue in file path or filemanager object.

 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath;

    if (str_FolderName!=nil){
        filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/%@",str_FolderName,str_FileName]];
    }else{
        filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",str_FileName]];
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSMutableDictionary *data;
    if ([fileManager fileExistsAtPath: filePath])
    {
        //file is exist
        data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

    }
    else
    {
        if (str_FolderName!=nil){
            NSString *strDicPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",str_FolderName]];
            // You need to create director before creating file.
            if (![[NSFileManager defaultManager] fileExistsAtPath:strDicPath])
            {
                NSError *error;
                [[NSFileManager defaultManager] createDirectoryAtPath:strDicPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
            }

        }
        BOOL Success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        // sometime return YES, sometime return NO <<< this is my question
        if(Success == YES){
            data = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
        }else{
            data = [[NSMutableDictionary alloc] init];
        }
    }

I also check this code in simulator and device both.

For writing string into file:

NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];


问:
HTML and AngularJS Interpolation for email form
I'm using formspree.io for some simple contact forms and want to dynamically change the email address with Angular1 so it looks something like this:

```<code><form action="https://formspree.io/{{ user.email }}" method="POST">
</code>```

Can anyone help shine some light on this? I can't quite work it out so any thoughts would be massively appreciated.

答:
Trust the url input with SCE (Strict Contextual Escaping (SCE)

See sce docs

Body:
I'm using formspree.io for some simple contact forms and want to dynamically change the email address with Angular1 so it looks something like this:

<form action="https://formspree.io/{{ user.email }}" method="POST">

Can anyone help shine some light on this? I can't quite work it out so any thoughts would be massively appreciated.