问:
Importing Python SendGrid on GAE
I have an App Engine project which I’d like to start using SendGrid with. I downloaded and installed the library and I can import sendgrid normally from the Python terminal. However, when I type import sendgrid in the GAE code, it gives me the following error message:

```<code>import sendgrid
ImportError: No module named sendgrid
</code>```

I downloaded the SendGrid folder from GitHub and put it in the lib directory of my project. What am I missing?

答:
This can be solved by installing SendGrid directly in lib dir of your project.

```<code>> pip install sendgrid -t lib
</code>```

In order to do this, you need to have appengine_config.py in your root directory. It allows you to include third-party packages and its contents look like this:

```<code>from google.appengine.ext import vendor

vendor.add('lib')
</code>```

Then you just call import sendgrid and you are ready to go.

Title: Importing Python SendGrid on GAE

Body:
I have an App Engine project which I’d like to start using SendGrid with. I downloaded and installed the library and I can import sendgrid normally from the Python terminal. However, when I type import sendgrid in the GAE code, it gives me the following error message:

import sendgrid
ImportError: No module named sendgrid

I downloaded the SendGrid folder from GitHub and put it in the lib directory of my project. What am I missing?

Body:
This can be solved by installing SendGrid directly in lib dir of your project.

> pip install sendgrid -t lib

In order to do this, you need to have appengine_config.py in your root directory. It allows you to include third-party packages and its contents look like this:

from google.appengine.ext import vendor

vendor.add('lib')

Then you just call import sendgrid and you are ready to go.


来源: stackexchange

问:
Embedding a live chart from an external page into Wordpress post
My wordpress site has a blog on the homepage, e.g. www.myblog.com.
I made a web app in Flask (a Python web development framework) which has the url www.myblog.com:8000/chart1

I want to show this within a post on my homepage/blog. If this is possible how can I do this?

答:
An iframe should work. WordPress strips iframes out of the post editor, but you could either hardcode the  HTML into a specific post type or something. I think a simpler option would be just to use a plugin like Iframe Shortcode:

Iframe Shortcode

Install/activate that and it'll give you an option to insert a shortcode into your post content.

ContentLicense: CC BY-SA 3.0

Body:
An iframe should work. WordPress strips iframes out of the post editor, but you could either hardcode the <iframe src="www.myblog.com:8000/chart1"></iframe> HTML into a specific post type or something. I think a simpler option would be just to use a plugin like Iframe Shortcode:

Iframe Shortcode

Install/activate that and it'll give you an option to insert a shortcode into your post content.


问:
Populate drop-down list in HTML using JSON data
I'm a student and very new to code. I've created a drop-down list using HTML and CSS, and I'm trying to populate it using data from JSON. This is my HTML code:

```<code>    <div class="dropdown">
  <button class="dropbtn">Choose your area</button>
  <div class="dropdown-content">
    <a href="#">Place 1</a>
    <a href="#">Place 2</a>
    <a href="#">Place 3</a>

  </div>
</div>
</code>```

I'm trying to replace 'Place 1', 'Place 2' etc with about 150 real place names. These are in JSON:

```<code>    "areaNames": [
 {
   "A": 1,
   "B": "Barking & Dagenham"
 },
 {
   "A": 2,
   "B": "Barnet"
 },
</code>```

and so on. How do I pull in the place names from JSON to be in the place of  'Place 1', 'Place 2' etc? I've tried following the advice in response to similar tutorials but that seems to give me a list of several separate drop-down boxes rather than a simple list of places.

Thanks for your help.

答:
Here is working example with pure JS.

var areaNames = [
  {
     "A": 1,
     "B": "Barking & Dagenham",
     "C": "https://google.com"
  },
  {
     "A": 2,
     "B": "Barnet",
     "C": "https://google.com"
  }
]

var dropdownContent = document.querySelector('.dropdown-content');

for (i = 0; i < areaNames.length; i++) {

  var element = areaNames[i];

  var htmlToAppend = document.createElement('a');
  htmlToAppend.innerHTML = element.B;
  htmlToAppend.href = element.C;

  dropdownContent.appendChild(htmlToAppend);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  display: block;
}</code>```

  <button class="dropbtn">Choose your area</button>

```

Body:
I'm a student and very new to code. I've created a drop-down list using HTML and CSS, and I'm trying to populate it using data from JSON. This is my HTML code:

  <button class="dropbtn">Choose your area</button>

    Place 1
    Place 2
    Place 3

I'm trying to replace 'Place 1', 'Place 2' etc with about 150 real place names. These are in JSON:

    "areaNames": [
 {
   "A": 1,
   "B": "Barking & Dagenham"
 },
 {
   "A": 2,
   "B": "Barnet"
 },

and so on. How do I pull in the place names from JSON to be in the place of  'Place 1', 'Place 2' etc? I've tried following the advice in response to similar tutorials but that seems to give me a list of several separate drop-down boxes rather than a simple list of places.

Thanks for your help.

Body:
Here is working example with pure JS.

var areaNames = [
  {
     "A": 1,
     "B": "Barking & Dagenham",
     "C": "https://google.com"
  },
  {
     "A": 2,
     "B": "Barnet",
     "C": "https://google.com"
  }
]

var dropdownContent = document.querySelector('.dropdown-content');

for (i = 0; i < areaNames.length; i++) {

  var element = areaNames[i];

  var htmlToAppend = document.createElement('a');
  htmlToAppend.innerHTML = element.B;
  htmlToAppend.href = element.C;

  dropdownContent.appendChild(htmlToAppend);
}

a {
  display: block;
}

<div class="dropdown">
  <button class="dropbtn">Choose your area</button>
  <div class="dropdown-content">

  </div>
</div>


问:
insert information to external DB in android studio
I'm using android studio to get information from user and insert it into external DB, and i saw a lot of videos in youtube but still there is a problem when run it says: "registration success" but doesn't insert into DB

This is my code in android studio

public class signup extends AppCompatActivity {

```<code>EditText email,password,name;
Switch visually_impaired;
String Email,Password,Name,Visually_impaired,Beacon_alert,Buildings_alert;;
Context ctx = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);
    name = (EditText) findViewById(R.id.name_editText);
    password = (EditText) findViewById(R.id.password_editText);
    email = (EditText) findViewById(R.id.email_editText);
    visually_impaired = (Switch) findViewById(R.id.blindOpt);

}

public void register(View v){
    Email = email.getText().toString();
    Name = name.getText().toString();
    Password = password.getText().toString();
    Visually_impaired = visually_impaired.getText().toString();
    BackGround b = new BackGround(this);
    b.execute(Email,Password,Name,Visually_impaired);
}

class BackGround extends AsyncTask<String,String,String> {

    Context ctx;
    public BackGround(Context ctx){
        this.ctx = ctx;
    }

    @Override
    protected String doInBackground(String... strings) {
        String email = strings[0];
        String password = strings[1];
        String name = strings[2];
        String visually_impaired = strings[3];

        try {
            URL url = new URL("http://ksuexpress.com/register.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream os = httpURLConnection.getOutputStream();
            BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            String data = URLEncoder.encode("email","UTF-8")+ " = "+URLEncoder.encode(email,"UTF-8") +"&"+
                    URLEncoder.encode("password","UTF-8")+ " = "+URLEncoder.encode(password,"UTF-8") +"&"+
                    URLEncoder.encode("name","UTF-8")+ " = "+URLEncoder.encode(name,"UTF-8") +"&"+
                    URLEncoder.encode("visually_impaired","UTF-8")+ " = "+URLEncoder.encode(visually_impaired,"UTF-8");
            bufferWriter.write(data);
            bufferWriter.flush();
            bufferWriter.close();
            os.close();
            InputStream is = httpURLConnection.getInputStream();
            is.close();
            return "Registration success....";

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result){
        Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();

    }
}
</code>```

}

and also i have a php code in server that uses POST and insert it to the DB

can anyone help me please ...

答:
Some possible fixes:

change " = " to "=" without spaces

add some logs in doInBackground and make sure you're getting the correct parameters into email,password,etc.

change InputStream is = httpURLConnection.getInputStream(); is.close(); to httpURLConnection.connect();

Body:
I'm using android studio to get information from user and insert it into external DB, and i saw a lot of videos in youtube but still there is a problem when run it says: "registration success" but doesn't insert into DB

This is my code in android studio

public class signup extends AppCompatActivity {

EditText email,password,name;
Switch visually_impaired;
String Email,Password,Name,Visually_impaired,Beacon_alert,Buildings_alert;;
Context ctx = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);
    name = (EditText) findViewById(R.id.name_editText);
    password = (EditText) findViewById(R.id.password_editText);
    email = (EditText) findViewById(R.id.email_editText);
    visually_impaired = (Switch) findViewById(R.id.blindOpt);

}

public void register(View v){
    Email = email.getText().toString();
    Name = name.getText().toString();
    Password = password.getText().toString();
    Visually_impaired = visually_impaired.getText().toString();
    BackGround b = new BackGround(this);
    b.execute(Email,Password,Name,Visually_impaired);
}

class BackGround extends AsyncTask<String,String,String> {

    Context ctx;
    public BackGround(Context ctx){
        this.ctx = ctx;
    }

    @Override
    protected String doInBackground(String... strings) {
        String email = strings[0];
        String password = strings[1];
        String name = strings[2];
        String visually_impaired = strings[3];

        try {
            URL url = new URL("http://ksuexpress.com/register.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream os = httpURLConnection.getOutputStream();
            BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            String data = URLEncoder.encode("email","UTF-8")+ " = "+URLEncoder.encode(email,"UTF-8") +"&"+
                    URLEncoder.encode("password","UTF-8")+ " = "+URLEncoder.encode(password,"UTF-8") +"&"+
                    URLEncoder.encode("name","UTF-8")+ " = "+URLEncoder.encode(name,"UTF-8") +"&"+
                    URLEncoder.encode("visually_impaired","UTF-8")+ " = "+URLEncoder.encode(visually_impaired,"UTF-8");
            bufferWriter.write(data);
            bufferWriter.flush();
            bufferWriter.close();
            os.close();
            InputStream is = httpURLConnection.getInputStream();
            is.close();
            return "Registration success....";

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result){
        Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();

    }
}

}

and also i have a php code in server that uses POST and insert it to the DB

can anyone help me please ...


问:
Is it possible to convert Option<Result<T, E>> to a Result<Option<T>, E> without using match?
My first thought is to map the Option, but I can't use try! from inside of the closure. The match statement looks unnecessary, but I can't figure out how to simplify it.

```<code>fn example<T, E>(val: Option<Result<T, E>>) -> Result<Option<T>, E> {
    Ok(match val {
        Some(v) => Some(v?),
        None => None
    })
}
</code>```

答:
You can use Option::map_or():

```<code>val.map_or(Ok(None), |v| v.map(Some))
</code>```

Body:
My first thought is to map the Option, but I can't use try! from inside of the closure. The match statement looks unnecessary, but I can't figure out how to simplify it.

fn example<T, E>(val: Option<Result<T, E>>) -> Result<Option<T>, E> {
    Ok(match val {
        Some(v) => Some(v?),
        None => None
    })
}

Body:
You can use Option::map_or():

val.map_or(Ok(None), |v| v.map(Some))


问:
Laravel 5.4 Multi auth - Auth::guard()->user() empty
I've created a multi auth test in Laravel 5.4. It's using custom middlewares, custom Eloquent providers, etc. The auth flow is working, I can login in both ways. But if the user is signed in, in the home controller when I want to check the user with Auth::user() or Auth::guard()->user(), it's empty. The Auth::guard() is empty as well. But I don't understand, why?! It should contains the signed in user instance, shouldn't it?

Also the $request->getUserResolver() says that the guard is null... o.O

What did I do wrong?

Here it is my test repo, if you want to check my code.

Thank you in advance!

Edit 1:

In the \app\Http\Controllers\Employee\HomeController.php the Auth::guard()->user() and the Auth::user() are empty.

```<code>namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{

    public function __construct(Request $request)
    {
        $this->middleware('auth.employee:employee');
    }

    public function index(Request $request)
    {
        $users[] = Auth::user();
        $users[] = Auth::guard()->user();
        $users[] = Auth::guard('employee')->user();

        dd($users);

        return view('employees.home.index');
    }
}
</code>```

答:
Auth::shouldUse(your_guard_name);

call this in your login function

Body:
I've created a multi auth test in Laravel 5.4. It's using custom middlewares, custom Eloquent providers, etc. The auth flow is working, I can login in both ways. But if the user is signed in, in the home controller when I want to check the user with Auth::user() or Auth::guard()->user(), it's empty. The Auth::guard() is empty as well. But I don't understand, why?! It should contains the signed in user instance, shouldn't it?

Also the $request->getUserResolver() says that the guard is null... o.O

What did I do wrong?

Here it is my test repo, if you want to check my code.

Thank you in advance!

Edit 1:

In the \app\Http\Controllers\Employee\HomeController.php the Auth::guard()->user() and the Auth::user() are empty.

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{

    public function __construct(Request $request)
    {
        $this->middleware('auth.employee:employee');
    }

    public function index(Request $request)
    {
        $users[] = Auth::user();
        $users[] = Auth::guard()->user();
        $users[] = Auth::guard('employee')->user();

        dd($users);

        return view('employees.home.index');
    }
}


问:
Changing provider in tests using ReflectiveInjector
Is it possible to change provider using ReflectiveInjector in the same context? I need B to use different value in second test. A & B are services...

  let injector: ReflectiveInjector;
  beforeEach(() => {
    injector = ReflectiveInjector.resolveAndCreate([
      A, { provide: B, useValue: null }
    ]);
  });

  ...

  it('should be null', () => {
    const a = injector.get(A);
    expect(a.B).toBe(null)
  });

  it('shoul NOT be null', () => {
    const a = injector.get(A);
    // need something like this:
    // a.B = injector.CHANGE_B_PLEASE({ provide: B, useValue: true })
    expect(a.B).not.toBe(null)
  });
```

答:
My solution for testing:

  let injector: ReflectiveInjector;
  setup((value) => {
    injector = ReflectiveInjector.resolveAndCreate([
      A, { provide: B, useValue: value }
    ]);
  });

  ...

  it('should be null', () => {
    setup(null);
    const a = injector.get(A);
    expect(a.B).toBe(null)
  });

  it('shoul NOT be null', () => {
    setup(true);
    const a = injector.get(A);
    const b = injector.get(B);
    expect(a.B).toBe(true)
    expect(b).toBe(true)
  });
```

For more information check:

DI Guide

Transient Dependencies

DI Advanced Topics

Body:
My solution for testing:

  let injector: ReflectiveInjector;
  setup((value) => {
    injector = ReflectiveInjector.resolveAndCreate([
      A, { provide: B, useValue: value }
    ]);
  });

  ...

  it('should be null', () => {
    setup(null);
    const a = injector.get(A);
    expect(a.B).toBe(null)
  });

  it('shoul NOT be null', () => {
    setup(true);
    const a = injector.get(A);
    const b = injector.get(B);
    expect(a.B).toBe(true)
    expect(b).toBe(true)
  });

For more information check:

DI Guide

Transient Dependencies

DI Advanced Topics


问:
spring mvc 3.0: put a bunch of .jsp files under spring's control
In my spring mvc 3.0 project I have a directory full of .jsp files (~150) which I want to put under spring's control.

Until now they where invoked by web.xml directly, without going thru the spring servlet.

From now, I want to put them all under spring's control to enjoy spring's goodies and make my project more uniform.

Of course, I don't want to write a single controller for each .jsp file. How can I do this?

答:
JSPs must not include any code that requires dependency injection. So don't do it.

If you really must, you can use

```<code><%!
    public void init() {
        ApplicationContextUtils.getRequiredWebApplicationContext(
             getServletContext()).getAutowireCapableBeanFactory()
             .autowireBean(this);
    }
%>
</code>```

But this is extremely ugly.

ContentLicense: CC BY-SA 2.5

Body:
JSPs must not include any code that requires dependency injection. So don't do it.

If you really must, you can use

<%!
    public void init() {
        ApplicationContextUtils.getRequiredWebApplicationContext(
             getServletContext()).getAutowireCapableBeanFactory()
             .autowireBean(this);
    }
%>

But this is extremely ugly.


问:
Issue with passing object to child react componenet
I am using react, currently I need to display a html list, in LocationFinderList I am initializing Location elements but Location does not get the object and instead I get only numeric property as shown in the pictures.

How to fix my script so Location show the name for an object passe fromLocationFinderList`?

Could be an issue with spread operator?

Notes: location in locations object in LocationFinderList are defined as properties of an object not as items in an array.

```<code>{
                2643743: {
                    name: "London",
                    country: "GB"
                },
                4119617: {
                    name: "London",
                    country: "US"
                }
}
</code>```

```<code>import React, { PropTypes } from 'react';
import Location from './Location';

const LocationFinderList = ({ locations, onLocationClick }) => (
    <ul>
        {Object.keys(locations).map((location, index) =>
            <Location
                key={index}
                {...location}
                onClick={() => onLocationClick(location.id)}
            />
        )}
    </ul>
);

export default LocationFinderList;
</code>```

```<code>import React, { PropTypes } from 'react';

const Location = ({ onClick, location }) => (
    <li
        onClick={onClick}
    >
        {location}
    </li>
)

export default Location;
</code>```

答:
Since you are using Object.keys to map over you will get the keys as a result and hence if you want to pass the object you need to pass it like locations[location]

Change you code to

```<code>const LocationFinderList = ({ locations, onLocationClick }) => (
    <ul>
        {Object.keys(locations).map((location, index) =>
            <Location
                key={index}
                {...locations[location]}
                onClick={() => onLocationClick(location)}
            />
        )}
    </ul>
);
</code>```

And

```<code>const Location = ({ onClick, name, country}) => (
    <li
        onClick={onClick}
    >
        {name}
    </li>
)
</code>```

Body:
I am using react, currently I need to display a html list, in LocationFinderList I am initializing Location elements but Location does not get the object and instead I get only numeric property as shown in the pictures.

How to fix my script so Location show the name for an object passe fromLocationFinderList`?

Could be an issue with spread operator?

Notes: location in locations object in LocationFinderList are defined as properties of an object not as items in an array.

{
                2643743: {
                    name: "London",
                    country: "GB"
                },
                4119617: {
                    name: "London",
                    country: "US"
                }
}

import React, { PropTypes } from 'react';
import Location from './Location';

const LocationFinderList = ({ locations, onLocationClick }) => (

        {Object.keys(locations).map((location, index) =>
            <Location
                key={index}
                {...location}
                onClick={() => onLocationClick(location.id)}
            />
        )}

);

export default LocationFinderList;

import React, { PropTypes } from 'react';

const Location = ({ onClick, location }) => (

        {location}

)

export default Location;

Body:
Since you are using Object.keys to map over you will get the keys as a result and hence if you want to pass the object you need to pass it like locations[location]

Change you code to

const LocationFinderList = ({ locations, onLocationClick }) => (
    <ul>
        {Object.keys(locations).map((location, index) =>
            <Location
                key={index}
                {...locations[location]}
                onClick={() => onLocationClick(location)}
            />
        )}
    </ul>
);

And

const Location = ({ onClick, name, country}) => (
    <li
        onClick={onClick}
    >
        {name}
    </li>
)


问:
android fragment top bar difference between devices
I have many fragments in my application Like

and it's worked very well on MarshiMello as above, but in other device there is top bar I don't know how to remove it ...?

答:
Use below code to remove title.</p>

```<code>@Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
 Dialog dialog = super.onCreateDialog(savedInstanceState);

    // request a window without the title
 dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
 return dialog;
}
</code>```

Body:
Use below code to remove title.

@Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
 Dialog dialog = super.onCreateDialog(savedInstanceState);

    // request a window without the title
 dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
 return dialog;
}


问:
Create a new form group inside of the form group in the other component not in the one where the form was initialise in Angular 2
Trying to create a new form group inside of the existing form group in Angular 2. I define the main form in one of the component with the empty formGroup "type". I pass that formGroup "type" to another component. In that component I want to create a new formGroup with name "time", but it doesn't work. I didn't find any method in the FormGroup class for creating a new group. There is just methods for Controls for adding them to the FormGroup.

addControl method works but the next one not.

```<code>this.typeForm.addControl("gender", new FormControl('', Validators.required));
this.typeForm['time'] = this.fb.group({});
</code>```

The FormBuilder should create something like:

```<code>{
  "name": "",
  "type": {
           "gender": "",
           "time": {
                   }
          }
}
</code>```

Any idea how can I do that?

答:
I think you can try to do something like this:</p>

```<code>ngOnInit() {
    this.form = this.fb.group({
            name: [''],
            type: this.typeOptions()
        });
}

typeOptions(): FormGroup {
       return this.someService.getTypes().subscribe(
            res => {
                this.options = res.body;
            let obj: any = {};

            for (let option of options) {
                 let control: FormControl = new FormControl(option.value || '');
                 obj[option.title] = control;
            }

            return  new FormGroup(obj);
        }
    );
 }
</code>```

Body:
Trying to create a new form group inside of the existing form group in Angular 2. I define the main form in one of the component with the empty formGroup "type". I pass that formGroup "type" to another component. In that component I want to create a new formGroup with name "time", but it doesn't work. I didn't find any method in the FormGroup class for creating a new group. There is just methods for Controls for adding them to the FormGroup.

addControl method works but the next one not.

this.typeForm.addControl("gender", new FormControl('', Validators.required));
this.typeForm['time'] = this.fb.group({});

The FormBuilder should create something like:

{
  "name": "",
  "type": {
           "gender": "",
           "time": {
                   }
          }
}

Any idea how can I do that?

Body:
I think you can try to do something like this:

ngOnInit() {
    this.form = this.fb.group({
            name: [''],
            type: this.typeOptions()
        });
}

typeOptions(): FormGroup {
       return this.someService.getTypes().subscribe(
            res => {
                this.options = res.body;
            let obj: any = {};

            for (let option of options) {
                 let control: FormControl = new FormControl(option.value || '');
                 obj[option.title] = control;
            }

            return  new FormGroup(obj);
        }
    );
 }


问:
How to set an icon for an QML Plasmoid
I have a very simple Plasmoid (it consists of only 1 JS file and 1 main.qml file). I've been browsing the internet for almost an eternity, but I can't figure out, how to set an icon the for the plasmoid to use in the KDE panel.</p>

答:
In 5 minutes I found a tutorial and a quick browse of the sources shows that you should add an "Icon" entry in your plasmoid metadata.desktop file.

See the Calculator applet as a simple example:
https://cgit.kde.org/kdeplasma-addons.git/tree/applets/calculator/package/metadata.desktop#n117

That icon should then translate into those SVG icons (per theme) you have in /usr/share/icons

Title: How to set an icon for an QML Plasmoid


问:
Using HttpContext outside of a Controller - Bad practice?
I've been writing some logging services for my ASP.NET Core API.

I wrote a middleware that will log every action being called (cross-cutting concern, seemed logical).

One of the things I wanted to log is the user's IP (for instance).
The only way I could think of getting that data is through HttpContext.Connection.

It worked as expected.

But lately I've been reading some more about it and I understand that accessing HttpContext outside of the controller is considered a bad practice.
It makes the code not testable since it's very hard to mock and imitate.

Also, the code is not portable to other.NET applications and has to live in the context of the ASP.NET application.

So my question is - is it really such a bad practice using HttpContext outside of controllers - inside a middleware for instance?

And if so - what's the alternative?

Or maybe using HttpContext inside of components that will ever be used inside an ASP.NET (such as TOP-level controllers, or middleware) is legit.

Thanks.

答:
It is totally fine to use an instance of an HttpContext class in ASP.NET core outside of an controller. Especially writing a middleware will be useless without an instance of HttpContext that represents the current request.

The main difference is that you should not use a static accessor like HttpContext.Current in the ASP.NET System.Web kind of thinking. Your referenced blog post is about how to mimick this back in ASP.NET Core if much of your existing code relies on this. In ASP.NET Core terms, an instance of the context is passed to your Invoke method of your middleware or you gain access to an IHttpContextAccessor object using dependency injection.

Have a look at this sample in the ASP.NET Core Docs. The HttpContext is injected as a parameter names context, so there is no need to rely on a static accessor like HttpContext.Current. Especially this is easier to test, because you can create an own instance of HttpContext in your unit test and pass it to the Invoke method.

```<code>public class RequestCultureMiddleware
{
    private readonly RequestDelegate _next;

    public RequestCultureMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context)
    {
        var cultureQuery = context.Request.Query["culture"];
        if (!string.IsNullOrWhiteSpace(cultureQuery))
        {
            var culture = new CultureInfo(cultureQuery);

            CultureInfo.CurrentCulture = culture;
            CultureInfo.CurrentUICulture = culture;

        }

        // Call the next delegate/middleware in the pipeline
        return this._next(context);
    }
}
</code>```

Body:
It is totally fine to use an instance of an HttpContext class in ASP.NET core outside of an controller. Especially writing a middleware will be useless without an instance of HttpContext that represents the current request.

The main difference is that you should not use a static accessor like HttpContext.Current in the ASP.NET System.Web kind of thinking. Your referenced blog post is about how to mimick this back in ASP.NET Core if much of your existing code relies on this. In ASP.NET Core terms, an instance of the context is passed to your Invoke method of your middleware or you gain access to an IHttpContextAccessor object using dependency injection.

Have a look at this sample in the ASP.NET Core Docs. The HttpContext is injected as a parameter names context, so there is no need to rely on a static accessor like HttpContext.Current. Especially this is easier to test, because you can create an own instance of HttpContext in your unit test and pass it to the Invoke method.

public class RequestCultureMiddleware
{
    private readonly RequestDelegate _next;

    public RequestCultureMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context)
    {
        var cultureQuery = context.Request.Query["culture"];
        if (!string.IsNullOrWhiteSpace(cultureQuery))
        {
            var culture = new CultureInfo(cultureQuery);

            CultureInfo.CurrentCulture = culture;
            CultureInfo.CurrentUICulture = culture;

        }

        // Call the next delegate/middleware in the pipeline
        return this._next(context);
    }
}


问:
selenium C# Unable to locate element
I am having a trouble with Selenium. I am trying to open Google and search Selenium. Then to open the first page that appear, so I am doing this:

driver.FindElement(By.XPath("//*@id=\"rso\"]/div/div/div[1]/div/h3/a")).Click();

But it doesn't open the first url by XPath. It says: Unable to locate element
Can you help me? Thank you in advance!

答:
Your syntax for the xpath is wrong, after * symbol there should be a square bracket.

Relative xpath: (//div[@id='ires']//div[@class='srg']//h3[@class='r']/a)[1]

Relative xpath is recommended because if html of the page gets change then absolute xpath will fails

Before clicking the element provide Explicit wait.

```<code>  WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
  wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("(//div[@id='ires']//div[@class='srg']//h3[@class='r']/a)[1]"))).Click();
</code>```

Try it and let me know if it works for you.

Title: selenium C# Unable to locate element

Body:
Your syntax for the xpath is wrong, after * symbol there should be a square bracket.

Relative xpath: (//div[@id='ires']//div[@class='srg']//h3[@class='r']/a)[1]

Relative xpath is recommended because if html of the page gets change then absolute xpath will fails

Before clicking the element provide Explicit wait.

  WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
  wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("(//div[@id='ires']//div[@class='srg']//h3[@class='r']/a)[1]"))).Click();

Try it and let me know if it works for you.


问:
no raising error in android 4.4.2
I'm quite a novice in the Android world

and I ran to the next situation

I create this code

```<code>//function
procedure LoadPictureFromResource(const ResName: string; out aImage: TImage);
var
  aResource: TResourceStream;
begin
  aResource := TResourceStream.Create(HInstance, ResName, RT_RCDATA);
  try
    aImage.Bitmap.LoadFromStream(aResource);
  finally
    aResource.DisposeOf;
  end;
end;
....
//call function
  FImage := TImage.Create(Self);
  FImage.Parent := Self;
  FImage.Align := TAlignLayout.Left;
  FImage.Margins.Left := 6;
  FImage.Margins.Top := 3;
  FImage.Margins.Bottom := 3;
  FImage.Margins.Right := 3;
  FImage.Width := 64;
  LoadPictureFromResource(resPicturesError, FImage);
</code>```

obviously with a mistake in the declaration parameter for procedure

used out instead var or const or empty

works with Windows but is still syntax / logic wrong

Android debug mode - Delphi reports an error (the device does not answer anything and operating normally) Segmentation fault (11)

Work mode - Delphi and the device does not report anything

Android does not report anything (error is dangerous) - why?

答:
Resource files are only supported for desktop platforms, please see the details in the docs: http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Resource_Files_Support

If you want to add the file to the mobile project in Delphi, follow the instructions provided in blog: https://community.embarcadero.com/article/articles-tutorials/151-ui/927-deploying-and-accessing-local-files-on-ios-and-android

Please note, that paths for iOS and Android are different - you can enter them in Deployment window, which has separate settings for every platform.

Title: no raising error in android 4.4.2

Body:
I'm quite a novice in the Android world

and I ran to the next situation

I create this code

//function
procedure LoadPictureFromResource(const ResName: string; out aImage: TImage);
var
  aResource: TResourceStream;
begin
  aResource := TResourceStream.Create(HInstance, ResName, RT_RCDATA);
  try
    aImage.Bitmap.LoadFromStream(aResource);
  finally
    aResource.DisposeOf;
  end;
end;
....
//call function
  FImage := TImage.Create(Self);
  FImage.Parent := Self;
  FImage.Align := TAlignLayout.Left;
  FImage.Margins.Left := 6;
  FImage.Margins.Top := 3;
  FImage.Margins.Bottom := 3;
  FImage.Margins.Right := 3;
  FImage.Width := 64;
  LoadPictureFromResource(resPicturesError, FImage);

obviously with a mistake in the declaration parameter for procedure

used out instead var or const or empty

works with Windows but is still syntax / logic wrong

Android debug mode - Delphi reports an error (the device does not answer anything and operating normally) Segmentation fault (11)

Work mode - Delphi and the device does not report anything

Android does not report anything (error is dangerous) - why?


问:
adding URL to map marker in Marker Cluster google map API
So basically what I am trying to do is have a map cluster and once you click into the clusters and click on the individule map markers you will be linked off to a different page on my website.

this is what i have so far. but i cant seem to pull the URLS through.. into different markers.

```<code>   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: {lat: -39.3642, lng: 164.0444318}
    });

    // Add some markers to the map.
    // Note: The code uses the JavaScript Array.prototype.map() method to
    // create an array of markers based on a given "locations" array.
    // The map() method here has nothing to do with the Google Maps API.
    var markers = locations.map(function(location, i) {
      return new google.maps.Marker({
        position: location,
        url: "http://travelpark.co.nz" //Will be different for each marker
      });

    });

    // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
   }

   var locations = [
        {lat: -37.7862985, lng: 175.2773836},
      {lat: -37.8011434, lng: 174.871265}
   ]

   google.maps.event.addListener(markers, 'click', function() {
        window.location.href = this.url;
    });
</code>```

The event listener at the bottom doesnt work.. i cant seem to figure this out. any help would be appreciated

答:
Assign listener to each marker object not to the array. Use your map function itself to avoid 2 for loops:</p>

```<code> var markers = locations.map(function(location, i) {
                   var marker =  new google.maps.Marker({
                                position: location,
                                url: "http://travelpark.co.nz" //Will be different for each marker
                                });
                   google.maps.event.addListener(marker, 'click', function(){
                                window.location.href = this.url;
                               });
                   return marker;
});
</code>```

Body:
So basically what I am trying to do is have a map cluster and once you click into the clusters and click on the individule map markers you will be linked off to a different page on my website.

this is what i have so far. but i cant seem to pull the URLS through.. into different markers.

   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: {lat: -39.3642, lng: 164.0444318}
    });

    // Add some markers to the map.
    // Note: The code uses the JavaScript Array.prototype.map() method to
    // create an array of markers based on a given "locations" array.
    // The map() method here has nothing to do with the Google Maps API.
    var markers = locations.map(function(location, i) {
      return new google.maps.Marker({
        position: location,
        url: "http://travelpark.co.nz" //Will be different for each marker
      });

    });

    // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
   }

   var locations = [
        {lat: -37.7862985, lng: 175.2773836},
      {lat: -37.8011434, lng: 174.871265}
   ]

   google.maps.event.addListener(markers, 'click', function() {
        window.location.href = this.url;
    });

The event listener at the bottom doesnt work.. i cant seem to figure this out. any help would be appreciated

Body:
Assign listener to each marker object not to the array. Use your map function itself to avoid 2 for loops:

 var markers = locations.map(function(location, i) {
                   var marker =  new google.maps.Marker({
                                position: location,
                                url: "http://travelpark.co.nz" //Will be different for each marker
                                });
                   google.maps.event.addListener(marker, 'click', function(){
                                window.location.href = this.url;
                               });
                   return marker;
});


问:
Should I use value() or exists() to filter records in xml for speed
Question #1: one can use value() or exist() method to filter rows. I want to know which one is faster.

Question #2: in SQL, we use IN operator like following :

```<code>select *
from abc
where abcid in (1,2)
</code>```

Similarly can we use IN operator when dealing with XML?

Query #1:

```<code>WITH XMLNAMESPACES (
     'http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription' AS PD,
     'http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain' AS WM)
SELECT
    CatalogDescription.value('(/PD:ProductDescription/@ProductModelName)[1]', 'nvarchar(100)')
FROM
    Production.ProductModel
WHERE
    CatalogDescription.exist('/PD:ProductDescription[@ProductModelName=''Mountain 100''][1]') = 1
</code>```

Query #2:

```<code>WITH XMLNAMESPACES (
     'http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription' AS PD,
     'http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain' AS WM)
SELECT
    CatalogDescription.value('(/PD:ProductDescription/@ProductModelName)[1]', 'nvarchar(100)')
FROM
    Production.ProductModel
WHERE
    CatalogDescription.value('(/PD:ProductDescription/@ProductModelName)[1]', 'nvarchar(100)') = 'Mountain 100'
</code>```

Yours sincerely

答:
(1) The difference could come from your indexes.

A PATH index will boost performance of the exist() predicate on the WHERE clause, whereas a PROPERTY index will boost performance of the value() function.

Read: http://msdn.microsoft.com/en-us/library/bb522562.aspx

(2)The = operator of XPath 1.0 works that way, though XPath 1.0 doesn't provide syntax for writing sequences. So if you have an XML document of the form

```<code><doc>
  <value>1</value>
  <value>2</value>
  <value>3</value>
</doc>
</code>```

then an expression like //doc[value = 2] will return that doc element.

In XPath 2.0, the syntax (1, 2, 3) will create a sequence of three integers, and you can write conditions like $i = (1, 2, 3). But literal sequences are not a feature of XPath 1.0 -- the only way to get multiple values on one side of an XPath expression is to use a path expression that matches multiple nodes.

Body:
Question #1: one can use value() or exist() method to filter rows. I want to know which one is faster.

Question #2: in SQL, we use IN operator like following :

select *
from abc
where abcid in (1,2)

Similarly can we use IN operator when dealing with XML?

Query #1:

WITH XMLNAMESPACES (
     'http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription' AS PD,
     'http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain' AS WM)
SELECT
    CatalogDescription.value('(/PD:ProductDescription/@ProductModelName)[1]', 'nvarchar(100)')
FROM
    Production.ProductModel
WHERE
    CatalogDescription.exist('/PD:ProductDescription[@ProductModelName=''Mountain 100''][1]') = 1

Query #2:

WITH XMLNAMESPACES (
     'http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription' AS PD,
     'http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain' AS WM)
SELECT
    CatalogDescription.value('(/PD:ProductDescription/@ProductModelName)[1]', 'nvarchar(100)')
FROM
    Production.ProductModel
WHERE
    CatalogDescription.value('(/PD:ProductDescription/@ProductModelName)[1]', 'nvarchar(100)') = 'Mountain 100'

Yours sincerely

Body:
(1) The difference could come from your indexes.

A PATH index will boost performance of the exist() predicate on the WHERE clause, whereas a PROPERTY index will boost performance of the value() function.

Read: http://msdn.microsoft.com/en-us/library/bb522562.aspx

(2)The = operator of XPath 1.0 works that way, though XPath 1.0 doesn't provide syntax for writing sequences. So if you have an XML document of the form

<doc>
  <value>1</value>
  <value>2</value>
  <value>3</value>
</doc>

then an expression like //doc[value = 2] will return that doc element.

In XPath 2.0, the syntax (1, 2, 3) will create a sequence of three integers, and you can write conditions like $i = (1, 2, 3). But literal sequences are not a feature of XPath 1.0 -- the only way to get multiple values on one side of an XPath expression is to use a path expression that matches multiple nodes.


问:
Loading system properties for tests
I recently found a solution that allows me to load system properties for my unit tests. It works great if I'm running a test individually, but if I choose to run the whole test suite, it fails. Can someone tell me why?

The first step is to load the test application context:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
</code>```

The next step is to create a class which will load the system properties:

```<code>import java.io.InputStream;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.springframework.core.io.Resource;

public class SystemPropertiesLoader{

    private Resource resource;

    public void setResource(final Resource resource){
        this.resource = resource;
    }

    @PostConstruct
    public void applyProperties() throws Exception{

        final Properties systemProperties = System.getProperties();

        final InputStream inputStream = resource.getInputStream();

        try{
            systemProperties.load(inputStream);
        } finally{
            inputStream.close();
        }
    }
}
</code>```

The final step is to list this as a bean in my test application context:

```<code><bean class="com.foo.SystemPropertiesLoader">
    <property name="resource" value="classpath:localdevelopment_Company.properties" />
</bean>
</code>```

When I run the test suite, several of my tests, all of which rely on system properties, fail. If I go to the specific test and run it, it will pass. I've debugged it and I've verified that the code in SystemPropertiesLoader is being executed, and all other beans are being pulled successfully from the context. However, the properties are not being loaded correctly, as they are all coming up null when I try to access them. Any suggestions?

答:
A few ideas:

If you are unit testing, so why not set the required properties in each individual test case. There is no point using spring to set a global variable.

Why do you use system properties. Spring manages property objects that you can inject into you beans. They can be setup in the appContext.xml and also be initialised there (see: PropertyPlaceHolderConfigurer) using System properties. Having your code access System properties is against the very philosophy of spring.

Setting system properties from a file is rather wrong anyways. Normally you would use System properties to override settings in the properties file.

Title: Loading system properties for tests

Body:
I recently found a solution that allows me to load system properties for my unit tests. It works great if I'm running a test individually, but if I choose to run the whole test suite, it fails. Can someone tell me why?

The first step is to load the test application context:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")

The next step is to create a class which will load the system properties:

import java.io.InputStream;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.springframework.core.io.Resource;

public class SystemPropertiesLoader{

    private Resource resource;

    public void setResource(final Resource resource){
        this.resource = resource;
    }

    @PostConstruct
    public void applyProperties() throws Exception{

        final Properties systemProperties = System.getProperties();

        final InputStream inputStream = resource.getInputStream();

        try{
            systemProperties.load(inputStream);
        } finally{
            inputStream.close();
        }
    }
}

The final step is to list this as a bean in my test application context:

<bean class="com.foo.SystemPropertiesLoader">
    <property name="resource" value="classpath:localdevelopment_Company.properties" />
</bean>

When I run the test suite, several of my tests, all of which rely on system properties, fail. If I go to the specific test and run it, it will pass. I've debugged it and I've verified that the code in SystemPropertiesLoader is being executed, and all other beans are being pulled successfully from the context. However, the properties are not being loaded correctly, as they are all coming up null when I try to access them. Any suggestions?


问:
Precisely IP geolocation
Can I get users latitude and longitude with 6 digits after decimal point from his IP (like 52.229676 and 21.012229)? I've already tried some Geo-IP services but it gave me only 4 digits after decimal point.</p>

答:
IP geolocation provides city level accuracy and not street level. Therefore, there is no reason you want to get 6 decimal compare to existing decimal because the location is usually central of the city.

If you need high precision, you will need to get the coordinates from GPS. However, it required end user permission before you can access this information.

Title: Precisely IP geolocation


问:
textured sprite is all black in three.js
I'm starting on three.js and I'm already stuck on a trivial case : display an image on a sprite. I can only get a black plane following the lines written in the documentation:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8>
        <title>TEST Sprite</title>
        <style>
            body { margin: 0; background-color:#000; }
            canvas { width: 100%; height: 100%; }
            #glRender {
                position:absolute;
                top: 50px;
                left: 200px;
                min-width: 200px;
                width: 50%;
                min-height: 200px;
                z-index: 1;
                height: 50%;
                border: 10px solid #38272C;
            }

        </style>
    </head>
    <body>
        <div id="glRender"></div>
        <script src="http://threejs.org/build/three.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth / 2, window.innerHeight / 2 );

            container = document.getElementById( 'glRender' );
            document.body.appendChild( container );
            container.appendChild( renderer.domElement );

            // A simple cube
            var geometry = new THREE.BoxGeometry( 1, 1, 1 );
            var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
            var cube = new THREE.Mesh( geometry, material );
            scene.add( cube );

            // completely black...
            var photoTexLoad = new THREE.TextureLoader().load( 'http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg' );
            var matPhoto = new THREE.SpriteMaterial( { map: photoTexLoad, color: 0xffffff } );
            var sprite = new THREE.Sprite( matPhoto );
            sprite.scale.set( 2, 2, 2 );
            sprite.position.set( 1, 0, 0.5 );
            scene.add( sprite );

            camera.position.z = 5;

            function render() {
                requestAnimationFrame( render );
                cube.rotation.x += 0.01;
                cube.rotation.y += 0.1;
                renderer.render( scene, camera );
            }

            render();

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

I get the spinning green cube intersecting with a black plane.
What did I miss to have the image displayed on the plane?

答:
.TextureLoader().load() is asynchronous.  Trying to apply it immediately after invoking it leads to a black plane in your code most likely because the texture has not finished loading.

You can solve this by:

Passing a callback to .load as a 2nd parameter.  (It is called once the texture has finished loading):

```<code>var matPhoto,
    sprite,
    texloader = new THREE.TextureLoader();

texloader.load('http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg',
  function(tex) {
  matPhoto = new THREE.SpriteMaterial( { map: tex, color: 0xffffff } );
  sprite = new THREE.Sprite( matPhoto );
  //...etc...
  }
);
</code>```

OR

set an event listener:

```<code>var texloader = new THREE.TextureLoader();

texloader.load('http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg');

textureLoader.addEventListener('load', function(event){

  // event.content holds the texture---------------v
  matPhoto = new THREE.SpriteMaterial( { map: event.content, color: 0xffffff } ); = event.content;

});
</code>```

Body:
I'm starting on three.js and I'm already stuck on a trivial case : display an image on a sprite. I can only get a black plane following the lines written in the documentation:

<!DOCTYPE html>

        <meta charset=utf-8>
        <title>TEST Sprite</title>

I get the spinning green cube intersecting with a black plane.
What did I miss to have the image displayed on the plane?

Body:
.TextureLoader().load() is asynchronous.  Trying to apply it immediately after invoking it leads to a black plane in your code most likely because the texture has not finished loading.

You can solve this by:

Passing a callback to .load as a 2nd parameter.  (It is called once the texture has finished loading):

var matPhoto,
    sprite,
    texloader = new THREE.TextureLoader();

texloader.load('http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg',
  function(tex) {
  matPhoto = new THREE.SpriteMaterial( { map: tex, color: 0xffffff } );
  sprite = new THREE.Sprite( matPhoto );
  //...etc...
  }
);

OR

set an event listener:

var texloader = new THREE.TextureLoader();

texloader.load('http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg');

textureLoader.addEventListener('load', function(event){

  // event.content holds the texture---------------v
  matPhoto = new THREE.SpriteMaterial( { map: event.content, color: 0xffffff } ); = event.content;

});


问:
How do you replace all numbers in a string with a defined character in PHP?

How would you replace all numbers in a string with a pre-defined character?

Replace each individual number with a dash "-".

```<code>$str = "John is 28 years old and donated $40.39!";
</code>```

Desired output:

```<code>"John is -- years old and donated $--.--!"
</code>```

I am assuming preg_replace() will be used but I am not sure how to target just numbers.

答:
PHP code demo

```<code><?php

$str = "John is 28 years old and donated $40.39!";
echo preg_replace("/\d/", "-", $str);
</code>```

OR:

```<code><?php

$str = "John is 28 years old and donated $40.39!";
echo preg_replace("/[0-9]/", "-", $str);
</code>```

Output:
John is -- years old and donated $--.--!

ContentLicense: CC BY-SA 4.0

Body:
How would you replace all numbers in a string with a pre-defined character?

Replace each individual number with a dash "-".

$str = "John is 28 years old and donated $40.39!";

Desired output:

"John is -- years old and donated $--.--!"

I am assuming preg_replace() will be used but I am not sure how to target just numbers.

Body:
PHP code demo

<?php

$str = "John is 28 years old and donated $40.39!";
echo preg_replace("/\d/", "-", $str);

OR:

<?php

$str = "John is 28 years old and donated $40.39!";
echo preg_replace("/[0-9]/", "-", $str);

Output:
John is -- years old and donated $--.--!


问:
Cant redirect output to a file
```<code>tail -f /var/log/kern.log | sed 's/.* //'
</code>```

Gives me the output on the terminal but when i do

```<code> tail -f /var/log/kern.log | sed 's/.* //' >> logfile.txt
</code>```

i cant find anything in the file. From the kernel module i print the names of the executables. For eg if i run ls , kern.log has /bin/ls but with the timestamp etc. So im trying the above to extract only the path and it works as long as i run it without redirecting to an output file, i have also tried tee logfile.txt . Still nothing. Please help.

答:
The problem with your sed command is that you're taking "everything that is followed by a space" (the ".* ") and replacing it with "nothing".  What you need to do is to grab everything up to the first space and save it, then replace everything with the saved bit.  To save part of your input string, you put that part of the regex in parentheses: (.*)  This can then be put into the replacement string using \1.

But there is more to it than that.  sed is greedy -- it will grab as much as it can.  So when you've got a string like "abc def ghi", it will see that "abc def" is followed by a space and grab all of that.  So the question is, how do you get just the first part, up until the first space?

You can select all the characters that are not your delimiter (the space) that are followed by a space.  So in the example above, because the character between c and d is a space, that won't be selected and only the abc part will be.

So what you end up with is this:

```<code>sed "s/\([^ ]*\) .*/\1/"`
</code>```

where the matching pattern consists of "anything that's not a space, as many as there are" (which is in parentheses to save it) "([^ ]\*)", a single space " ", and then anything else ".*".  The replacement string "\1" is "whatever matched the part of the regex in the first set of parentheses".

Here's a quick test I did:

```<code>Testing: cat testout.txt
cat: testout.txt: No such file or directory

Testing: cat testin.txt
abc def ghi
asdf jkl; fdsa ;lkj qwerty 123
Once upon a time
When in the course

Testing: cat testin.txt | sed "s/\([^ ]*\) .*/\1/" >> testout.txt

Testing: cat testout.txt
abc
asdf
Once
When

Testing: cat testin.txt | sed "s/\([^ ]*\) .*/\1/" >> testout.txt

Testing: cat testout.txt
abc
asdf
Once
When
abc
asdf
Once
When

Testing:
</code>```

It starts off with nothing in testout.txt and 4 lines in testin.txt.  Then it sends the contents of testin.txt to sed with the output appending to a file.  Then it shows the contents.  I did it again, then, to show that it's really appending (there are now 8 lines in testout.txt, two sets of 4.)  (Note: I added blank lines just to make it easier to read.)

Please let me know if you have any questions.

Hope this helps!

Title: Cant redirect output to a file

Body:
tail -f /var/log/kern.log | sed 's/.* //'

Gives me the output on the terminal but when i do

 tail -f /var/log/kern.log | sed 's/.* //' >> logfile.txt

i cant find anything in the file. From the kernel module i print the names of the executables. For eg if i run ls , kern.log has /bin/ls but with the timestamp etc. So im trying the above to extract only the path and it works as long as i run it without redirecting to an output file, i have also tried tee logfile.txt . Still nothing. Please help.

Body:
The problem with your sed command is that you're taking "everything that is followed by a space" (the ".* ") and replacing it with "nothing".  What you need to do is to grab everything up to the first space and save it, then replace everything with the saved bit.  To save part of your input string, you put that part of the regex in parentheses: (.*)  This can then be put into the replacement string using \1.

But there is more to it than that.  sed is greedy -- it will grab as much as it can.  So when you've got a string like "abc def ghi", it will see that "abc def" is followed by a space and grab all of that.  So the question is, how do you get just the first part, up until the first space?

You can select all the characters that are not your delimiter (the space) that are followed by a space.  So in the example above, because the character between c and d is a space, that won't be selected and only the abc part will be.

So what you end up with is this:

sed "s/\([^ ]*\) .*/\1/"`

where the matching pattern consists of "anything that's not a space, as many as there are" (which is in parentheses to save it) "([^ ]\*)", a single space " ", and then anything else ".*".  The replacement string "\1" is "whatever matched the part of the regex in the first set of parentheses".

Here's a quick test I did:

Testing: cat testout.txt
cat: testout.txt: No such file or directory

Testing: cat testin.txt
abc def ghi
asdf jkl; fdsa ;lkj qwerty 123
Once upon a time
When in the course

Testing: cat testin.txt | sed "s/\([^ ]*\) .*/\1/" >> testout.txt

Testing: cat testout.txt
abc
asdf
Once
When

Testing: cat testin.txt | sed "s/\([^ ]*\) .*/\1/" >> testout.txt

Testing: cat testout.txt
abc
asdf
Once
When
abc
asdf
Once
When

Testing:

It starts off with nothing in testout.txt and 4 lines in testin.txt.  Then it sends the contents of testin.txt to sed with the output appending to a file.  Then it shows the contents.  I did it again, then, to show that it's really appending (there are now 8 lines in testout.txt, two sets of 4.)  (Note: I added blank lines just to make it easier to read.)

Please let me know if you have any questions.

Hope this helps!


问:
Achieve error differentiation in Promises

Background

I have a REST API using MongoDB, Node.js and Express that makes a request to my NoSQL DB and depending on different results, I want to differentiate which error I send the customer.

Problem

The current version of my code has a generic error handler and always sends the same error message to the client:

```<code>api.post("/Surveys/", (req, res) => {
        const surveyJSON = req.body;
        const sender = replyFactory(res);

        Survey.findOne({_id: surveyJSON.id})
            .then(doc => {
                if(doc !== null)
                    throw {reason: "ObjectRepeated"};

                //do stuff
                return new Survey(surveyJSON).save();
            })
            .then(() => sender.replySuccess("Object saved with success!"))
            .catch(error => {
                /*
                 * Here I don't know if:
                 * 1. The object is repeated
                 * 2. There was an error while saving (eg. validation failed)
                 * 3. Server had a hiccup (500)
                 */
                sender.replyBadRequest(error);
            });
    });
</code>```

This is a problem, because the client will always get the same error message, no matter what and I need error differentiation!

Research

I found a possible solution, based on the division of logic and error/response handling:

Handling multiple catches in promise chain

However, I don't understand a few things:

I don't see how, at least in my example, I can separate the logic from the response. The response will depend on the logic after all!

I would like to avoid error sub-classing and hierarchy. First because I don't use bluebird, and I can't subclass the error class the answer suggests, and second because I don't want my code with a billion different error classes with brittle hierarchies that will change in the future.

My idea, that I don't really like either

With this structure, if I want error differentiation, the only thing I can do is to detect an error occurred, build an object with that information and then throw it:

```<code>.then(doc => {
    if(doc === null)
        throw {reason: "ObjectNotFound"};

    //do stuff
    return doc.save();
})
.catch(error => {
    if(error.reason === "ObjectNotFound")
        sendJsonResponse(res, 404, err);
    else if(error.reason === "Something else ")
        sendJsonResponse(/*you get the idea*/);
    else //if we don't know the reasons, its because the server likely crashed
        sendJsonResponse(res, 500, err);
});
</code>```

I personally don't find this solution particularly attractive because it means I will have a huge if then else chain of statements in my catch block.

Also, as mentioned in the previous post, generic error handlers are usually frowned upon (and for a good reason imo).

Questions

How can I improve this code?

答:
Objectives

When I started this thread, I had two objectives in mind:

Having error differentiation

Avoid an if then else of doom in a generic catcher

I have now come up with two radically distinct solutions, which I now post here, for future reference.

Solution 1: Generic error handler with Errors Object

This solution is based on the solution from @Marc Rohloff, however, instead of having an array of functions and looping through each one, I have an object with all the errors.

This approach is better because it is faster, and removes the need for the if validation, meaning you actually do less logic:

```<code>const errorHandlers = {
    ObjectRepeated: function(error){
        return { code: 400, error };
    },
    SomethingElse: function(error){
        return { code: 499, error };
    }
};

Survey.findOne({
        _id: "bananasId"
    })
    .then(doc => {

        //we dont want to add this object if we already have it
        if (doc !== null)
            throw { reason: "ObjectRepeated", error:"Object could not be inserted because it already exists."};

        //saving empty object for demonstration purposes
        return new Survey({}).save();
    })
    .then(() => console.log("Object saved with success!"))
    .catch(error => {
        respondToError(error);
    });

    const respondToError = error => {
        const errorObj = errorHandlers[error.reason](error);

        if (errorObj !== undefined)
            console.log(`Failed with ${errorObj.code} and reason ${error.reason}: ${JSON.stringify(errorObj)}`);
        else
            //send default error Obj, server 500
            console.log(`Generic fail message ${JSON.stringify(error)}`);
    };
</code>```

This solution achieves:

Partial error differentiation (I will explain why)

Avoids an if then else of doom.

This solution only has partial error differentiation. The reason for this is because you can only differentiate errors that you specifically build, via the throw {reaon: "reasonHere", error: "errorHere"} mechanism.

In this example, you would be able to know if the document already exists, but if there is an error saving the said document (lets say, a validation one) then it would be treated as "Generic" error and thrown as a 500.

To achieve full error differentiation with this, you would have to use the  nested Promise anti pattern like the following:

```<code>.then(doc => {

    //we dont want to add this object if we already have it
    if (doc !== null)
        throw { reason: "ObjectRepeated", error:"Object could not be inserted because it already exists." };

    //saving empty object for demonstration purposes
    return new Survey({}).save()
        .then(() => {console.log("great success!");})
        .catch(error => {throw {reason: "SomethingElse", error}});
})
</code>```

It would work... But I see it as a best practice to avoid anti-patterns.

Solution 2: Using ECMA6 Generators via co.

This solution uses Generators via the library co. Meant to replace Promises in near future with a syntax similar to async/await this new feature allows you to write asynchronous code that reads like synchronous (well, almost).

To use it, you first need to install co, or something similar like ogen. I pretty much prefer co, so that is what i will be using here instead.

```<code>const requestHandler = function*() {

    const survey = yield Survey.findOne({
        _id: "bananasId"
    });

    if (survey !== null) {
        console.log("use HTTP PUT instead!");
        return;
    }

    try {
        //saving empty object for demonstration purposes
        yield(new Survey({}).save());
        console.log("Saved Successfully !");
        return;
    }
    catch (error) {
        console.log(`Failed to save with error:  ${error}`);
        return;
    }

};

co(requestHandler)
    .then(() => {
        console.log("finished!");
    })
    .catch(console.log);
</code>```

The generator function requestHandler will yield all Promises to the library, which will resolve them and either return or throw accordingly.

Using this strategy, you effectively code like you were coding synchronous code (except for the use of yield).

I personally prefer this strategy because:

Your code is easy to read and it looks synchronous (while still have the advantages of asynchronous code).

You do not have to build and throw error objects every where, you can simply send the message immediately.

And, you can BREAK the code flow via return. This is not possible in a promise chain, as in those you have to force a throw (many times a meaningless one) and catch it to stop executing.

The generator function will only be executed once passed into the library co, which then returns a Promise, stating if the execution was successful or not.

This solution achieves:

error differentiation

avoids if then else hell and generalized catchers (although you will use try/catch in your code, and you still have access to a generalized catcher if you need one).

Using generators is, in my opinion, more flexible and makes for easier to read code. Not all cases are cases for generator usage (like mpj suggests in the video) but in this specific case, I believe it to be the best option.

Conclusion

Solution 1: good classical approach to the problem, but has issues inherent to promise chaining. You can overcome some of them by nesting promises, but that is an anti pattern and defeats their purpose.

Solution 2: more versatile, but requires a library and knowledge on how generators work. Furthermore, different libraries will have different behaviors, so you should be aware of that.

Body:
Background

I have a REST API using MongoDB, Node.js and Express that makes a request to my NoSQL DB and depending on different results, I want to differentiate which error I send the customer.

Problem

The current version of my code has a generic error handler and always sends the same error message to the client:

api.post("/Surveys/", (req, res) => {
        const surveyJSON = req.body;
        const sender = replyFactory(res);

        Survey.findOne({_id: surveyJSON.id})
            .then(doc => {
                if(doc !== null)
                    throw {reason: "ObjectRepeated"};

                //do stuff
                return new Survey(surveyJSON).save();
            })
            .then(() => sender.replySuccess("Object saved with success!"))
            .catch(error => {
                /*
                 * Here I don't know if:
                 * 1. The object is repeated
                 * 2. There was an error while saving (eg. validation failed)
                 * 3. Server had a hiccup (500)
                 */
                sender.replyBadRequest(error);
            });
    });

This is a problem, because the client will always get the same error message, no matter what and I need error differentiation!

Research

I found a possible solution, based on the division of logic and error/response handling:

Handling multiple catches in promise chain

However, I don't understand a few things:

I don't see how, at least in my example, I can separate the logic from the response. The response will depend on the logic after all!

I would like to avoid error sub-classing and hierarchy. First because I don't use bluebird, and I can't subclass the error class the answer suggests, and second because I don't want my code with a billion different error classes with brittle hierarchies that will change in the future.

My idea, that I don't really like either

With this structure, if I want error differentiation, the only thing I can do is to detect an error occurred, build an object with that information and then throw it:

.then(doc => {
    if(doc === null)
        throw {reason: "ObjectNotFound"};

    //do stuff
    return doc.save();
})
.catch(error => {
    if(error.reason === "ObjectNotFound")
        sendJsonResponse(res, 404, err);
    else if(error.reason === "Something else ")
        sendJsonResponse(/*you get the idea*/);
    else //if we don't know the reasons, its because the server likely crashed
        sendJsonResponse(res, 500, err);
});

I personally don't find this solution particularly attractive because it means I will have a huge if then else chain of statements in my catch block.

Also, as mentioned in the previous post, generic error handlers are usually frowned upon (and for a good reason imo).

Questions

How can I improve this code?

Body:
Objectives

When I started this thread, I had two objectives in mind:

Having error differentiation

Avoid an if then else of doom in a generic catcher

I have now come up with two radically distinct solutions, which I now post here, for future reference.

Solution 1: Generic error handler with Errors Object

This solution is based on the solution from @Marc Rohloff, however, instead of having an array of functions and looping through each one, I have an object with all the errors.

This approach is better because it is faster, and removes the need for the if validation, meaning you actually do less logic:

const errorHandlers = {
    ObjectRepeated: function(error){
        return { code: 400, error };
    },
    SomethingElse: function(error){
        return { code: 499, error };
    }
};

Survey.findOne({
        _id: "bananasId"
    })
    .then(doc => {

        //we dont want to add this object if we already have it
        if (doc !== null)
            throw { reason: "ObjectRepeated", error:"Object could not be inserted because it already exists."};

        //saving empty object for demonstration purposes
        return new Survey({}).save();
    })
    .then(() => console.log("Object saved with success!"))
    .catch(error => {
        respondToError(error);
    });

    const respondToError = error => {
        const errorObj = errorHandlers[error.reason](error);

        if (errorObj !== undefined)
            console.log(`Failed with ${errorObj.code} and reason ${error.reason}: ${JSON.stringify(errorObj)}`);
        else
            //send default error Obj, server 500
            console.log(`Generic fail message ${JSON.stringify(error)}`);
    };

This solution achieves:

Partial error differentiation (I will explain why)

Avoids an if then else of doom.

This solution only has partial error differentiation. The reason for this is because you can only differentiate errors that you specifically build, via the throw {reaon: "reasonHere", error: "errorHere"} mechanism.

In this example, you would be able to know if the document already exists, but if there is an error saving the said document (lets say, a validation one) then it would be treated as "Generic" error and thrown as a 500.

To achieve full error differentiation with this, you would have to use the  nested Promise anti pattern like the following:

.then(doc => {

    //we dont want to add this object if we already have it
    if (doc !== null)
        throw { reason: "ObjectRepeated", error:"Object could not be inserted because it already exists." };

    //saving empty object for demonstration purposes
    return new Survey({}).save()
        .then(() => {console.log("great success!");})
        .catch(error => {throw {reason: "SomethingElse", error}});
})

It would work... But I see it as a best practice to avoid anti-patterns.

Solution 2: Using ECMA6 Generators via co.

This solution uses Generators via the library co. Meant to replace Promises in near future with a syntax similar to async/await this new feature allows you to write asynchronous code that reads like synchronous (well, almost).

To use it, you first need to install co, or something similar like ogen. I pretty much prefer co, so that is what i will be using here instead.

const requestHandler = function*() {

    const survey = yield Survey.findOne({
        _id: "bananasId"
    });

    if (survey !== null) {
        console.log("use HTTP PUT instead!");
        return;
    }

    try {
        //saving empty object for demonstration purposes
        yield(new Survey({}).save());
        console.log("Saved Successfully !");
        return;
    }
    catch (error) {
        console.log(`Failed to save with error:  ${error}`);
        return;
    }

};

co(requestHandler)
    .then(() => {
        console.log("finished!");
    })
    .catch(console.log);

The generator function requestHandler will yield all Promises to the library, which will resolve them and either return or throw accordingly.

Using this strategy, you effectively code like you were coding synchronous code (except for the use of yield).

I personally prefer this strategy because:

Your code is easy to read and it looks synchronous (while still have the advantages of asynchronous code).

You do not have to build and throw error objects every where, you can simply send the message immediately.

And, you can BREAK the code flow via return. This is not possible in a promise chain, as in those you have to force a throw (many times a meaningless one) and catch it to stop executing.

The generator function will only be executed once passed into the library co, which then returns a Promise, stating if the execution was successful or not.

This solution achieves:

error differentiation

avoids if then else hell and generalized catchers (although you will use try/catch in your code, and you still have access to a generalized catcher if you need one).

Using generators is, in my opinion, more flexible and makes for easier to read code. Not all cases are cases for generator usage (like mpj suggests in the video) but in this specific case, I believe it to be the best option.

Conclusion

Solution 1: good classical approach to the problem, but has issues inherent to promise chaining. You can overcome some of them by nesting promises, but that is an anti pattern and defeats their purpose.

Solution 2: more versatile, but requires a library and knowledge on how generators work. Furthermore, different libraries will have different behaviors, so you should be aware of that.


答:
Change
    {...locations}

to
    {...locations[location]}

Title: Issue with passing object to child react componenet

Body:
I am using react, currently I need to display a html list, in LocationFinderList I am initializing Location elements but Location does not get the object and instead I get only numeric property as shown in the pictures.

How to fix my script so Location show the name for an object passe fromLocationFinderList`?

Could be an issue with spread operator?

Notes: location in locations object in LocationFinderList are defined as properties of an object not as items in an array.

{
                2643743: {
                    name: "London",
                    country: "GB"
                },
                4119617: {
                    name: "London",
                    country: "US"
                }
}

import React, { PropTypes } from 'react';
import Location from './Location';

const LocationFinderList = ({ locations, onLocationClick }) => (

        {Object.keys(locations).map((location, index) =>
            <Location
                key={index}
                {...location}
                onClick={() => onLocationClick(location.id)}
            />
        )}

);

export default LocationFinderList;

import React, { PropTypes } from 'react';

const Location = ({ onClick, location }) => (

        {location}

)

export default Location;


问:
Gradle stock on build ***** gradle project info
enter image description here

I have buy new macbook and I download android studio when I start new project its stock in build ..... Gradle project info
android studio last version 2.3

I try gradle work offline in setting and the same

OS X 10.9.5

java 1.8 (121)

android studio only show Building My Application Gradle project info

Thank you

答:
According to this you may just be experiencing a slow network connection. WHen a project is created for the first time there is a lot to be downloaded, and it can take a while on slow connections.

ACcording to this you may be using the wrong version of android studio. If you navigate to the folder where you have Android Studio's files, look for "studio.exe" and "studio64.exe". First though, close the current open Android Studio window. Start by selecting "studio64" and opening it. Create a new project and see if it gets stuck. If it gets stuck,  try with "studio.exe" and create the project again. If it gets stuck agian, try a different solution.

And according to this you could try pressing "cancel" and finding your build.gradle on project-level. IN there you will find something like this:

```<code>buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}
</code>```

Replace 2.3.0 with an earlier version, e.g. 2.0.0. Then press (in the menu bar at the top) build>make project. Gradle will start to build should in theory finish.

If none of these work, leave a comment so I know and can look for other alternatives to these

Body:
According to this you may just be experiencing a slow network connection. WHen a project is created for the first time there is a lot to be downloaded, and it can take a while on slow connections.

ACcording to this you may be using the wrong version of android studio. If you navigate to the folder where you have Android Studio's files, look for "studio.exe" and "studio64.exe". First though, close the current open Android Studio window. Start by selecting "studio64" and opening it. Create a new project and see if it gets stuck. If it gets stuck,  try with "studio.exe" and create the project again. If it gets stuck agian, try a different solution.

And according to this you could try pressing "cancel" and finding your build.gradle on project-level. IN there you will find something like this:

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

Replace 2.3.0 with an earlier version, e.g. 2.0.0. Then press (in the menu bar at the top) build>make project. Gradle will start to build should in theory finish.

If none of these work, leave a comment so I know and can look for other alternatives to these


问:
How to play video on image?
I have following Image :

Now I want to place a vimeo video on this image with responsive view :

To do that I am using following css and html code :

html code :

```<code><div class="vimeo">
<article>
    <figure>
        <iframe src="https://player.vimeo.com/video/211148482?autoplay=1&title=0&byline=0&portrait=0" width="568" height="453" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
    </figure>
</article>
</div>
</code>```

CSS code :

```<code>.vimeo {
    font: 16px/1.4 Georgia, Serif;
    width: 45%;
    margin: 1px auto;
    background: url(images/bg.jpg);
    background-size: contain;
    background-repeat: no-repeat;
    position: relative;
}

pre, article style, article script {
    white-space: pre;
    display: block;
    overflow-x: auto;

}

img {
    max-width: 100%;
}
figure {
    display: block;
}
figcaption {
    display: block; text-align: center; orphans: 2;
}
</code>```

Now it looks like this image :

I want to set it on the image gray background, How can I do this ?

答:
Check the code, need some fine-tuning though.

$(function() {

    var $allVideos = $("iframe[src^='//player.vimeo.com'], iframe[src^='//www.youtube.com'], object, embed"),
    $fluidEl = $("figure");

 $allVideos.each(function() {

   $(this)
     // jQuery .data does not work on object/embed elements
     .attr('data-aspectRatio', this.height / this.width)
     .removeAttr('height')
     .removeAttr('width');

 });

 $(window).resize(function() {

   var newWidth = $fluidEl.width();
   $allVideos.each(function() {

     var $el = $(this);
     $el
         .width(newWidth)
         .height(newWidth * $el.attr('data-aspectRatio'));

   });

 }).resize();

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>figure {
    display: block;
    background: url(https://i.stack.imgur.com/JQiLu.jpg);
    background-size: contain;
    background-repeat: no-repeat;
    padding: 7%;
}

figcaption {
  position: relative;
  top: 50px;
}</code>```

Caption

```

Kudos to
https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php

Title: How to play video on image?

Body:
I have following Image :

Now I want to place a vimeo video on this image with responsive view :

To do that I am using following css and html code :

html code :

CSS code :

.vimeo {
    font: 16px/1.4 Georgia, Serif;
    width: 45%;
    margin: 1px auto;
    background: url(images/bg.jpg);
    background-size: contain;
    background-repeat: no-repeat;
    position: relative;
}

pre, article style, article script {
    white-space: pre;
    display: block;
    overflow-x: auto;

}

img {
    max-width: 100%;
}
figure {
    display: block;
}
figcaption {
    display: block; text-align: center; orphans: 2;
}

Now it looks like this image :

I want to set it on the image gray background, How can I do this ?

Body:
Check the code, need some fine-tuning though.

$(function() {

    var $allVideos = $("iframe[src^='//player.vimeo.com'], iframe[src^='//www.youtube.com'], object, embed"),
    $fluidEl = $("figure");

 $allVideos.each(function() {

   $(this)
     // jQuery .data does not work on object/embed elements
     .attr('data-aspectRatio', this.height / this.width)
     .removeAttr('height')
     .removeAttr('width');

 });

 $(window).resize(function() {

   var newWidth = $fluidEl.width();
   $allVideos.each(function() {

     var $el = $(this);
     $el
         .width(newWidth)
         .height(newWidth * $el.attr('data-aspectRatio'));

   });

 }).resize();

});

figure {
    display: block;
    background: url(https://i.stack.imgur.com/JQiLu.jpg);
    background-size: contain;
    background-repeat: no-repeat;
    padding: 7%;
}

figcaption {
  position: relative;
  top: 50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<figure>
  <iframe src="//player.vimeo.com/video/211148482?autoplay=0&title=0&byline=0&portrait=0" width="400" height="225" frameborder="0"></iframe>
  <figcaption>Caption</figcaption>
 </figure>

Kudos to
https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php


问:
Why does NGINX reverse proxy $.ajax post give "net::ERR_CONNECTION_REFUSED"
I get "net::ERR_CONNECTION_REFUSED" when waiting for xhr response.
I have tried using the api directy and it works fine. I recieve my responses. Also when using it through nginx reverse proxy my api actually recieves the POST, but jquery doesn't get anything back. Like I said, it does when using http://ip:port..

My nginx config lookes like this:

```<code>upstream daffy {
    server 127.0.0.1:4747;
}

server {
    listen 80;
    server_name daffy;

    access_log  /var/log/nginx/daffy.access.log;
    error_log   /var/log/nginx/daffy.error.log;

    location /socket.io {
        proxy_pass http://daffy/socket.io;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }

    location /git/pull/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_redirect off;
        proxy_set_header    X-Forwarded-Proto https;
        proxy_set_header Host $http_host;
        proxy_pass http://daffy;
    }

    location / {
        allow   192.168.7.0/24;
        deny    all;

        proxy_pass http://daffy;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header Host $http_host;
        proxy_redirect off;
    }
}
</code>```

Nginx shows no errors in error log.. but access log does not register the POST request at all.

nginx-1.11.12-1.el7.ngx.x86_64

does anyone have a suggestion?

UPDATE
I have tried disabling firewall and turned on debug in my error log.

Nginx doesn't really provide anything in error log with debug on.

But GET is working just fine:

```<code>192.168.7.114 - - [02/Apr/2017:09:54:02 +0200] "GET /users/?_=1491119642698 HTTP/1.1" 200 570 "http://daffy/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
</code>```

SELinux is disabled.

答:
SOLVED!!

I had to change my python backend to return a bit faster than 2 seconds:

```<code>Popen(["/path/to/awesome.sh"], stdin=None,stdout=None,stderr=None)
</code>```

Before I was using subprocess.check_call or subprocess.call

Anyway, I cut of 2 seconds of the return from api :)

Body:
I get "net::ERR_CONNECTION_REFUSED" when waiting for xhr response.
I have tried using the api directy and it works fine. I recieve my responses. Also when using it through nginx reverse proxy my api actually recieves the POST, but jquery doesn't get anything back. Like I said, it does when using http://ip:port..

My nginx config lookes like this:

upstream daffy {
    server 127.0.0.1:4747;
}

server {
    listen 80;
    server_name daffy;

    access_log  /var/log/nginx/daffy.access.log;
    error_log   /var/log/nginx/daffy.error.log;

    location /socket.io {
        proxy_pass http://daffy/socket.io;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }

    location /git/pull/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_redirect off;
        proxy_set_header    X-Forwarded-Proto https;
        proxy_set_header Host $http_host;
        proxy_pass http://daffy;
    }

    location / {
        allow   192.168.7.0/24;
        deny    all;

        proxy_pass http://daffy;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header Host $http_host;
        proxy_redirect off;
    }
}

Nginx shows no errors in error log.. but access log does not register the POST request at all.

nginx-1.11.12-1.el7.ngx.x86_64

does anyone have a suggestion?

UPDATE
I have tried disabling firewall and turned on debug in my error log.

Nginx doesn't really provide anything in error log with debug on.

But GET is working just fine:

192.168.7.114 - - [02/Apr/2017:09:54:02 +0200] "GET /users/?_=1491119642698 HTTP/1.1" 200 570 "http://daffy/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"

SELinux is disabled.

Body:
SOLVED!!

I had to change my python backend to return a bit faster than 2 seconds:

Popen(["/path/to/awesome.sh"], stdin=None,stdout=None,stderr=None)

Before I was using subprocess.check_call or subprocess.call

Anyway, I cut of 2 seconds of the return from api :)


答:
You can also do this with a normal replace:

```<code>$input   = "John is 28 years old and donated $40.39!";
$numbers = str_split('1234567890');
$output  = str_replace($numbers,'-',$input);
echo $output;
</code>```

just in case you were wondering. Code was tested and it works. The output is:

John is -- years old and donated $--.--!

No need for 'obscure' regular expressions. Do you remember where the slashes and braces go and why?

Title: How do you replace all numbers in a string with a defined character in PHP?

Body:
You can also do this with a normal replace:

$input   = "John is 28 years old and donated $40.39!";
$numbers = str_split('1234567890');
$output  = str_replace($numbers,'-',$input);
echo $output;

just in case you were wondering. Code was tested and it works. The output is:

John is -- years old and donated $--.--!

No need for 'obscure' regular expressions. Do you remember where the slashes and braces go and why?


问:
Use AWS Lambda to access S3 using only Roles
I have a Lambda function written in Java I and I want it to access S3 (putObject).

I do not want to use or store credentials in my Lambda function in order to access S3. Instead, I would like to use IAM roles.

How can I code an AWS S3 client inside my java code (that would be ran by Lambda) that won't need any credentials and assume that the Lambda has the appropriate Role?

答:
You don't need to store credentials in your lambda functions. All funtions run with a role - the role you set when you created the function. Since the lambda function has a role, you can add or remove permissions from this role as needed, without changing the function itself

Manage Permissions: Using an IAM Role (Execution Role)

Each Lambda function has an IAM role (execution role) associated with
  it. You specify the IAM role when you create your Lambda function.
  Permissions you grant to this role determine what AWS Lambda can do
  when it assumes the role. There are two types of permissions that you
  grant to the IAM role:

If your Lambda function code accesses other AWS resources, such as to
  read an object from an S3 bucket or write logs to CloudWatch Logs, you
  need to grant permissions for relevant Amazon S3 and CloudWatch
  actions to the role.   If the event source is stream-based (Amazon
  Kinesis Streams and DynamoDB streams), AWS Lambda polls these streams
  on your behalf. AWS Lambda needs permissions to poll the stream and
  read new records on the stream so you need to grant the relevant
  permissions to this role.

http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html


问:
Difference between EA and RUP 4+1?
What is the difference between Enterprise architecture and RUP (Rational Unified Process) 4+1 view on arcitecture?

Is it similar alternative to EA or its the same?

IMHO EA = business + information + technology + applications

while the 4+1 RUP architecture is connected only to the IT of an company, not needed to solve IT Governance etc.
What do you think?

答:
EA has some frameworks for describing some levels of organisations. These levels are strategies, business process, IT services and technologies for that services. EA frameworks have activities and artifacts for representing these levels. In fact, after applying EA, we have some descriptions of "services" or "application" for supporting business processes of organizations. Now for implementing each service or application, we use "RUP 4+1 view" for representing the "architecture" of that system.
In fact, this concepts can link to each other for implementing the service of the organization.</p>

Title: Difference between EA and RUP 4+1?


问:
Will F# perform well when writing math functions for a C# program?
Does anyone know how well F# measures with regards to performance, compared to C#. I have a C# raytracer with a lot of vector manipulations, ray-collission algorithms etc. and thought they might be more easily expressed in F#. I'm not asking for how well F# is at expressing math problems, something which has been answered here, but rather if I should expect better or worse performance? As raytracing is very performance intensive, even small cases of poor performance can be a problem in the wrong places.

Edit:

It seems that there are already a lot of questions on the subject that I couldn't find (there are no results if you actually search for anything with the term 'F#'). One good point here was the following answer:

F# provides some performance-related
  features that can make a difference.

Firstly, the implementation of
  delegates on .NET is currently quite
  inefficient and, consequently, F# uses
  its own FastFunc type for
  high-performance first-class
  functions.

Secondly, F# uses .NET metadata to
  convey inline functions so that they
  can be exported across APIs and, of
  course, that can dramatically improve
  performance in certain circumstances.

Finally, pattern matching can be
  extremely laborious to express in C#
  because the language lacks pattern
  matching but it is almost impossible
  to maintain optimized C# code
  equivalent to many non-trivial pattern
  matches. In contrast, the F# compiler
  aggressively optimizes pattern matches
  during compilation.

Conversely, the C# compiler is better
  at optimizing loops using IEnumerables
  and is better at optimizing
  computations over value types (e.g.
  complex arithmetic).

Cheers, Jon Harrop.

答:
Maybe you already know, but maybe not.

Google on the name "Luke Hoban", he has made a ray tracer with C# 3.0 and now works in Microsofts F# team.

See also: http://blogs.msdn.com/lukeh/ and http://blogs.msdn.com/lukeh/archive/2007/04/03/a-ray-tracer-in-c-3-0.aspx .

He should know.

OwnerDisplayName: Morten Christiansen

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: tuinstoel