问:
groups of routes with react-router-4
My react app has 3 entry points with overlapping routes, and it is getting hard to maintain. 2 of the apps are basically just stuck in a couple places on the legacy site, until the main app has enough functionality to fully replace the main site.

I am using React router 4, and have a routes.tsx file with all my routes. But I would like to group the routes by function, and then have the routes component for each app just take what it needs.

Currently my routes look like this:

```<code>const MainAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            <Route path='/customers' component={CustomersDisplayPage} />
            <Route path='/customers/:id' component={CustomersDisplayPage} />
            <Route path='/cars' component={CarDisplayPage} />
            <Route path='/cars/:id' component={CarDisplayPage} />
        </Switch>
    );
};
</code>```

But I would like it to look like this:

```<code>const MainAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            <CustomerAppRoutes />
            <CarAppRoutes />
        </Switch>
    );

const CustomerAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route path='/customers' component={CustomersDisplayPage} />
            <Route path='/customers/:id' component={CustomersDisplayPage} />
        </Switch>
    );
};

const CarAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route path='/cars' component={CarDisplayPage} />
            <Route path='/cars/:id' component={CarDisplayPage} />
        </Switch>
    );
};
</code>```

But this causes Caroutes not to route properly. I have tried using Div's instead, and that does not work either.

答:
You could barrel it in separate files and then map them in the main file

CustomerRoutes.js

```<code>import ...
export default [
    { path: '/customers', component: CustomersDisplayPage },
    { path: '/customers/:id', component: CustomersDisplayPage }
]
</code>```

CarAppRoutes.js

```<code>import ...
export default [
    { path: '/cars', component: CarDisplayPage },
    { path: '/cars/:id', component: CarDisplayPage }
]
</code>```

MainRoutes.js

```<code>import ...
import CarAppRoutes from 'wherever';
import CustomerRoutes from 'wherever';

...
<Switch>
    <Route exact path='/' component={HomePage} />
    { CustomerRoutes.map(props => <Route {...props} />) }
    { CarAppRoutes.map(props => <Route {...props} />) }
</Switch>
</code>```

Title: groups of routes with react-router-4

Body:
My react app has 3 entry points with overlapping routes, and it is getting hard to maintain. 2 of the apps are basically just stuck in a couple places on the legacy site, until the main app has enough functionality to fully replace the main site.

I am using React router 4, and have a routes.tsx file with all my routes. But I would like to group the routes by function, and then have the routes component for each app just take what it needs.

Currently my routes look like this:

const MainAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            <Route path='/customers' component={CustomersDisplayPage} />
            <Route path='/customers/:id' component={CustomersDisplayPage} />
            <Route path='/cars' component={CarDisplayPage} />
            <Route path='/cars/:id' component={CarDisplayPage} />
        </Switch>
    );
};

But I would like it to look like this:

const MainAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            <CustomerAppRoutes />
            <CarAppRoutes />
        </Switch>
    );

const CustomerAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route path='/customers' component={CustomersDisplayPage} />
            <Route path='/customers/:id' component={CustomersDisplayPage} />
        </Switch>
    );
};

const CarAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route path='/cars' component={CarDisplayPage} />
            <Route path='/cars/:id' component={CarDisplayPage} />
        </Switch>
    );
};

But this causes Caroutes not to route properly. I have tried using Div's instead, and that does not work either.

Body:
You could barrel it in separate files and then map them in the main file

CustomerRoutes.js

import ...
export default [
    { path: '/customers', component: CustomersDisplayPage },
    { path: '/customers/:id', component: CustomersDisplayPage }
]

CarAppRoutes.js

import ...
export default [
    { path: '/cars', component: CarDisplayPage },
    { path: '/cars/:id', component: CarDisplayPage }
]

MainRoutes.js

import ...
import CarAppRoutes from 'wherever';
import CustomerRoutes from 'wherever';

...
<Switch>
    <Route exact path='/' component={HomePage} />
    { CustomerRoutes.map(props => <Route {...props} />) }
    { CarAppRoutes.map(props => <Route {...props} />) }
</Switch>


来源: stackexchange

问:
Inheriting from a template class using the inheriting class
When I inherit from a class the compiler has to know the definition of the base class in order to create it. But when I inherit from a template class using oneself (the inheriting class), how can the compiler create the code? It does not know the size of the class yet.

```<code>#include <iostream>

template <class T> class IFoo
{
public:
     virtual T addX(T foo, double val) = 0;
     // T memberVar; // uncomment for error
};

class Foo : public IFoo<Foo>
{
public:
    Foo(double value)
        : m_value(value) {}

    Foo addX(Foo foo, double b) override
    {
        return Foo(foo.m_value + b);
    }

    double m_value;
};

int main()
{
    Foo foo1(1);
    Foo foo2 = foo1.addX(foo1, 1);

    std::cout << foo2.m_value;
}
</code>```

First I thought it works because it's an interface but it also works with a regular class.

When I store the template as a member i get an error that Foo is undefined, just as I expected.

答:
how can the compiler create the code?

Answering this question would be the same as answering this question: How can the compiler compile that?

```<code>struct Type;
Type func(Type);
</code>```

Live example

How can you define a type that doesn't exist and yet declare a function that use that type?

The answer is simple: There is no code to compile with that actually use that non-existing type. Since there is no code to compile, how can it even fail?

Now maybe you're wondering what is has to do with your code? How does it make that a class can send itself as template parameter to it's parent?

Let's analyze what the compiler see when you're doing that:

```<code>struct Foo : IFoo<Foo> { /* ... */ };
</code>```

First, the compile sees this:

```<code>struct Foo ...
</code>```

The compiler now knows that Foo exists, yet it's an incomplete type.

Now, he sees that:

```<code>... : IFoo<Foo> ...
</code>```

It knows what IFoo is, and it knows that Foo is a type. The compiler now only have to instanciate IFoo with that type:

```<code>template <class T> struct IFoo
{
     virtual T addX(T foo, double val) = 0;
};
</code>```

So really, it declares a class, with the declaration of a function in it. You saw above that declaring a function with an incomplete type works. The same happens here. At that point, Your code is possible as this code is:

```<code>struct Foo;
template struct IFoo<Foo>; // instanciate IFoo with Foo
</code>```

So really there's no sorcery there.

Now let's have a more convincing example. What about that?

```<code>template<typename T>
struct IFoo {
    void stuff(T f) {
        f.something();
    }
};

struct Foo : IFoo<Foo> {
    void something() {}
};
</code>```

How can the compiler call something on an incomplete type?

The thing is: it don't. Foo is complete when we use something. This is because template function are instantiated only when they are used.

Remember we can separate functions definition even with template?

```<code>template<typename T>
struct IFoo {
    void stuff(T f);
};

template<typename T>
void IFoo<T>::stuff(T f) {
    f.something();
}

struct Foo : IFoo<Foo> {
    void something() {}
};
</code>```

Great! Does it start looking exactly the same as your example with the pure virtual function? Let's make another valid transformation:

```<code>template<typename T>
struct IFoo {
    void stuff(T f);
};

struct Foo : IFoo<Foo> {
    void something() {}
};

// Later...
template<typename T>
void IFoo<T>::stuff(T f) {
    f.something();
}
</code>```

Done! We defined the function later, after Foo is complete. And this is exaclty what happens: The compiler will instanciate IFoo<Foo>::stuff only when used. And the point where it's used, Foo is complete. No magic there either.

Why can't you declare a T member variable inside IFoo then?

Simple, for the same reason why this code won't compile:

```<code>struct Bar;
Bar myBar;
</code>```

It doesn't make sense declaring a variable of an incomplete type.

ContentLicense: CC BY-SA 3.0

Body:
When I inherit from a class the compiler has to know the definition of the base class in order to create it. But when I inherit from a template class using oneself (the inheriting class), how can the compiler create the code? It does not know the size of the class yet.

#include <iostream>

template <class T> class IFoo
{
public:
     virtual T addX(T foo, double val) = 0;
     // T memberVar; // uncomment for error
};

class Foo : public IFoo<Foo>
{
public:
    Foo(double value)
        : m_value(value) {}

    Foo addX(Foo foo, double b) override
    {
        return Foo(foo.m_value + b);
    }

    double m_value;
};

int main()
{
    Foo foo1(1);
    Foo foo2 = foo1.addX(foo1, 1);

    std::cout << foo2.m_value;
}

First I thought it works because it's an interface but it also works with a regular class.

When I store the template as a member i get an error that Foo is undefined, just as I expected.

Body:
how can the compiler create the code?

Answering this question would be the same as answering this question: How can the compiler compile that?

struct Type;
Type func(Type);

Live example

How can you define a type that doesn't exist and yet declare a function that use that type?

The answer is simple: There is no code to compile with that actually use that non-existing type. Since there is no code to compile, how can it even fail?

Now maybe you're wondering what is has to do with your code? How does it make that a class can send itself as template parameter to it's parent?

Let's analyze what the compiler see when you're doing that:

struct Foo : IFoo<Foo> { /* ... */ };

First, the compile sees this:

struct Foo ...

The compiler now knows that Foo exists, yet it's an incomplete type.

Now, he sees that:

... : IFoo<Foo> ...

It knows what IFoo is, and it knows that Foo is a type. The compiler now only have to instanciate IFoo with that type:

template <class T> struct IFoo
{
     virtual T addX(T foo, double val) = 0;
};

So really, it declares a class, with the declaration of a function in it. You saw above that declaring a function with an incomplete type works. The same happens here. At that point, Your code is possible as this code is:

struct Foo;
template struct IFoo<Foo>; // instanciate IFoo with Foo

So really there's no sorcery there.

Now let's have a more convincing example. What about that?

template<typename T>
struct IFoo {
    void stuff(T f) {
        f.something();
    }
};

struct Foo : IFoo<Foo> {
    void something() {}
};

How can the compiler call something on an incomplete type?

The thing is: it don't. Foo is complete when we use something. This is because template function are instantiated only when they are used.

Remember we can separate functions definition even with template?

template<typename T>
struct IFoo {
    void stuff(T f);
};

template<typename T>
void IFoo<T>::stuff(T f) {
    f.something();
}

struct Foo : IFoo<Foo> {
    void something() {}
};

Great! Does it start looking exactly the same as your example with the pure virtual function? Let's make another valid transformation:

template<typename T>
struct IFoo {
    void stuff(T f);
};

struct Foo : IFoo<Foo> {
    void something() {}
};

// Later...
template<typename T>
void IFoo<T>::stuff(T f) {
    f.something();
}

Done! We defined the function later, after Foo is complete. And this is exaclty what happens: The compiler will instanciate IFoo<Foo>::stuff only when used. And the point where it's used, Foo is complete. No magic there either.

Why can't you declare a T member variable inside IFoo then?

Simple, for the same reason why this code won't compile:

struct Bar;
Bar myBar;

It doesn't make sense declaring a variable of an incomplete type.


问:
Toggle between two colors when key is pressed
I'm currently learning C# with Unity and I created a simple game where you can change the color of the player (which is red by default) by clicking the "C" key (which will change to green).
The code works but, the problem is, I don't know how to create a code that changes the green color to red color again by using the same key ("C").
The only alternative I know is to create another if but with a different button.
Here is my code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cubecolor : MonoBehaviour {

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<Renderer> ().material.color = Color.red;

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.C))
            gameObject.GetComponent<Renderer> ().material.color = Color.green;

    }
}
</code>```

答:
Well I would do this.</p>

```<code>Private Renderer objectRenderer = gameObject.getComponent<Renderer>();
Private Update() {
    If(Input.GetKeyDown(KeyCode.C))
        If(objectRenderer.material.color == Color.green)
           objectRenderer.material.color = Color.red;
        else
           objectRenderer.material.color = Color.green;
}
</code>```

Body:
I'm currently learning C# with Unity and I created a simple game where you can change the color of the player (which is red by default) by clicking the "C" key (which will change to green).
The code works but, the problem is, I don't know how to create a code that changes the green color to red color again by using the same key ("C").
The only alternative I know is to create another if but with a different button.
Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cubecolor : MonoBehaviour {

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<Renderer> ().material.color = Color.red;

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.C))
            gameObject.GetComponent<Renderer> ().material.color = Color.green;

    }
}

Body:
Well I would do this.

Private Renderer objectRenderer = gameObject.getComponent<Renderer>();
Private Update() {
    If(Input.GetKeyDown(KeyCode.C))
        If(objectRenderer.material.color == Color.green)
           objectRenderer.material.color = Color.red;
        else
           objectRenderer.material.color = Color.green;
}


问:
django - Could not parse the remainder: '-mail' from 'e-mail'
I was following the Definitive Guide To Django (v2)

Here's the traceback if you want to take a look
http://dpaste.com/344698/

It gives me this error:

```<code>TemplateSyntaxError at /contact/

Could not parse the remainder: '-mail' from 'e-mail'
Template error

In template /home/jwxie/django-dev/mysite/contact/template/contact_form.html, error at line 5
and line 5 is {% block content %}
</code>```

The code I had in the views.py

```<code>from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.mail import send_mail

def contact(request):
    display_error = []
    if request.method == 'POST':
        if not request.POST.get('subject',''):
            display_error.append('Enter a subject')
        if not request.POST.get('message',''):
            display_error.append('Enter a message')
        if not request.POST.get('e-mail') and '@' not in request.POST['e-mail']:
            display_error.append('Enter a valid e-mail address')
        if not display_error:
            send_mail(
                      request.POST['subject'],
                      request.POST['message'],
                      request.POST.get('e-mail','noreply@example.com'),
                      ['siteowner@example.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    return render_to_response('contact_form.html',{
                'subject': request.POST.get('subject',''),
                'message': request.POST.get('message',''),
                'e-mail': request.POST.get('e-mail',''),
                'display_error': display_error,
                })

def contact_thanks(request):
    return HttpResponse('Thanks')
</code>```

This is the code in contact_form.html

```<code>{% extends "base.html" %}

{% block title %} Contact {% endblock %}
{% block content %}
{% block content-h1 %}<p>Feel free to contact us!</p> {% endblock %}

<form action="/contact/" method="post">
<p>Subject: <input type="text" name="subject" value="{{ subject }}"></p>
<p>Your e-mail (optional): <input type="text" name="e-mail" value="{{ e-mail }}"> </p>
<p>Message: <textarea name="message" rows="10" cols="50">{{ message }}</textarea></p>
<input type="submit" value="Submit">
</form>

{% if display_error %}
<ul>
{% for error in display_error %}
<li>{{error}}</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}
</code>```

I had contact as app, the structure looks like this:   mysite/contact and it has its own template  mysite/contact/template
I am sure the setting.py is correct...

what do you guys think? any help is appreciated. I am just playing around with the sample code.

答:
Why do you write "e-mail"?  Don't the template variables have to be a Python variable names?  "e_mail"?

http://docs.djangoproject.com/en/dev/topics/templates/#variables

It says

Variable names consist of any
  combination of alphanumeric characters
  and the underscore ("_").

ContentLicense: CC BY-SA 2.5

Body:
I was following the Definitive Guide To Django (v2)

Here's the traceback if you want to take a look
http://dpaste.com/344698/

It gives me this error:

TemplateSyntaxError at /contact/

Could not parse the remainder: '-mail' from 'e-mail'
Template error

In template /home/jwxie/django-dev/mysite/contact/template/contact_form.html, error at line 5
and line 5 is {% block content %}

The code I had in the views.py

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.mail import send_mail

def contact(request):
    display_error = []
    if request.method == 'POST':
        if not request.POST.get('subject',''):
            display_error.append('Enter a subject')
        if not request.POST.get('message',''):
            display_error.append('Enter a message')
        if not request.POST.get('e-mail') and '@' not in request.POST['e-mail']:
            display_error.append('Enter a valid e-mail address')
        if not display_error:
            send_mail(
                      request.POST['subject'],
                      request.POST['message'],
                      request.POST.get('e-mail','noreply@example.com'),
                      ['siteowner@example.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    return render_to_response('contact_form.html',{
                'subject': request.POST.get('subject',''),
                'message': request.POST.get('message',''),
                'e-mail': request.POST.get('e-mail',''),
                'display_error': display_error,
                })

def contact_thanks(request):
    return HttpResponse('Thanks')

This is the code in contact_form.html

{% extends "base.html" %}

{% block title %} Contact {% endblock %}
{% block content %}
{% block content-h1 %}
Feel free to contact us!
 {% endblock %}

<form action="/contact/" method="post">

Subject: <input type="text" name="subject" value="{{ subject }}">

Your e-mail (optional): <input type="text" name="e-mail" value="{{ e-mail }}">

Message: <textarea name="message" rows="10" cols="50">{{ message }}</textarea>

<input type="submit" value="Submit">
</form>

{% if display_error %}

{% for error in display_error %}

{{error}}

{% endfor %}

{% endif %}
{% endblock %}

I had contact as app, the structure looks like this:   mysite/contact and it has its own template  mysite/contact/template
I am sure the setting.py is correct...

what do you guys think? any help is appreciated. I am just playing around with the sample code.


问:
LOCATION in Hive
While creating hive tables, Can I point the 'LOCATION' to a place in hdfs where data is present. Do I still need to load data or Will the data be available on hive directly?</p>

答:
You can specify any location while creating table and the data will be accessible. If table is partitioned, then use ALTER TABLE ADD PARTITION or MSCK REPAIR TABLE table_name or Amazon version ALTER TABLE table_name RECOVER PARTITIONS , this will add any partitions that exist on HDFS but not in metastore to the metastore. See docs here: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RecoverPartitions(MSCKREPAIRTABLE)

If table is not partitioned, you can simply specify the location with data while creating table or change table location using ALTER TABLE SET LOCATION.

Title: LOCATION in Hive

ContentLicense: CC BY-SA 4.0


问:
right join where key is null in python pandas with MultiIndexes
I have two dataframes with MultiIndexes, and I need to right join them and then get the items on the right side which didn't have a key match.

The preferred answer for how to do right join where key is null in python pandas suggests to do something like this:

```<code>In [1]: dfa = pd.DataFrame({'A': range(5)}, index=range(5))

In [2]: dfb = pd.DataFrame({'A': range(10, 15)}, index=range(3,8))

In [3]: dfa
Out[3]:
   A
0  0
1  1
2  2
3  3
4  4

In [4]: dfb
Out[4]:
    A
3  10
4  11
5  12
6  13
7  14

In [5]: dfb.loc[dfb.index - dfa.index]
Out[5]:
    A
5  12
6  13
7  14
</code>```

but when I try that with my code, I get an error:

```<code>TypeError: cannot perform __sub__ with this index type: <class 'pandas.core.indexes.multi.MultiIndex'>
</code>```

What options do I have given that MultiIndexes can't be subtracted from one another?

答:
You do not need a join to get the items that did not match. A simpler way would be using the below:

```<code>df = dfb[dfb.index.isin(dfa.index) == False]
</code>```

Alternate way, that uses join, would be:

```<code>a = dfa.join(dfb, lsuffix='a', how='right')
a[a.Aa.isnull()][['A']]
</code>```

I do not know your exact requirement, but to get the result, 1st is probably a neater way of achieving the goal. Regards

Body:
I have two dataframes with MultiIndexes, and I need to right join them and then get the items on the right side which didn't have a key match.

The preferred answer for how to do right join where key is null in python pandas suggests to do something like this:

In [1]: dfa = pd.DataFrame({'A': range(5)}, index=range(5))

In [2]: dfb = pd.DataFrame({'A': range(10, 15)}, index=range(3,8))

In [3]: dfa
Out[3]:
   A
0  0
1  1
2  2
3  3
4  4

In [4]: dfb
Out[4]:
    A
3  10
4  11
5  12
6  13
7  14

In [5]: dfb.loc[dfb.index - dfa.index]
Out[5]:
    A
5  12
6  13
7  14

but when I try that with my code, I get an error:

TypeError: cannot perform __sub__ with this index type: <class 'pandas.core.indexes.multi.MultiIndex'>

What options do I have given that MultiIndexes can't be subtracted from one another?

Body:
You do not need a join to get the items that did not match. A simpler way would be using the below:

df = dfb[dfb.index.isin(dfa.index) == False]

Alternate way, that uses join, would be:

a = dfa.join(dfb, lsuffix='a', how='right')
a[a.Aa.isnull()][['A']]

I do not know your exact requirement, but to get the result, 1st is probably a neater way of achieving the goal. Regards


问:
Code optimization - Automatic click
guys.

I am using the following code on tampermonkey / violentmonkey to automatically approve entries in my database.

The code it self works fine but since I need to use in several two tabs and the entries are high so I'm wondering if there a way to make it faster.

```<code>window.onload=function(){

setInterval(autoBypass,1500); };

function autoBypass(){
if(document.getElementsByClassName("error").length>0){
document.getElementsByClassName("bypass")[0].click();
}
else{setInterval(autoAprove,500);}
}

function autoAprove(){
 if(document.getElementsByClassName("aprove").length>0){
 document.getElementsByClassName("aprove")[0].click();
}
}
</code>```

I'm using 1.5s to give time to the page to load but sometimes - especially when I'm using Opera browser - it gets stuck on a loop and I have to close the tab.

Any ideas?

答:
Your code runs autoBypass every 1500ms. Every 1500ms, autoBypass tells autoAprove to run every 500ms. After one minute, autoAprove has run 1740 times, and it only gets worse from there. More and more of the browser's time is spent running your code, leaving it unable to respond to input.

One or both of those timers should be setTimeout, not setInterval.

Title: Code optimization - Automatic click

Body:
guys.

I am using the following code on tampermonkey / violentmonkey to automatically approve entries in my database.

The code it self works fine but since I need to use in several two tabs and the entries are high so I'm wondering if there a way to make it faster.

window.onload=function(){

setInterval(autoBypass,1500); };

function autoBypass(){
if(document.getElementsByClassName("error").length>0){
document.getElementsByClassName("bypass")[0].click();
}
else{setInterval(autoAprove,500);}
}

function autoAprove(){
 if(document.getElementsByClassName("aprove").length>0){
 document.getElementsByClassName("aprove")[0].click();
}
}

I'm using 1.5s to give time to the page to load but sometimes - especially when I'm using Opera browser - it gets stuck on a loop and I have to close the tab.

Any ideas?


问:
Creating an NPM START script in package.json
So I'm trying to create a script that when someone makes npm start it starts a localhost.
Now this is what I have on my package.json:

```<code>"scripts": {
    "start": "npm run open",
    "open": "concurrently \"http-server -a localhost -p 1234\" \"sleepms 1000 && open http://localhost:1234/public/index.htm\"",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

"devDependencies": {
    "concurrently": "^3.5.1",
    "http-server": "^0.10.0",
    "opn-cli": "^3.1.0",
    "sleep-ms": "^2.0.1"
  }
</code>```

But what I'm getting is a 404 of the localhost...

Other question, is it possible to make so that when the user types npm start it installs or updates all dependencies?

I just recently started with Web development, please have that in mind...

Thank you

答:
Per the http-server documentation...

http-server [path] [options]

[path] defaults to ./public if the folder exists, and ./ otherwise.

Since you are not passing a path, it's defaulting to ./public as its root directory, so you do not need to include /public in your URL.

Try accessing http://localhost:1234/index.htm instead of http://localhost:1234/public/index.htm

Body:
So I'm trying to create a script that when someone makes npm start it starts a localhost.
Now this is what I have on my package.json:

"scripts": {
    "start": "npm run open",
    "open": "concurrently \"http-server -a localhost -p 1234\" \"sleepms 1000 && open http://localhost:1234/public/index.htm\"",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

"devDependencies": {
    "concurrently": "^3.5.1",
    "http-server": "^0.10.0",
    "opn-cli": "^3.1.0",
    "sleep-ms": "^2.0.1"
  }

But what I'm getting is a 404 of the localhost...

Other question, is it possible to make so that when the user types npm start it installs or updates all dependencies?

I just recently started with Web development, please have that in mind...

Thank you


问:
How would a Uber driver receive a request in real-time (instantaneously) with Firebase?
If I have an app that connect a restaurant to users, how should restaurants receive an order from users as soon as the user request the order? Similarly, how would Uber drivers be notified when riders request a ride?

Adding snapshot listener sounds expensive for Firestore. From what I understand, snapshot listeners should be used when realtime updates are very important but for a limite amount of time, like in a match in a multiplayer game.

To be listening to realtime changes in the Firestore database all day long sounds expensive.

Another option would be a notification. What would be the best option, or which other way would be the most appropriate?

答:
Notifications are most likely the right solution to this use case.

It is difficult to create a mobile app that can correctly keep a Firebase/Firestore listener up and running all the time; mobile OSs like to limit that type of background activity.  (The newer versions of Android are particularly aggressive with background service limits.)

Having your server issue an FCM notification to "wake up" the mobile app for a specific action is reliable and fairly straighforward to implement.


问:
action.devices.traits.Modes - anyone implemented this?
i've implemented a Smart Home app on Google, and now want to implement the n-way Modes trait for some switch types.
my JSON response seems to mirror that of the example, and discovery works, but i can't interact with the switch using the mode examples (JSON not complete) - anyone got any idea what i'm missing?</p>

```<code>    "attributes": {
           "availableModes": [{
                 "name": "Control",
                 "name_values": [{
                   "name_synonym": ["control", "mode"],
                   "lang": "en"
                    }],
                 "settings": [{
                  "setting_name": "Off",
                  "setting_values": [{
                    "setting_synonym": [ "Off"],
                    "lang": "en"
                    }]
                 },{
                  "setting_name": "Level1",
                  "setting_values": [{
                    "setting_synonym": ["Level1"],
                    "lang": "en"
                    }]
               }],
                 "ordered": false
              }]
        }
</code>```

答:
From the documentation, custom names for modes and toggles do not work yet.

"Currently, you must submit names to us so we can add support for them."

Body:
i've implemented a Smart Home app on Google, and now want to implement the n-way Modes trait for some switch types.
my JSON response seems to mirror that of the example, and discovery works, but i can't interact with the switch using the mode examples (JSON not complete) - anyone got any idea what i'm missing?

    "attributes": {
           "availableModes": [{
                 "name": "Control",
                 "name_values": [{
                   "name_synonym": ["control", "mode"],
                   "lang": "en"
                    }],
                 "settings": [{
                  "setting_name": "Off",
                  "setting_values": [{
                    "setting_synonym": [ "Off"],
                    "lang": "en"
                    }]
                 },{
                  "setting_name": "Level1",
                  "setting_values": [{
                    "setting_synonym": ["Level1"],
                    "lang": "en"
                    }]
               }],
                 "ordered": false
              }]
        }


问:
Regex to change only number inside a div
I have this regex for now

```<code>/<div[^>]*>|(\d{1,9}\.\d{2})/
</code>```

which detect the opening of a
 and group the number in a currency format inside it.

If I have a string like this

```<code><div class="foo">Hello world 4546.00 and 6596.45 bla bla bla</div>
</code>```

I would like to only replace the numbers inside it with a preg_replace

As you can see in the example below, I don't want the number outside of the div to be selected, only ones inside.

https://regex101.com/r/AZd896/1/

答:
While Parsing HTML with regex sounds like fun, please use a proper XML parser instead. You can use the following DOMDocument code to achieve, this functionality:

```<code><?php

$html = 'dasdfasdf 355.56 asdfasd
<div class="sdaf">sdfsad 36546545643.00 asdfa sdf sadfasdf 544.45 sadfs</div>';

$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$divs = $doc->getElementsByTagName('div');
foreach($divs as $div)
{
    $innerText = $div->nodeValue;
    $div->nodeValue = preg_replace('(\d{1,9}\.\d{2})', 'whatever', $innerText);
}

$html = $doc->saveHTML();

var_dump($html);
</code>```

Now, with this you only have to parse with REGEX the inner string instead of the
 itself.

Body:
I have this regex for now

/
]*>|(\d{1,9}\.\d{2})/

which detect the opening of a
 and group the number in a currency format inside it.

If I have a string like this

Hello world 4546.00 and 6596.45 bla bla bla

I would like to only replace the numbers inside it with a preg_replace

As you can see in the example below, I don't want the number outside of the div to be selected, only ones inside.

https://regex101.com/r/AZd896/1/

Body:
While Parsing HTML with regex sounds like fun, please use a proper XML parser instead. You can use the following DOMDocument code to achieve, this functionality:

<?php

$html = 'dasdfasdf 355.56 asdfasd
<div class="sdaf">sdfsad 36546545643.00 asdfa sdf sadfasdf 544.45 sadfs</div>';

$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$divs = $doc->getElementsByTagName('div');
foreach($divs as $div)
{
    $innerText = $div->nodeValue;
    $div->nodeValue = preg_replace('(\d{1,9}\.\d{2})', 'whatever', $innerText);
}

$html = $doc->saveHTML();

var_dump($html);

Now, with this you only have to parse with REGEX the inner string instead of the <div> itself.


问:
How to output a variable value to the log from MSBuild
How do I output a variable value to the log from MSBuild?

I am trying to debug an MSBuild script and would like to output a variable's value to the log.

答:
You can actually debug MSBuild scripts with Visual Studio 2010 now. It requires some hacking, and it isn't officially supported, but it is an option.

Otherwise use the Message task. Normal rules for referencing Properties, Items and Item Metadata (also referred to as batching) apply.

This example:

```<code><Project DefaultTargets="Build"
         xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <TestItem Include="test1" />
    <TestItem Include="test2" />
    <TestItem Include="test3" />
  </ItemGroup>

  <PropertyGroup>
    <TestProperty>Property Value</TestProperty>
  </PropertyGroup>

  <Target Name="TestMessage" AfterTargets="Build" >

    <!-- Use $(Property Name) to reference a property -->
    <Message Text="$(TestProperty)" Importance="high"/>

    <!-- Use @(Item Name) to output a semi-colon
         separated list of items on one line      -->
    <Message Text="@(TestItem)" Importance="high"/>

    <!-- Use %(Item Name.Metadata Property Name) to
         call the Message task once for each item.   -->
    <!-- This will output each item on a separate line -->
    <Message Text="%(TestItem.Identity)" Importance="high"/>

  </Target>
</Project>
</code>```

Will produce this output:

```<code>Property Value
test1;test2;test3
test1
test2
test3
</code>```

Body:
You can actually debug MSBuild scripts with Visual Studio 2010 now. It requires some hacking, and it isn't officially supported, but it is an option.

Otherwise use the Message task. Normal rules for referencing Properties, Items and Item Metadata (also referred to as batching) apply.

This example:

<Project DefaultTargets="Build"
         xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <TestItem Include="test1" />
    <TestItem Include="test2" />
    <TestItem Include="test3" />
  </ItemGroup>

  <PropertyGroup>
    <TestProperty>Property Value</TestProperty>
  </PropertyGroup>

  <Target Name="TestMessage" AfterTargets="Build" >

    <!-- Use $(Property Name) to reference a property -->
    <Message Text="$(TestProperty)" Importance="high"/>

    <!-- Use @(Item Name) to output a semi-colon
         separated list of items on one line      -->
    <Message Text="@(TestItem)" Importance="high"/>

    <!-- Use %(Item Name.Metadata Property Name) to
         call the Message task once for each item.   -->
    <!-- This will output each item on a separate line -->
    <Message Text="%(TestItem.Identity)" Importance="high"/>

  </Target>
</Project>

Will produce this output:

Property Value
test1;test2;test3
test1
test2
test3


问:
Generic and non-generic interfaces and inheritance - ambiguity while accessing
I have the following setup

Base class

```<code>public class Fruit
{

}
</code>```

Inherited class

```<code>public class Apple : Fruit
{

}
</code>```

Generic Base interface

```<code>public interface IFruitsBase<T> where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}
</code>```

Non generic Interface that inheritates from generic interface with the base class as the generic

```<code>public interface IFruits : IFruitsBase<Fruit>
{

}
</code>```

Specific interface of the correspoing class

```<code>public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}
</code>```

Base implementation class

```<code>public class Fruits<T> : IFruitsBase<T>, IFruits where T : Fruit
{
    public T GetItem()
    {
        return null;
    }
    public void ProcessItem(T fruit)
    {

    }
    public void Check()
    {

    }

    Fruit IFruitsBase<Fruit>.GetItem()
    {
        return this.GetItem();
    }
    void IFruitsBase<Fruit>.ProcessItem(Fruit fruit)
    {
        ProcessItem((T)fruit);
    }
}
</code>```

Specific implementation

```<code>public class Apples : Fruits<Apple>, IApples
{
    public void MakeAppleJuice(IEnumerable<Apple> apples)
    {

    }
}
</code>```

The problem I am facing, is at that part:

```<code>public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}
</code>```

Here I am getting the message:

Possible ambiguity while accessing by this Interface Apple IFruitsBase<Apple> Get() Fruit IFruitsBase<Fruit>.Get()

To fix the problem I could remove the interface IFruits from IApples, but this gives other errors as in:

```<code>public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits GetFruits(Type type)
    {
        return this.Apples; //simplified the code here, it should actually get the member of this that fits the type
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits[] { context.Apples }); //can't do that since context.Apples doesnt inherit from IFruits, to fix the above ambiguity
    }

    public void Check(IEnumerable<IFruits> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}
</code>```

My goal is if someone accesses the objects with:

```<code>var context = new Context();
context.Apples.[only apple relevant methods should be accessable]
</code>```

if someone access it with:

```<code>var context = new Context();
context.GetFruits(item.GetType()).[only fruit relevant methods should be accessable]
</code>```

and no matter if one got it with method a or b, all should be passable to methods with a signature of

```<code>void Foo(IFruits fruits);
</code>```

答:
I hope I did not understand the question wrong, and this is not too stupid :)</p>

```<code>public interface IFruit
{
}
public interface IApple: IFruit
{
}
public interface IFruits<T> where T : IFruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}
public class Fruits<T> : IFruits<T> where T : IFruit
{
    public void Check()
    {
        throw new NotImplementedException();
    }

    public T GetItem()
    {
        throw new NotImplementedException();
    }

    public void ProcessItem(T fruit)
    {
        throw new NotImplementedException();
    }
}
public interface IApples
{
    void MakeAppleJuice(IEnumerable<IApple> apples);
}
public class Apples : Fruits<IApple>, IApples
{
    public void MakeAppleJuice(IEnumerable<IApple> apples)
    {
        throw new NotImplementedException();
    }
}
public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits<IFruit> GetFruits<T>()
    {
        return null;
    }
    private void test()
    {
        //this.GetFruits<IFruit>().ProcessItem(
        //this.GetFruits<IApple>().ProcessItem(
        //this.Apples.MakeAppleJuice(
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits<IFruit>[] { context.GetFruits<IApple>() });
    }
    public void Check(IEnumerable<IFruits<IFruit>> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}
</code>```

Body:
I have the following setup

Base class

public class Fruit
{

}

Inherited class

public class Apple : Fruit
{

}

Generic Base interface

public interface IFruitsBase<T> where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}

Non generic Interface that inheritates from generic interface with the base class as the generic

public interface IFruits : IFruitsBase<Fruit>
{

}

Specific interface of the correspoing class

public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}

Base implementation class

public class Fruits<T> : IFruitsBase<T>, IFruits where T : Fruit
{
    public T GetItem()
    {
        return null;
    }
    public void ProcessItem(T fruit)
    {

    }
    public void Check()
    {

    }

    Fruit IFruitsBase<Fruit>.GetItem()
    {
        return this.GetItem();
    }
    void IFruitsBase<Fruit>.ProcessItem(Fruit fruit)
    {
        ProcessItem((T)fruit);
    }
}

Specific implementation

public class Apples : Fruits<Apple>, IApples
{
    public void MakeAppleJuice(IEnumerable<Apple> apples)
    {

    }
}

The problem I am facing, is at that part:

public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}

Here I am getting the message:

Possible ambiguity while accessing by this Interface Apple IFruitsBase<Apple> Get() Fruit IFruitsBase<Fruit>.Get()

To fix the problem I could remove the interface IFruits from IApples, but this gives other errors as in:

public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits GetFruits(Type type)
    {
        return this.Apples; //simplified the code here, it should actually get the member of this that fits the type
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits[] { context.Apples }); //can't do that since context.Apples doesnt inherit from IFruits, to fix the above ambiguity
    }

    public void Check(IEnumerable<IFruits> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}

My goal is if someone accesses the objects with:

var context = new Context();
context.Apples.[only apple relevant methods should be accessable]

if someone access it with:

var context = new Context();
context.GetFruits(item.GetType()).[only fruit relevant methods should be accessable]

and no matter if one got it with method a or b, all should be passable to methods with a signature of

void Foo(IFruits fruits);

Body:
I hope I did not understand the question wrong, and this is not too stupid :)

public interface IFruit
{
}
public interface IApple: IFruit
{
}
public interface IFruits<T> where T : IFruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}
public class Fruits<T> : IFruits<T> where T : IFruit
{
    public void Check()
    {
        throw new NotImplementedException();
    }

    public T GetItem()
    {
        throw new NotImplementedException();
    }

    public void ProcessItem(T fruit)
    {
        throw new NotImplementedException();
    }
}
public interface IApples
{
    void MakeAppleJuice(IEnumerable<IApple> apples);
}
public class Apples : Fruits<IApple>, IApples
{
    public void MakeAppleJuice(IEnumerable<IApple> apples)
    {
        throw new NotImplementedException();
    }
}
public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits<IFruit> GetFruits<T>()
    {
        return null;
    }
    private void test()
    {
        //this.GetFruits<IFruit>().ProcessItem(
        //this.GetFruits<IApple>().ProcessItem(
        //this.Apples.MakeAppleJuice(
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits<IFruit>[] { context.GetFruits<IApple>() });
    }
    public void Check(IEnumerable<IFruits<IFruit>> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}


问:
How to connect Azure Paas Database using Powershell with intergrated security
How can I connect to an Azure SQLDatabase (Paas Instance) using Powershell without a username & password but rather with Active Directory. I can connect with a username and password when I use invoke-sqlcmd  as below

```<code>$Servername = "XXXXXX.database.windows.net"
$params = @{

   Database = $databasename

   ServerInstance = $ServerName

   Username = $UserName

   Password = $password

   'OutputSqlErrors' = $true

   Query = $QueryString

}

Invoke-Sqlcmd  @params
</code>```

I need the ability to do it with Active Directory. I have read a few articles on how to connect with active directory as long as you specify it on the connection string (Context of C#) Using ODBC connection or other data sources. Since Powershell is based on .Net; this should be do-able..

```<code>    $ConnString = "DRIVER=ODBC Driver 13 for SQL Server;SERVER=xxxxx.database.windows.net;DATABASE=DBName;Trusted_Connection=Yes"
    $Conn = new-object System.Data.Odbc.OdbcConnection($ConnString)
    $conn.open()
    $cmd = new-object System.Data.Odbc.OdbcCommand("select getdate() as X", $Conn)
    $data = new-object System.Data.Odbc.OdbcDataAdapter($cmd)
    $dt = new-object System.Data.DataColumn
    $data.Fill($dt)
    $Conn.Close()

#`server=Server;database=Database;Authentication=ActiveDirectoryIntegrated;`
</code>```

The objective of trying to use Active Directory is that, within Paas, only AD Accounts can Add other AD accounts. I want to be able to add other accounts with method rather than logging in the Azure portal and adding an AD account manually.

答:
The following sample shows how to invoke Add-AzureAccount without the popup dialog:</p>

```<code>$username = "someorgid@orgaccount.com"
$password = "Pa$$w0rd" | ConvertTo-SecureString -AsPlainText -Force

$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
Add-AzureAccount -Credential $credential
</code>```

Body:
How can I connect to an Azure SQLDatabase (Paas Instance) using Powershell without a username & password but rather with Active Directory. I can connect with a username and password when I use invoke-sqlcmd  as below

$Servername = "XXXXXX.database.windows.net"
$params = @{

   Database = $databasename

   ServerInstance = $ServerName

   Username = $UserName

   Password = $password

   'OutputSqlErrors' = $true

   Query = $QueryString

}

Invoke-Sqlcmd  @params

I need the ability to do it with Active Directory. I have read a few articles on how to connect with active directory as long as you specify it on the connection string (Context of C#) Using ODBC connection or other data sources. Since Powershell is based on .Net; this should be do-able..

    $ConnString = "DRIVER=ODBC Driver 13 for SQL Server;SERVER=xxxxx.database.windows.net;DATABASE=DBName;Trusted_Connection=Yes"
    $Conn = new-object System.Data.Odbc.OdbcConnection($ConnString)
    $conn.open()
    $cmd = new-object System.Data.Odbc.OdbcCommand("select getdate() as X", $Conn)
    $data = new-object System.Data.Odbc.OdbcDataAdapter($cmd)
    $dt = new-object System.Data.DataColumn
    $data.Fill($dt)
    $Conn.Close()

#`server=Server;database=Database;Authentication=ActiveDirectoryIntegrated;`

The objective of trying to use Active Directory is that, within Paas, only AD Accounts can Add other AD accounts. I want to be able to add other accounts with method rather than logging in the Azure portal and adding an AD account manually.

Body:
The following sample shows how to invoke Add-AzureAccount without the popup dialog:

$username = "someorgid@orgaccount.com"
$password = "Pa$$w0rd" | ConvertTo-SecureString -AsPlainText -Force

$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
Add-AzureAccount -Credential $credential


问:
Angular 2 ng bootstrap typehead pass additional parameter
How to pass form array index to getCities function in ng-bootstrap typehead including current input text. Consider 3 is form array index.

address.component.html

```<code><input name="city" type="text" id="city" formControlName="city" [ngbTypeahead]="getCities">
</code>```

address.component.ts

```<code>getCities = (text$: Observable<string>) =>
    text$
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(query =>
        query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
            return Observable.of([]);
        });)
</code>```

答:
It sounds like you are needing to pass an additional parameter to the ngbTypeahead function (be it an index parameter or otherwise).

While the documentation ( https://ng-bootstrap.github.io/#/components/typeahead/api ) does not provide for passing parameters, you can implement a "factory" method that returns an appropriate function with the index (or whatever) parameter passed in.

address.component.html

    <input name="city"
        type="text"
        id="city"
        formControlName="city"
        [ngbTypeahead]="searchFunctionFactory($index)" >
```

<p><strong>address.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>    //A function that returns a "search" function for our ngbTypeahead w/ "preloaded" parameters
    public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {

        //Create a function that considers the specified $index parameter value
        let getCities = (text$: Observable<string>) =>
            text$
                .debounceTime(300)
                .distinctUntilChanged()
                .switchMap( query => {

                    //some logic involving $index here
                    //...

                    //query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
                    //return Observable.of([]);
                });

        //Return that "custom" function, which will in turn be called by the ngbTypescript component
        return getCities;
    }
</code>```

Body:
How to pass form array index to getCities function in ng-bootstrap typehead including current input text. Consider 3 is form array index.

address.component.html

<input name="city" type="text" id="city" formControlName="city" [ngbTypeahead]="getCities">

address.component.ts

getCities = (text$: Observable<string>) =>
    text$
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(query =>
        query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
            return Observable.of([]);
        });)

Body:
It sounds like you are needing to pass an additional parameter to the ngbTypeahead function (be it an index parameter or otherwise).

While the documentation ( https://ng-bootstrap.github.io/#/components/typeahead/api ) does not provide for passing parameters, you can implement a "factory" method that returns an appropriate function with the index (or whatever) parameter passed in.

address.component.html

    <input name="city"
        type="text"
        id="city"
        formControlName="city"
        [ngbTypeahead]="searchFunctionFactory($index)" >

address.component.ts

    //A function that returns a "search" function for our ngbTypeahead w/ "preloaded" parameters
    public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {

        //Create a function that considers the specified $index parameter value
        let getCities = (text$: Observable<string>) =>
            text$
                .debounceTime(300)
                .distinctUntilChanged()
                .switchMap( query => {

                    //some logic involving $index here
                    //...

                    //query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
                    //return Observable.of([]);
                });

        //Return that "custom" function, which will in turn be called by the ngbTypescript component
        return getCities;
    }


问:
JNA Memory Leak - How to fix?
```<code>        public static User32 USER32_INSTANCE = (User32) Native.loadLibrary("user32", User32.class);

        user32 = USER32_INSTANCE;

        user32.EnumWindows((hWnd, arg) -> {
          int size = 1024 * 8;
          char[] buffer = new char[size];
          USER32_INSTANCE.GetWindowTextW(hWnd, buffer, size);

          char[] buffer2 = new char[size];
          PointerByReference pointer = new PointerByReference();
          User32DLL.GetWindowThreadProcessId(hWnd, pointer);
          Pointer process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pointer.getValue());
          Psapi.GetModuleBaseNameW(process, null, buffer2, size);

          String result = Native.toString(buffer).trim();
          String proc = Native.toString(buffer2).trim();

          // ... (non-JNA stuff)
        }
</code>```

I haven't touched C/C++ since college and I honestly have no clue how to actually free the memory here :(

I know that there's a memory leak - I did some profiling with YourKit and traced a memory leak to this block of code (specifically, it seems to be leaking in the GetWindowTextW call and the Native.toString() calls). Could someone just give me an example of how to properly free up whatever memory blocks are being used?

I see that Pointer has a clear() method, should I use that? But I don't know how to get the size (clear takes a length argument). I also see that there's a Memory type that subclasses Pointer, but according to instanceof, none of the Pointers I have right now are actually instances of that.

答:
After opening a handle to a process with OpenProcess, you need to close the process handle with CloseHandle. Remember that OpenProcess returns a Handle, not a Pointer.

```<code>Kernel32.INSTANCE.CloseHandle(process);
</code>```

Note also that JNA provides a pretty in-depth mapping of the Windows API out of the box in the net.java.dev.jna-platform package (I think?)

Title: JNA Memory Leak - How to fix?

Body:
        public static User32 USER32_INSTANCE = (User32) Native.loadLibrary("user32", User32.class);

        user32 = USER32_INSTANCE;

        user32.EnumWindows((hWnd, arg) -> {
          int size = 1024 * 8;
          char[] buffer = new char[size];
          USER32_INSTANCE.GetWindowTextW(hWnd, buffer, size);

          char[] buffer2 = new char[size];
          PointerByReference pointer = new PointerByReference();
          User32DLL.GetWindowThreadProcessId(hWnd, pointer);
          Pointer process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pointer.getValue());
          Psapi.GetModuleBaseNameW(process, null, buffer2, size);

          String result = Native.toString(buffer).trim();
          String proc = Native.toString(buffer2).trim();

          // ... (non-JNA stuff)
        }

I haven't touched C/C++ since college and I honestly have no clue how to actually free the memory here :(

I know that there's a memory leak - I did some profiling with YourKit and traced a memory leak to this block of code (specifically, it seems to be leaking in the GetWindowTextW call and the Native.toString() calls). Could someone just give me an example of how to properly free up whatever memory blocks are being used?

I see that Pointer has a clear() method, should I use that? But I don't know how to get the size (clear takes a length argument). I also see that there's a Memory type that subclasses Pointer, but according to instanceof, none of the Pointers I have right now are actually instances of that.

Body:
After opening a handle to a process with OpenProcess, you need to close the process handle with CloseHandle. Remember that OpenProcess returns a Handle, not a Pointer.

Kernel32.INSTANCE.CloseHandle(process);

Note also that JNA provides a pretty in-depth mapping of the Windows API out of the box in the net.java.dev.jna-platform package (I think?)


问:
Issues Serializing an ArrayList object containing other ArrayList objects
So I'm Serializing an ArrayList of ArrayLists essentially but I'm running into an issue. To be honest I'm still pretty new to Java, I've tried so many different methods to fix this as well as searched relentlessly on this site and have not been successful. I know that the way I word things may be hard to follow along or is confusing so I'll post my code here to see. Sorry in advance for all the code. SuperUsers has an arraylist of LoginInfo, PasswordKeeper has an Arraylist of SuperUsers, and the SuperUser arraylist gets serialized in PasswordKeeper. but any changes made to the LoginInfo arraylist do not save and i cannot figure out why. If anyone can help I would really Appreciate it. Thanks</p>

```<code>public class PasswordKeeper{

    private ArrayList<SuperUser> users;
    private static Scanner keyboard = new Scanner(System.in);

    public PasswordKeeper() {
        users = new ArrayList();
    }

    public void login() {
        try {
            // reads in SuperUser arraylist
            get();
        } catch (EOFException a) {
            System.out.println("You are the First User!");
        } catch (IOException b) {
            System.out.println(b);
        } catch (ClassNotFoundException c) {
            System.out.println(c);
        }
        boolean loopDisplay = true;
        while (loopDisplay) {
                existingUser = keyboard.next();
                existingPass = keyboard.next();
                SuperUser temp = new SuperUser(existingUser, existingPass);
                System.out.println();
                if (users.contains(temp)) {

                    // viewing superUser method
                    temp.display();
                    //saves after method call is over
                    try {
                        System.out.println("Saving.");
                        save(users);
                    } catch (IOException e) {
                        System.out.println(e);
                    }
                }
            }
            //This happens if there is a new user
            if(answer == 2){
            SuperUser tempNew = null;
            boolean cont = true;
            String newUser;
            String pass;
            while(cont){
                newUser = keyboard.nextLine();
                System.out.println();
                //System.out.println(users.size());

                tempNew = new SuperUser(newUser, pass);
                if(passValid(pass) == true){
                    if(makeSure(tempNew) == true){
                        System.out.println("Login Created!");
                        tempNew = new SuperUser(newUser, pass);
                        //actually being added to the arraylist
                        users.add(tempNew);
                        cont = false;
                    }
                }
            }
            //SuperUser.display method
            tempNew.display();
            try{
                System.out.println("Saving.");
                save(users);
            }catch(IOException e){
                System.out.println(e);
            }
        }
        }
    }
    //makeSure and passValid methods
    public boolean makeSure(SuperUser user){
    if(users.contains(user)){
        return false;
    }
    return true;
}

public boolean passValid(String pass){
        boolean passes = false;
        String upper = "(.*[A-Z].*)";
        String lower = "(.*[a-z].*)";
        String numbers = "(.*[0-9].*)";
        String special = "(.*[,~,!,@,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";

        if((pass.length()>15) || (pass.length() < 8)){
            System.out.println("Entry must contain over 8 characters\n" +
            "and less than 15.");
            passes = false;
        }if(!pass.matches(upper) || !pass.matches(lower)){
            System.out.println("Entry must contain at least one uppercase and lowercase");
            passes = false;
        }if(!pass.matches(numbers)){
                    System.out.println("Password should contain atleast one number.");
                    passes = false;
        }if(!pass.matches(special)){
                    System.out.println("Password should contain atleast one special character");
                    passes = false;
        }else{
            passes = true;
        }
        return passes;
    //serializable methods
    public void save(ArrayList<SuperUser> obj) throws IOException {

        File file = new File("userInformation.dat");
        FileOutputStream fileOut = new FileOutputStream(file, false);
        BufferedOutputStream buffedOutput = new BufferedOutputStream(fileOut);
        ObjectOutputStream out = new ObjectOutputStream(buffedOutput);
        out.writeObject(obj);
        out.close();
        fileOut.close();
    }

    public ArrayList<SuperUser> get() throws IOException, ClassNotFoundException {
        FileInputStream fileIn = new FileInputStream("userInformation.dat");
        BufferedInputStream buffedInput = new BufferedInputStream(fileIn);
        ObjectInputStream in = new ObjectInputStream(buffedInput);
        users = (ArrayList<SuperUser>) in.readObject();
        in.close();
        fileIn.close();
        return users;
    }

    public class SuperUser implements Serializable {
        private String userName;
        private String password;
        private static Scanner keyboard = new Scanner(System.in);
        private ArrayList<LoginInfo> info = new ArrayList();

        public SuperUser(String name, String pass) {
            userName = name;
            password = pass;
        }

        public String getUser() {
            return userName;
        }

        public void display() {

            String next = keyboard.next();
            //want to add data to LoginInfo arraylist
            if (next.equalsIgnoreCase("add")) {
                add();
            } else if (next.equalsIgnoreCase("delete")) {
                delete();
            } else if (numberCheck(next)) {
                int choice = (int) Integer.parseInt(next) - 1;
                edit(choice);
            //!!!! this: after doing this i lose whatever data i added
            //to the LoginInfo arraylist, right after this the
            //SuperUser arraylist gets saved. but the added data to
            //loginInfo does not
            } else if (next.equalsIgnoreCase("logout")) {
                System.out.println(info.size());
            }
        }

        public boolean numberCheck(String in) {
            try {
                Integer.parseInt(in);
            } catch (NumberFormatException e) {
                return false;
            }
            return true;
        }
        //method to add to the Arraylist
        public void add() {
            System.out.println("What is the website name?:");
            String trash = keyboard.nextLine();
            String webName = keyboard.nextLine();
            System.out.println("The Username?:");
            String webUsername = keyboard.nextLine();
            System.out.println("The Password?:");
            String webPass = keyboard.nextLine();
            info.add(new LoginInfo(webUsername, webPass, webName));
            System.out.println(info.size());
            //method goes back to display
            display();
        }
    }
}
</code>```

答:
Your problem is here

```<code>SuperUser temp = new  SuperUser(existingUser, existingPass);
    System.out.println();
    if (users.contains(temp)) {
        // viewing superUser method
        temp.display();
</code>```

You create a temporary object which with the username and password.

Your 'users.contains()' method returns true because '.equals()' is based on the username, however the 'temp' object is a different instance to that in the list.

So when you call 'temp.display()' it is not calling on an object in the list, so no data changes will save.

You need to find the existing object from the list for that user. I would suggest that you swap your list for a map keyed on username.

Body:
So I'm Serializing an ArrayList of ArrayLists essentially but I'm running into an issue. To be honest I'm still pretty new to Java, I've tried so many different methods to fix this as well as searched relentlessly on this site and have not been successful. I know that the way I word things may be hard to follow along or is confusing so I'll post my code here to see. Sorry in advance for all the code. SuperUsers has an arraylist of LoginInfo, PasswordKeeper has an Arraylist of SuperUsers, and the SuperUser arraylist gets serialized in PasswordKeeper. but any changes made to the LoginInfo arraylist do not save and i cannot figure out why. If anyone can help I would really Appreciate it. Thanks

public class PasswordKeeper{

    private ArrayList<SuperUser> users;
    private static Scanner keyboard = new Scanner(System.in);

    public PasswordKeeper() {
        users = new ArrayList();
    }

    public void login() {
        try {
            // reads in SuperUser arraylist
            get();
        } catch (EOFException a) {
            System.out.println("You are the First User!");
        } catch (IOException b) {
            System.out.println(b);
        } catch (ClassNotFoundException c) {
            System.out.println(c);
        }
        boolean loopDisplay = true;
        while (loopDisplay) {
                existingUser = keyboard.next();
                existingPass = keyboard.next();
                SuperUser temp = new SuperUser(existingUser, existingPass);
                System.out.println();
                if (users.contains(temp)) {

                    // viewing superUser method
                    temp.display();
                    //saves after method call is over
                    try {
                        System.out.println("Saving.");
                        save(users);
                    } catch (IOException e) {
                        System.out.println(e);
                    }
                }
            }
            //This happens if there is a new user
            if(answer == 2){
            SuperUser tempNew = null;
            boolean cont = true;
            String newUser;
            String pass;
            while(cont){
                newUser = keyboard.nextLine();
                System.out.println();
                //System.out.println(users.size());

                tempNew = new SuperUser(newUser, pass);
                if(passValid(pass) == true){
                    if(makeSure(tempNew) == true){
                        System.out.println("Login Created!");
                        tempNew = new SuperUser(newUser, pass);
                        //actually being added to the arraylist
                        users.add(tempNew);
                        cont = false;
                    }
                }
            }
            //SuperUser.display method
            tempNew.display();
            try{
                System.out.println("Saving.");
                save(users);
            }catch(IOException e){
                System.out.println(e);
            }
        }
        }
    }
    //makeSure and passValid methods
    public boolean makeSure(SuperUser user){
    if(users.contains(user)){
        return false;
    }
    return true;
}

public boolean passValid(String pass){
        boolean passes = false;
        String upper = "(.*[A-Z].*)";
        String lower = "(.*[a-z].*)";
        String numbers = "(.*[0-9].*)";
        String special = "(.*[,~,!,@,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";

        if((pass.length()>15) || (pass.length() < 8)){
            System.out.println("Entry must contain over 8 characters\n" +
            "and less than 15.");
            passes = false;
        }if(!pass.matches(upper) || !pass.matches(lower)){
            System.out.println("Entry must contain at least one uppercase and lowercase");
            passes = false;
        }if(!pass.matches(numbers)){
                    System.out.println("Password should contain atleast one number.");
                    passes = false;
        }if(!pass.matches(special)){
                    System.out.println("Password should contain atleast one special character");
                    passes = false;
        }else{
            passes = true;
        }
        return passes;
    //serializable methods
    public void save(ArrayList<SuperUser> obj) throws IOException {

        File file = new File("userInformation.dat");
        FileOutputStream fileOut = new FileOutputStream(file, false);
        BufferedOutputStream buffedOutput = new BufferedOutputStream(fileOut);
        ObjectOutputStream out = new ObjectOutputStream(buffedOutput);
        out.writeObject(obj);
        out.close();
        fileOut.close();
    }

    public ArrayList<SuperUser> get() throws IOException, ClassNotFoundException {
        FileInputStream fileIn = new FileInputStream("userInformation.dat");
        BufferedInputStream buffedInput = new BufferedInputStream(fileIn);
        ObjectInputStream in = new ObjectInputStream(buffedInput);
        users = (ArrayList<SuperUser>) in.readObject();
        in.close();
        fileIn.close();
        return users;
    }

    public class SuperUser implements Serializable {
        private String userName;
        private String password;
        private static Scanner keyboard = new Scanner(System.in);
        private ArrayList<LoginInfo> info = new ArrayList();

        public SuperUser(String name, String pass) {
            userName = name;
            password = pass;
        }

        public String getUser() {
            return userName;
        }

        public void display() {

            String next = keyboard.next();
            //want to add data to LoginInfo arraylist
            if (next.equalsIgnoreCase("add")) {
                add();
            } else if (next.equalsIgnoreCase("delete")) {
                delete();
            } else if (numberCheck(next)) {
                int choice = (int) Integer.parseInt(next) - 1;
                edit(choice);
            //!!!! this: after doing this i lose whatever data i added
            //to the LoginInfo arraylist, right after this the
            //SuperUser arraylist gets saved. but the added data to
            //loginInfo does not
            } else if (next.equalsIgnoreCase("logout")) {
                System.out.println(info.size());
            }
        }

        public boolean numberCheck(String in) {
            try {
                Integer.parseInt(in);
            } catch (NumberFormatException e) {
                return false;
            }
            return true;
        }
        //method to add to the Arraylist
        public void add() {
            System.out.println("What is the website name?:");
            String trash = keyboard.nextLine();
            String webName = keyboard.nextLine();
            System.out.println("The Username?:");
            String webUsername = keyboard.nextLine();
            System.out.println("The Password?:");
            String webPass = keyboard.nextLine();
            info.add(new LoginInfo(webUsername, webPass, webName));
            System.out.println(info.size());
            //method goes back to display
            display();
        }
    }
}

Body:
Your problem is here

SuperUser temp = new  SuperUser(existingUser, existingPass);
    System.out.println();
    if (users.contains(temp)) {
        // viewing superUser method
        temp.display();

You create a temporary object which with the username and password.

Your 'users.contains()' method returns true because '.equals()' is based on the username, however the 'temp' object is a different instance to that in the list.

So when you call 'temp.display()' it is not calling on an object in the list, so no data changes will save.

You need to find the existing object from the list for that user. I would suggest that you swap your list for a map keyed on username.


问:
Button will call method from different class but regular method call will not
With the way I have things set up in my first iPad project, I've been curious why regular method calls aren't working the way I think they would.

In a view, inside initWithFrame I make a delegate pointer like this:

```<code>  mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];
</code>```

And make a button like this:

```<code>  CGRect backBTNFrame = CGRectMake(25, 30, 140, 52);
  backButton_video = [[UIButton alloc] init];
  backButton_video.frame = backBTNFrame;
  backBtnImg_video = [UIImage imageNamed:@"SHIP_button_back.png"];
  [backButton_video setImage:backBtnImg_video forState:UIControlStateNormal];
  backButton_video.backgroundColor = [UIColor clearColor];
  [self addSubview:backButton_video];

 [backButton_video addTarget:self
    action:@selector(kill_timers)
   forControlEvents:UIControlEventTouchUpInside];

 [backButton_video addTarget:del.switchVC
     action:@selector(gotoMain)
 forControlEvents:UIControlEventTouchUpInside];
</code>```

I click the button and it calls a method from a view controller:

```<code>- (void)gotoMain{

 NSLog(@"switch to main");

 for(UIView *v in [containerView subviews]) {
    [v removeFromSuperview];
 }

 MainMenu *mainMenu = [[MainMenu alloc] init];
 mainMenu.frame = CGRectMake(0, -20, 1024, 768);
 [containerView insertSubview:mainMenu atIndex:0];
 [mainMenu release];
}
</code>```

This gets rid of the view I was in, and adds the main menu view. This works fine.

However, if I make a delegate pointer like how it was before and call the self method kill_timers and the view controller method gotoMain, it will not work:

```<code> mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];

[self kill_timers];

[del.switchVC gotoMain];
</code>```

In the console I see the message that it kills the timer, which it does, but I have a NSLog ready to fire in the view controller, but nothing shows up. Just ain't happenin. Any clues? Why would the button and regular method call behave differently?

答:
That self in the ```<code>[self kill_timers];</code>``` literally means that the object (self) is told to do something. What you really want to do is tell your delegate to do something. This is not good design practice.

If you want your delegate to do something, then use NSNotificationCenter.

In your AppDelegate's applicationDidFinishLaunching:

```<code>[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(kill_timers)<br> name:@"Kill Timers"  object:nil];
</code>```

Then, when you want to call this created observer:

```<code>
[[NSNotificationCenter defaultCenter] postNotificationName:@"Kill Timers" object:nil];
</code>```

This will fire the method, without the messy design flaws associated with having multiple instances of your AppDelegate.

Body:
With the way I have things set up in my first iPad project, I've been curious why regular method calls aren't working the way I think they would.

In a view, inside initWithFrame I make a delegate pointer like this:

  mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];

And make a button like this:

  CGRect backBTNFrame = CGRectMake(25, 30, 140, 52);
  backButton_video = [[UIButton alloc] init];
  backButton_video.frame = backBTNFrame;
  backBtnImg_video = [UIImage imageNamed:@"SHIP_button_back.png"];
  [backButton_video setImage:backBtnImg_video forState:UIControlStateNormal];
  backButton_video.backgroundColor = [UIColor clearColor];
  [self addSubview:backButton_video];

 [backButton_video addTarget:self
    action:@selector(kill_timers)
   forControlEvents:UIControlEventTouchUpInside];

 [backButton_video addTarget:del.switchVC
     action:@selector(gotoMain)
 forControlEvents:UIControlEventTouchUpInside];

I click the button and it calls a method from a view controller:

- (void)gotoMain{

 NSLog(@"switch to main");

 for(UIView *v in [containerView subviews]) {
    [v removeFromSuperview];
 }

 MainMenu *mainMenu = [[MainMenu alloc] init];
 mainMenu.frame = CGRectMake(0, -20, 1024, 768);
 [containerView insertSubview:mainMenu atIndex:0];
 [mainMenu release];
}

This gets rid of the view I was in, and adds the main menu view. This works fine.

However, if I make a delegate pointer like how it was before and call the self method kill_timers and the view controller method gotoMain, it will not work:

 mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];

[self kill_timers];

[del.switchVC gotoMain];

In the console I see the message that it kills the timer, which it does, but I have a NSLog ready to fire in the view controller, but nothing shows up. Just ain't happenin. Any clues? Why would the button and regular method call behave differently?

Body:
That self in the
[self kill_timers];
 literally means that the object (self) is told to do something. What you really want to do is tell your delegate to do something. This is not good design practice.

If you want your delegate to do something, then use NSNotificationCenter.

In your AppDelegate's applicationDidFinishLaunching:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(kill_timers)
 name:@"Kill Timers"  object:nil];

Then, when you want to call this created observer:

[[NSNotificationCenter defaultCenter] postNotificationName:@"Kill Timers" object:nil];

This will fire the method, without the messy design flaws associated with having multiple instances of your AppDelegate.


问:
How to replace translator instance in slim framework?
I'm using slim and Laravel's illuminate/Translation. I'm new to all of this, I've found a solution to translate my pages but I'm having a problem when I'm trying to pass another translator instance(to change the translation of the page) to the container during run time to change the translation.
Here's what I'm doing:
I have a navigation bar with Twig like this:

```<code><li><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">lang<span class="caret"></span> </a>
                    <ul class="dropdown-menu">
                        <li><a href="{{path_for('en')}}" >english</a> </li>
                        <li><a href="{{path_for('fr')}}">french</a> </li>
                    </ul>
                    </li>
</code>```

and a language controller where I set the new instance of the translator to the container:

```<code>  public function getFrench($request, $response){
    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );
     // Register the french translator (set to "en" for English)
    $translator = new Translator($loader, "fr");

    $this->translator=$translator;

   }
</code>```

and this is how my container is set:

```<code>$container['translator']= function($container){

    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );
     // Register the french translator (set to "en" for English)
    $translator = new Translator($loader, "en");

    return $translator;
};
</code>```

**The view **  where I'm adding a translationExtension:

```<code>$container['view']= function($container){
    $view= new \Slim\Views\Twig(__DIR__ .'/../resources/views',['cache'=> false,]);

     // add translator functions to Twig
    $view->addExtension(new TranslatorExtension($container->get('translator')));

    return $view;

};
</code>```

I don't know if going about this the wrong way because I whatever I do I can't change the translation during runtime, I always get the translation that I set inside the container (in this case english), should I use globals instead of the controller way? and how would I go about this?

答:
You can use the Accept-Language-header to detect which language a user want to see. This you can do inside middleware.

Firstly you should remove the extension-adding from the container

```<code>$container['view']= function($container){
    $view= new \Slim\Views\Twig(__DIR__ .'/../resources/views',['cache'=> false,]);
    return $view;
};
</code>```

And then add the extension through a middleware, with the parsed language form the header:

```<code>$container = $app->getContainer();
$app->add(function (\Slim\Http\Request $request, $response, $next) use ($container) {
    $lang = $request->getHeader('Accept-Language');

    // $lang could be something like 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'
    // see above link for more information about parsing it
    $parsedLang = parseLang($lang);

    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );

    $translator = new Translator($loader, $parsedLang);

    // add the extension to twig
    $view = $container->get('view');
    $view->addExtension(new TranslatorExtension($translator));

    // execute the other middleware and the actual route
    return $next($request, $response);
});
</code>```

Body:
I'm using slim and Laravel's illuminate/Translation. I'm new to all of this, I've found a solution to translate my pages but I'm having a problem when I'm trying to pass another translator instance(to change the translation of the page) to the container during run time to change the translation.
Here's what I'm doing:
I have a navigation bar with Twig like this:

lang

english

french

and a language controller where I set the new instance of the translator to the container:

  public function getFrench($request, $response){
    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );
     // Register the french translator (set to "en" for English)
    $translator = new Translator($loader, "fr");

    $this->translator=$translator;

   }

and this is how my container is set:

$container['translator']= function($container){

    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );
     // Register the french translator (set to "en" for English)
    $translator = new Translator($loader, "en");

    return $translator;
};

**The view **  where I'm adding a translationExtension:

$container['view']= function($container){
    $view= new \Slim\Views\Twig(__DIR__ .'/../resources/views',['cache'=> false,]);

     // add translator functions to Twig
    $view->addExtension(new TranslatorExtension($container->get('translator')));

    return $view;

};

I don't know if going about this the wrong way because I whatever I do I can't change the translation during runtime, I always get the translation that I set inside the container (in this case english), should I use globals instead of the controller way? and how would I go about this?

Body:
You can use the Accept-Language-header to detect which language a user want to see. This you can do inside middleware.

Firstly you should remove the extension-adding from the container

$container['view']= function($container){
    $view= new \Slim\Views\Twig(__DIR__ .'/../resources/views',['cache'=> false,]);
    return $view;
};

And then add the extension through a middleware, with the parsed language form the header:

$container = $app->getContainer();
$app->add(function (\Slim\Http\Request $request, $response, $next) use ($container) {
    $lang = $request->getHeader('Accept-Language');

    // $lang could be something like 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'
    // see above link for more information about parsing it
    $parsedLang = parseLang($lang);

    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );

    $translator = new Translator($loader, $parsedLang);

    // add the extension to twig
    $view = $container->get('view');
    $view->addExtension(new TranslatorExtension($translator));

    // execute the other middleware and the actual route
    return $next($request, $response);
});


问:
how to keep program running after .mainloop()?
I'm trying to create a program which displays images using tkinter. The code I've written so far displays the image perfectly, however the program does not continue until the tkinter window is closed. I was wondering if there was any function instead of .mainloop() to keep the program running alongside the tkinter window? Any help much appreciated

```<code>window = Tk()
canvas1 = Canvas(window,height=600,width=600)
file = PhotoImage(file = 'GoogleDrive.png')
image = canvas1.create_image(300, 300, anchor = CENTER, image = file)
canvas1.pack()
canvas1.mainloop()

print ('\nA: Google Drive')
time.sleep(1)
print ('B: Google Slides')
time.sleep(1)
print ('C: Google Photos')
</code>```

答:
Tkinter is event driven.  This means that there must be an action (from the script or user) given to tkinter to change things.

The mainloop() function executes the window so there is no alternative to it.  Fortunately there are solutions:

If you want to perform actions alongside tkinter window(s) you have two options:

You can perform them all before mainloop() is called.

Or make them execute when a user performs an action in form of a button ect.

Or you can run functions in the background with threading or multiprocessing.

If you go for this option I would suggest threading because:

It's easy to use

You can communicate between different parts of the script.  You can struggle to do this in multithreading

However this depends entirely on the specific task.

In the example code you have given your best option is to call it before mainloop() is executed.  For example:

```<code>window = Tk()
canvas1 = Canvas(window,height=600,width=600)
file = PhotoImage(file = 'GoogleDrive.png')

image = canvas1.create_image(300, 300, anchor = CENTER, image = file)
canvas1.pack()
print ('\nA: Google Drive')
time.sleep(1)
print ('B: Google Slides')
time.sleep(1)
print ('C: Google Photos')
canvas1.mainloop()
</code>```

Although you could put it anywhere before mainloop().

Body:
I'm trying to create a program which displays images using tkinter. The code I've written so far displays the image perfectly, however the program does not continue until the tkinter window is closed. I was wondering if there was any function instead of .mainloop() to keep the program running alongside the tkinter window? Any help much appreciated

window = Tk()
canvas1 = Canvas(window,height=600,width=600)
file = PhotoImage(file = 'GoogleDrive.png')
image = canvas1.create_image(300, 300, anchor = CENTER, image = file)
canvas1.pack()
canvas1.mainloop()

print ('\nA: Google Drive')
time.sleep(1)
print ('B: Google Slides')
time.sleep(1)
print ('C: Google Photos')

Body:
Tkinter is event driven.  This means that there must be an action (from the script or user) given to tkinter to change things.

The mainloop() function executes the window so there is no alternative to it.  Fortunately there are solutions:

If you want to perform actions alongside tkinter window(s) you have two options:

You can perform them all before mainloop() is called.

Or make them execute when a user performs an action in form of a button ect.

Or you can run functions in the background with threading or multiprocessing.

If you go for this option I would suggest threading because:

It's easy to use

You can communicate between different parts of the script.  You can struggle to do this in multithreading

However this depends entirely on the specific task.

In the example code you have given your best option is to call it before mainloop() is executed.  For example:

window = Tk()
canvas1 = Canvas(window,height=600,width=600)
file = PhotoImage(file = 'GoogleDrive.png')

image = canvas1.create_image(300, 300, anchor = CENTER, image = file)
canvas1.pack()
print ('\nA: Google Drive')
time.sleep(1)
print ('B: Google Slides')
time.sleep(1)
print ('C: Google Photos')
canvas1.mainloop()

Although you could put it anywhere before mainloop().


问:
In C#, how can I know the file type from a byte[]?
I have a byte array filled from a file uploaded. But, in another part of the code, I need to know this file type uploaded from the byte[] so I can render the correct content-type to browser!

Thanks!!

答:
If you know it's a System.Drawing.Image, you can do:

```<code>public static string GetMimeTypeFromImageByteArray(byte[] byteArray)
{
   using (MemoryStream stream = new MemoryStream(byteArray))
   using (Image image = Image.FromStream(stream))
   {
       return ImageCodecInfo.GetImageEncoders().First(codec => codec.FormatID == image.RawFormat.Guid).MimeType;
   }
}
</code>```

Body:
If you know it's a System.Drawing.Image, you can do:

public static string GetMimeTypeFromImageByteArray(byte[] byteArray)
{
   using (MemoryStream stream = new MemoryStream(byteArray))
   using (Image image = Image.FromStream(stream))
   {
       return ImageCodecInfo.GetImageEncoders().First(codec => codec.FormatID == image.RawFormat.Guid).MimeType;
   }
}


问:
List of macOS text editors and code editors
I searched for this and found Maudite's question about text editors but they were all for Windows.

As you have no doubt guessed, I am trying to find out if there are any text/code editors for the Mac besides what I know of. I'll edit my post to include editors listed.

Free

Textwrangler

Xcode

Mac Vim

Aquamacs and closer to the original EMacs

JEdit

Editra

Eclipse

NetBeans

Kod

TextMate2 - GPL

Brackets

Atom.io

Commercial

Textmate

BBEdit

SubEthaEdit

Coda

Sublime Text 2

Smultron

WebStorm

Peppermint

Articles related to the subject

Faceoff, which is the best text editor ever?

Maceditors.com, mac editors features compared

Thank you everybody that has added suggestions.

答:
Mac UltraEdit is out as of 2011 - http://www.ultraedit.com/products/mac-text-editor.html

Very much a 1.0-ish feel and sluggish (though labeled 2.0.2), has all the great features of the Windows version (column edits, true hex mode, full out macro recording, and plugins for every language under the sun).

OwnerDisplayName: Teifion


问:
Replace variable products price range with "From:" + lowest price in WooCommerce
In WooCommerce when a Variable product has variations with different prices it displays a price range with 2 amounts: For example 89.00 - 109.00.

I'd like to change it, displaying only "From: " and the lowest price like for example From: 89.00 (removing the Max price).

("Fra: " means from in my language, just to clarify).

Here is the code that I have tried:

```<code>// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'Fra: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'Fra: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice ) {
$price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
}
return $price;
}
</code>```

This code doesn't work. Whenever I add it nothing happens.

What do I need to change, to get "From: " + the Min price instead?

答:
Your code is a bit incomplete as the hook and the function are missing…

Here is the correct way to make it works for your variable products:

```<code>add_filter( 'woocommerce_get_price_html', 'change_variable_products_price_display', 10, 2 );
function change_variable_products_price_display( $price, $product ) {

    // Only for variable products type
    if( ! $product->is_type('variable') ) return $price;

    $prices = $product->get_variation_prices( true );

    if ( empty( $prices['price'] ) )
        return apply_filters( 'woocommerce_variable_empty_price_html', '', $product );

    $min_price = current( $prices['price'] );
    $max_price = end( $prices['price'] );
    $prefix_html = '<span class="price-prefix">' . __('Fra: ') . '</span>';

    $prefix = $min_price !== $max_price ? $prefix_html : ''; // HERE the prefix

    return apply_filters( 'woocommerce_variable_price_html', $prefix . wc_price( $min_price ) . $product->get_price_suffix(), $product );
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.

Body:
In WooCommerce when a Variable product has variations with different prices it displays a price range with 2 amounts: For example 89.00 - 109.00.

I'd like to change it, displaying only "From: " and the lowest price like for example From: 89.00 (removing the Max price).

("Fra: " means from in my language, just to clarify).

Here is the code that I have tried:

// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'Fra: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'Fra: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice ) {
$price = '' . $saleprice . $product->get_price_suffix() . ' ' . $price . $product->get_price_suffix() . '';
}
return $price;
}

This code doesn't work. Whenever I add it nothing happens.

What do I need to change, to get "From: " + the Min price instead?

Body:
Your code is a bit incomplete as the hook and the function are missing…

Here is the correct way to make it works for your variable products:

add_filter( 'woocommerce_get_price_html', 'change_variable_products_price_display', 10, 2 );
function change_variable_products_price_display( $price, $product ) {

    // Only for variable products type
    if( ! $product->is_type('variable') ) return $price;

    $prices = $product->get_variation_prices( true );

    if ( empty( $prices['price'] ) )
        return apply_filters( 'woocommerce_variable_empty_price_html', '', $product );

    $min_price = current( $prices['price'] );
    $max_price = end( $prices['price'] );
    $prefix_html = '<span class="price-prefix">' . __('Fra: ') . '</span>';

    $prefix = $min_price !== $max_price ? $prefix_html : ''; // HERE the prefix

    return apply_filters( 'woocommerce_variable_price_html', $prefix . wc_price( $min_price ) . $product->get_price_suffix(), $product );
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.


问:
How to keep :active css style after click a button
Once the button is clicked I want it to stay with the active style instead of going back to normal style.  Can this be done with CSS please? Im using blurb button from DIVI Theme (WordPress). Please help me!

code:

    #blurb-hover.et_pb_blurb .et_pb_blurb_content
    .et_pb_main_blurb_image .et-pb-icon:hover {
           color: red !important; }

    #blurb-hover.et_pb_blurb .et_pb_blurb_content
    .et_pb_main_blurb_image .et-pb-icon:selected {
      background-color: #ff4b46;
      color: #fff; }

    #blurb-hover.et_pb_blurb .et_pb_blurb_content
    .et_pb_main_blurb_image .et-pb-icon:active {
        color: white !important;
       background-color: red;
        width: 140px;
        height: 100px; }

```

答:
We're going to to be using a hidden checkbox.

This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

HTML

```<code><input type="checkbox" id="activate-div">
  <label for="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>
  </label>
</code>```

CSS

```<code>#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}
</code>```

To make button change content:

HTML

```<code><input type="checkbox" id="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>

<label for="activate-div">
   //MY BUTTON STUFF
</label>
</code>```

CSS

```<code>#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}
</code>```

Hope it helps!!

Body:
We're going to to be using a hidden checkbox.

This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

HTML

<input type="checkbox" id="activate-div">
  <label for="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>
  </label>

CSS

#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}

To make button change content:

HTML

<input type="checkbox" id="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>

<label for="activate-div">
   //MY BUTTON STUFF
</label>

CSS

#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}

Hope it helps!!