问:
Load config.json with Angular2: Getting an error: DI Error at NoProviderError.ZoneAwareError
According to some post, I wanted to load the config.json file in my angular2 app but got the error above in the frontend.

Here what I have done:

app\app.module.ts

```<code>import { ConfigService } from './service/config-service';

@NgModule({
  providers: [
    { provide: APP_INITIALIZER, useFactory: (config: ConfigService) => () => config.load(), deps: [ConfigService], multi: true }
 ]
})
</code>```

app\service\config-service.ts

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

@Injectable()
export class ConfigService {
    private _config: Object;

    constructor(private http: Http) {
        console.log("Config Created");
    }

    load() {
        // Get the Config
        return new Promise(function(fulfill, reject) {
            // Get the conf
            this.http.get('/app/config.json')  // path of your config.json file
            .map(res => res.json())
            .subscribe(config => {
              this._config = config;
              fulfill(true);
            });
        });
    }

    getCentralSystemServer() {
        return this._config["CentralSystemServer"];
    }
}
</code>```

Let me know if you encountered the same kind of issue.

Thanks,
Serge.

答:
Its because you did not configure your service under providers array </p>

```<code>providers: [ ConfigService,////////////////change/////////////////////////////
    { provide: APP_INITIALIZER, useFactory: (config: ConfigService) => () => config.load(), deps: [ConfigService], multi: true }
 ]
</code>```

Body:
According to some post, I wanted to load the config.json file in my angular2 app but got the error above in the frontend.

Here what I have done:

app\app.module.ts

import { ConfigService } from './service/config-service';

@NgModule({
  providers: [
    { provide: APP_INITIALIZER, useFactory: (config: ConfigService) => () => config.load(), deps: [ConfigService], multi: true }
 ]
})

app\service\config-service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';

@Injectable()
export class ConfigService {
    private _config: Object;

    constructor(private http: Http) {
        console.log("Config Created");
    }

    load() {
        // Get the Config
        return new Promise(function(fulfill, reject) {
            // Get the conf
            this.http.get('/app/config.json')  // path of your config.json file
            .map(res => res.json())
            .subscribe(config => {
              this._config = config;
              fulfill(true);
            });
        });
    }

    getCentralSystemServer() {
        return this._config["CentralSystemServer"];
    }
}

Let me know if you encountered the same kind of issue.

Thanks,
Serge.

Body:
Its because you did not configure your service under providers array

providers: [ ConfigService,////////////////change/////////////////////////////
    { provide: APP_INITIALIZER, useFactory: (config: ConfigService) => () => config.load(), deps: [ConfigService], multi: true }
 ]


来源: stackexchange

问:
key binding issues when hosting WPF in Win Form
we have a WPF component (User Control) that's hosted in a Win Form through ElementHost. the WPF component is defined as the ElementHost's Child through

ElementHostControl.Child = wpfFrame

there are certain key bindings we want to pass in from the Win Form to WPF form. we are doing so through KeyBinding(). then we assign the keybinding to the
WPFFrame.InputBindings.add(curBinding);

it's kind working with most key combinations although I didn't test all of them. but Ctrl+B, Shift+P etc. seems all working fine.

But I try Shift+(Left Arrow key), it's not working. what's interesting is when I try it in standalone WPF application then it's doing the job as expected.

I made sure the data flow through the exactly same code but why Shift+P works while Shift+ <- doesn't? now I set a breakpoint in the WPF Commend executed and run it from Win Form. I use key binding to trigger another command then use Ctrl+<- to trigger the problematic command it actually "sometimes" working. if I remove breakpoint and do Ctrl+<- then it never triggers the associated command.

I suspect it's an integration issue in between WPF and Win form since Shift+<- works in WPF itself.

any input is appreciated.

答:
it's indeed a focusing issue. setting a break point and this line:
var v = Keyboard.FocusedElement;

at runtime shows the focus was stolen by various elements. I need to hand pick couple of them and set
Focusable="False"
in XAML. issue fixed!

ContentLicense: CC BY-SA 3.0


问:
Convert list of lists with different lengths to a numpy array
I have list of lists with different lengths (e.g. [[1, 2, 3], [4, 5], [6, 7, 8, 9]]) and want to convert it into a numpy array of integers. I understand that 'sub' arrays in numpy multidimensional array must be the same length. So what is the most efficient way to convert such a list as in example above into a numpy array like this [[1, 2, 3, 0], [4, 5, 0, 0], [6, 7, 8, 9]], i.e. completed with zeros?

答:
Here's a @Divakar type of answer:

```<code>In [945]: ll = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
In [946]: lens = [len(l) for l in ll]      # only iteration
In [947]: lens
Out[947]: [3, 2, 4]
In [948]: maxlen=max(lens)
In [949]: arr = np.zeros((len(ll),maxlen),int)
In [950]: mask = np.arange(maxlen) < np.array(lens)[:,None] # key line
In [951]: mask
Out[951]:
array([[ True,  True,  True, False],
       [ True,  True, False, False],
       [ True,  True,  True,  True]], dtype=bool)
In [952]: arr[mask] = np.concatenate(ll)    # fast 1d assignment
In [953]: arr
Out[953]:
array([[1, 2, 3, 0],
       [4, 5, 0, 0],
       [6, 7, 8, 9]])
</code>```

For large lists it has the potential of being faster.  But it's harder to understand and/or recreate.

Convert Python sequence to NumPy array, filling missing values - has a good post by Divakar.  itertools.zip_longest is also mentioned.  This could be cited as a duplicate.

Body:
Here's a @Divakar type of answer:

In [945]: ll = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
In [946]: lens = [len(l) for l in ll]      # only iteration
In [947]: lens
Out[947]: [3, 2, 4]
In [948]: maxlen=max(lens)
In [949]: arr = np.zeros((len(ll),maxlen),int)
In [950]: mask = np.arange(maxlen) < np.array(lens)[:,None] # key line
In [951]: mask
Out[951]:
array([[ True,  True,  True, False],
       [ True,  True, False, False],
       [ True,  True,  True,  True]], dtype=bool)
In [952]: arr[mask] = np.concatenate(ll)    # fast 1d assignment
In [953]: arr
Out[953]:
array([[1, 2, 3, 0],
       [4, 5, 0, 0],
       [6, 7, 8, 9]])

For large lists it has the potential of being faster.  But it's harder to understand and/or recreate.

Convert Python sequence to NumPy array, filling missing values - has a good post by Divakar.  itertools.zip_longest is also mentioned.  This could be cited as a duplicate.


问:
How Immutability is Achieved in Scala Streams?
It might become silly but I have question regarding to Scala Stream evaluation in immutable fashion.

Lets say I have a Stream like this (All lines executed in repl);

```<code>val a = Stream(1,2,3,4,5,6,7,8,9,10);
</code>```

a: scala.collection.immutable.Stream[Int] = Stream(1, ?)

When I run following lines;

```<code>a(3);
a
</code>```

I get ;

scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, ?)

My first question is how this immutable structure gets changed ? I mean if did like this (assuming variable 'a' defined as 'var');
a = a(3) I might expect such result.

My other question is when I run following lines;

```<code>val a = Stream(1,2,3,4,5,6,7,8,9,10);
</code>```

a: scala.collection.immutable.Stream[Int] = Stream(1, ?)

```<code>val b = a;
</code>```

b: scala.collection.immutable.Stream[Int] = Stream(1, ?)

```<code>b(5);
</code>```

scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, 5, 6, ?)

```<code>a
</code>```

scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, 5, 6, ?)

As you can see in last part after executing 'a', its seems changed again.

If I try this kind of assignment with List type (as far as I know List is strict version of Stream) and do some transformation like drop,take etc.)

```<code>val a = List(1,2,3,4,5)
val b = a;
b.dropRight(1)
</code>```

variable 'a' and 'b' still is still List(1,2,3,4,5)

So how this happened and what is the point that I'm missing ?

答:
Scala Streams provide memoization - they are like lazy lists, but once elements have been generated, they are stored for future retrieval.

So when you "force" the Stream b to evaluate some of its elements by requesting the element at index 5, the original Stream a (which is the same Stream object) is also forced.

Key point: doing this doesn't modify the stream (it remains immutable), it just changes which elements have been evaluated and are memoized.

Your Stream(1,?) and Stream(1,2,3,4,5,6,?) are the same stream, just evaluated to a different degree:

```<code>scala> val a = Stream(1,2,3,4,5,6,7,8,9,10);
a: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> val b = a

scala> a(3)
res9: Int = 4

scala> a
res10: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, ?)

scala> b
res11: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, ?)

scala> Stream(1,2,3,4,5,6,7,8,9,10) == a
res12: Boolean = true

scala> Stream(1,2,3,4,5,6,7,8,9,10) == b
res13: Boolean = true
</code>```

Body:
It might become silly but I have question regarding to Scala Stream evaluation in immutable fashion.

Lets say I have a Stream like this (All lines executed in repl);

val a = Stream(1,2,3,4,5,6,7,8,9,10);

a: scala.collection.immutable.Stream[Int] = Stream(1, ?)

When I run following lines;

a(3);
a

I get ;

scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, ?)

My first question is how this immutable structure gets changed ? I mean if did like this (assuming variable 'a' defined as 'var');
a = a(3) I might expect such result.

My other question is when I run following lines;

val a = Stream(1,2,3,4,5,6,7,8,9,10);

a: scala.collection.immutable.Stream[Int] = Stream(1, ?)

val b = a;

b: scala.collection.immutable.Stream[Int] = Stream(1, ?)

b(5);

scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, 5, 6, ?)

a

scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, 5, 6, ?)

As you can see in last part after executing 'a', its seems changed again.

If I try this kind of assignment with List type (as far as I know List is strict version of Stream) and do some transformation like drop,take etc.)

val a = List(1,2,3,4,5)
val b = a;
b.dropRight(1)

variable 'a' and 'b' still is still List(1,2,3,4,5)

So how this happened and what is the point that I'm missing ?

Body:
Scala Streams provide memoization - they are like lazy lists, but once elements have been generated, they are stored for future retrieval.

So when you "force" the Stream b to evaluate some of its elements by requesting the element at index 5, the original Stream a (which is the same Stream object) is also forced.

Key point: doing this doesn't modify the stream (it remains immutable), it just changes which elements have been evaluated and are memoized.

Your Stream(1,?) and Stream(1,2,3,4,5,6,?) are the same stream, just evaluated to a different degree:

scala> val a = Stream(1,2,3,4,5,6,7,8,9,10);
a: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> val b = a

scala> a(3)
res9: Int = 4

scala> a
res10: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, ?)

scala> b
res11: scala.collection.immutable.Stream[Int] = Stream(1, 2, 3, 4, ?)

scala> Stream(1,2,3,4,5,6,7,8,9,10) == a
res12: Boolean = true

scala> Stream(1,2,3,4,5,6,7,8,9,10) == b
res13: Boolean = true


问:
Query MySql database in Docker
I have a docker container with mariadb, and have created a database my_db in it (through an external script in a different container). How can I run SQL queries on my_db now from the command line? I just want to do

select * from my_table

from the terminal that is running the container.

答:
Easiest way is to exec into the container and execute the query using the mysql client, given the clients installed. </p>

```<code>docker exec -it CONTAINER_NAME mysql -p -e 'QUERY' DB_NAME
</code>```

Title: Query MySql database in Docker

Body:
Easiest way is to exec into the container and execute the query using the mysql client, given the clients installed.

docker exec -it CONTAINER_NAME mysql -p -e 'QUERY' DB_NAME


问:
What happens if extJS trial expires?
I am using extJS trial to learn. In few days, my trial shall expire. What it really means if trial expires. Does CMD tool stop building extJS or there is something else which I need to consider. </p>

答:
"You acknowledge that trial and/or beta software might place watermarks on output, contain limited functionality, function for a limited period of time, or limit the functionality or time of functioning of any output. Access to and/or use of any files or output created with such software is entirely at your own risk. we are licensing the software on an “as is” basis at your own risk and we disclaim any warranty or liability to you of any kind."

https://www.sencha.com/legal/sencha-software-license-agreement/

Title: What happens if extJS trial expires?


问:
Flask App using SQLAlcehmy: How to detect external changes committed to the database?
I have PhpMyAdmin to view and edit a database and a Flask + SQLAlchemy app that uses a table from this database. Everything is working fine and I can read/write to the database from the flask app. However, If I make a change through phpmyadmin, this change is not detected by SQLAlchmey. The only to get those changes is by manually refreshing SQLAlchmey connection

My Question is how to tell SQLAlchemy to reload/refresh its Database connection?

答:
To make sure that the SQLAlchemy engine reads the committed changes to the database, you have to set the isolation level :

```<code>engine = create_engine(
                "mysql://scott:tiger@localhost/test",
                isolation_level="READ UNCOMMITTED"
            )
</code>```

You can read more about isolation levels here and here is the official guide for SQLAlchemy docs (See fist Item)

Body:
To make sure that the SQLAlchemy engine reads the committed changes to the database, you have to set the isolation level :

engine = create_engine(
                "mysql://scott:tiger@localhost/test",
                isolation_level="READ UNCOMMITTED"
            )

You can read more about isolation levels here and here is the official guide for SQLAlchemy docs (See fist Item)


问:
nodejs redirecting data from ajax to ejs
I'm using ajax post on client side to post the user details to database. On server side, i handle my post request as :

```<code>      app.post("/journey",function(req,res){
      var obj = JSON.stringify(req.body);
      var dt = JSON.parse(obj);
      //console.log(dt.zip)
      var journey_details = new Journey({
        zip : dt.zip,
        age65 : dt.age65,
        first_name : dt.fname,
        last_name : dt.lname
      });
      journey_details.save(function (err) {
     if (err) {
       return err;
     }
     else {
       console.log("Journey details saved");
       // i use some api here to get json data named parsedData
       //since i've to display the name and parsedData on a new page, i send the data to front end javascript as
       res.send({redirect: '/profile', first_name : dt.fname, last_name : dt.lname, parsedData :  parsedData});
    });
    });
</code>```

Since i'm using ajax post, i redirect on ajax success. Once i get the above data, i redirect it to a new profile ejs page using

```<code>    var final_url = "http://localhost:3000" + data.redirect +"/"+data.first_name + "/" + data.last_name;
    window.location.replace(final_url);
</code>```

which will redirect them to localhost:3000/profile/fname/lname or may be i can use some unique id or anything like that in url
and it is handled in my profile ejs page

But i'd also want to send the parsedData to my profile ejs page. Since. parsedData has multiple json object with many fields, i don't think i can send it via url as :

```<code>    var final_url = "http://localhost:3000" + data.redirect +"/"+data.first_name + "/" + data.last_name + "/"+data.parsedData;
    window.location.replace(final_url);
</code>```

Is there any way so that i scan send it other than as in urlheader so that as i can access the parsedData as easily as i access fname and lname below:

```<code>    app.get("/profile/:firstname/:lastname",function(req,res){
    console.log(req.params.firstname);
    res.render("profile", {firstname : req.params.firstname,lastname : req.params.lastname}) // i want parsedData here

  });
</code>```

答: GET HTTP requests are not intended for the big url data, but using POST request in this case is logical error. Maybe the best way for you would be to pass only your journey_details.id to redirect url, without any data. And on the server side you will get this record and use all data you need. </p>

Body:
I'm using ajax post on client side to post the user details to database. On server side, i handle my post request as :

      app.post("/journey",function(req,res){
      var obj = JSON.stringify(req.body);
      var dt = JSON.parse(obj);
      //console.log(dt.zip)
      var journey_details = new Journey({
        zip : dt.zip,
        age65 : dt.age65,
        first_name : dt.fname,
        last_name : dt.lname
      });
      journey_details.save(function (err) {
     if (err) {
       return err;
     }
     else {
       console.log("Journey details saved");
       // i use some api here to get json data named parsedData
       //since i've to display the name and parsedData on a new page, i send the data to front end javascript as
       res.send({redirect: '/profile', first_name : dt.fname, last_name : dt.lname, parsedData :  parsedData});
    });
    });

Since i'm using ajax post, i redirect on ajax success. Once i get the above data, i redirect it to a new profile ejs page using

    var final_url = "http://localhost:3000" + data.redirect +"/"+data.first_name + "/" + data.last_name;
    window.location.replace(final_url);

which will redirect them to localhost:3000/profile/fname/lname or may be i can use some unique id or anything like that in url
and it is handled in my profile ejs page

But i'd also want to send the parsedData to my profile ejs page. Since. parsedData has multiple json object with many fields, i don't think i can send it via url as :

    var final_url = "http://localhost:3000" + data.redirect +"/"+data.first_name + "/" + data.last_name + "/"+data.parsedData;
    window.location.replace(final_url);

Is there any way so that i scan send it other than as in urlheader so that as i can access the parsedData as easily as i access fname and lname below:

    app.get("/profile/:firstname/:lastname",function(req,res){
    console.log(req.params.firstname);
    res.render("profile", {firstname : req.params.firstname,lastname : req.params.lastname}) // i want parsedData here

  });


问:
Why can we not return a structure to a function?
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

```<code>#include <stdio.h>

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}
</code>```

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

答:
```<code>#include<stdio.h>

struct distance
{
    int feet;
    float inch;
};

struct distance d1,d2,d3;

struct distance add(struct distance d1, struct distance d2);

int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);

}

 struct distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    while(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
        return d3;
    }
}
</code>```

Yes got it! here is the final output for the following inputs
inputs:

11

2.3
11
10
and here is the output:
sum of distances= 23'-0.3"

Body:
Why can we not return a structure as a return value? I would also like to print it as well? I want to print the variables of the structure returned.

#include <stdio.h>

struct distance
{
    int feet;
    float inch;
};

distance add(struct distance d1,struct distance d2);

distance d3;
int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);
    return dist3;
}

 distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    if(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
    }
}

The following error message is displayed
prog.c:7:1: error: unknown type name ‘distance’
 distance add(struct distance d1,struct distance d2);

Body:
#include<stdio.h>

struct distance
{
    int feet;
    float inch;
};

struct distance d1,d2,d3;

struct distance add(struct distance d1, struct distance d2);

int main()
{
    struct distance dist1, dist2,dist3;
    printf("first distance\n");
    scanf("%d",&dist1.feet);
    scanf("%f",&dist1.inch);
    printf("second distance\n");
    scanf("%d",&dist2.feet);
    scanf("%f",&dist2.inch);
    dist3 = add(dist1,dist2);
    printf("sum of distances= %d\'-%.1f\"",dist3.feet,dist3.inch);

}

 struct distance add(struct distance d1,struct distance d2){
    //Adding distances d1 and d2 and storing it in d3
    d3.feet = d2.feet+d1.feet;
    d3.inch = d2.inch+d1.inch;
    while(d3.inch>12){
        d3.inch-=12;
        ++d3.feet;
        return d3;
    }
}

Yes got it! here is the final output for the following inputs
inputs:

11

2.3
11
10
and here is the output:
sum of distances= 23'-0.3"


问:
How do you tell if an imported library ever gets use by the end user?
I'm pretty new to software but I have a strong stats background and naturally I want everything to tell me how useful it really is.

At my work we have a pretty large web app that makes calls for big files.  I would really like to start paring down on what is called and used but I am not sure where to start because I am not sure what files are actually getting used.

We have millions of visitors that use our app every month.  We are using Angular 1 and Foundations along with a bunch of other things.  If it is possible I would like to track if a foundations or angular library is requested, the size of the file, and if it was used.

Has anyone done something similar to this before?  I know how to check and see if a function is used but I'm not sure the best way to get started on something like this.

答:
Analyze any logs you can find

You can start by analyizing the server logs, if your server is using apache the logs will be in /var/log/apache2

If your server is on tomcat in java it would be in catalina.out.

Reguardless once you get the log files, you will want to run a regular expression or an endswith on the logs to get logs ending in .js.

A quick python script should get this done

```<code>from collections import defaultdict
freq = defaultdict(lambda:0);

with open("mylogfile.txt", "r") as f:
    array = []
    for line in f:
         if (line.endswith(('.js', '.css')):
            freq[line] += 1;
for key,val in freq.iteritems():
    print (key,val);
</code>```

Body:
Analyze any logs you can find

You can start by analyizing the server logs, if your server is using apache the logs will be in /var/log/apache2

If your server is on tomcat in java it would be in catalina.out.

Reguardless once you get the log files, you will want to run a regular expression or an endswith on the logs to get logs ending in .js.

A quick python script should get this done

from collections import defaultdict
freq = defaultdict(lambda:0);

with open("mylogfile.txt", "r") as f:
    array = []
    for line in f:
         if (line.endswith(('.js', '.css')):
            freq[line] += 1;
for key,val in freq.iteritems():
    print (key,val);


问:
Perl6: Match elements in a list with another list
I have a list of numbers L. There is another list of numbers M. I need to return a list L' of numbers found in both L and M.

Edit: Mathematically, I am looking for Multiset intersection.

Example:

L  = 3, 1, 4, 1, 5, 9, 2, 6

  M  = 9, 7, 1, 2, 1, 1

  L' = 9, 1, 2, 1

I wrote the following code for that:

```<code>my @some-numbers = 3, 1, 4, 1, 5, 9, 2, 6;
my @to-match     = 9, 7, 1, 2, 1, 1;
my @matched;

my %histogram;
for @some-numbers -> $n { %histogram{$n}++ };

for @to-match -> $n {
    next if not defined %histogram{$n};
    if %histogram{$n} > 0 {
        push @matched, $n;
        %histogram{$n}--;
    }
};

say @matched;
</code>```

While it achieves the purpose, I was wondering whether there was an idiomatic Perl6 way of doing this?

Some background: I have been trying to learn Perl6 and Python together, and solve the same puzzles in both the languages. Python offered a particularly pleasing solution for the above problem. To my beginner eyes at least :)

答:
You can try this:

```<code>use v6;

my @some_numbers = 3, 1, 4, 1, 5, 9, 2, 6;
my @to_match     = 9, 7, 1, 2, 1, 1;
my %seen  = map { $_ => 1 }, @to_match;
my @matched = grep { %seen{$_}:exists }, @some_numbers;
say @matched;
</code>```

Output:

```<code>[1 1 9 2]
</code>```

Body:
I have a list of numbers L. There is another list of numbers M. I need to return a list L' of numbers found in both L and M.

Edit: Mathematically, I am looking for Multiset intersection.

Example:

L  = 3, 1, 4, 1, 5, 9, 2, 6

  M  = 9, 7, 1, 2, 1, 1

  L' = 9, 1, 2, 1

I wrote the following code for that:

my @some-numbers = 3, 1, 4, 1, 5, 9, 2, 6;
my @to-match     = 9, 7, 1, 2, 1, 1;
my @matched;

my %histogram;
for @some-numbers -> $n { %histogram{$n}++ };

for @to-match -> $n {
    next if not defined %histogram{$n};
    if %histogram{$n} > 0 {
        push @matched, $n;
        %histogram{$n}--;
    }
};

say @matched;

While it achieves the purpose, I was wondering whether there was an idiomatic Perl6 way of doing this?

Some background: I have been trying to learn Perl6 and Python together, and solve the same puzzles in both the languages. Python offered a particularly pleasing solution for the above problem. To my beginner eyes at least :)

Body:
You can try this:

use v6;

my @some_numbers = 3, 1, 4, 1, 5, 9, 2, 6;
my @to_match     = 9, 7, 1, 2, 1, 1;
my %seen  = map { $_ => 1 }, @to_match;
my @matched = grep { %seen{$_}:exists }, @some_numbers;
say @matched;

Output:

[1 1 9 2]


问:
find number of repeating substrings in a string
I am looking for an algorithm that will find the number of repeating substrings in a single string.

For this, I was looking for some dynamic programming algorithms but didn't find any that would help me. I just want some tutorial on how to do this.

Let's say I have a string ABCDABCDABCD. The expected output for this would be 3, because there is ABCD 3 times.

For input AAAA, output would be 4, since A is repeated 4 times.

For input ASDF, output would be 1, since every individual character is repeated 1 time only.

I hope that someone can point me in the right direction. Thank you.

答:
I am taking the following assumptions:

The repeating substrings must be consecutive. That is, in case of ABCDABC, ABC would not count as a repeating substring, but it would in case of ABCABC.

The repeating substrings must be non-overalpping. That is, in case of ABCABC, ABC would not count as a repeating substring.

In case of multiple possible answers, we want the one with the maximum value. That is, in the case of AAAA, the answer should be 4 (a is the substring) rather than 2 (aa is the substring).

Under these assumptions, the algorithm is as follows:

Let the input string be denoted as inputString.

Calculate the KMP failure function array for the input string. Let this array be denoted as failure[]. This operation if of linear time complexity with respect to the length of the string. So, by definition, failure[i] denotes the length of the longest proper-prefix of the substring inputString[0....i] that is also a proper-suffix of the same substring.

Let len = inputString.length - failure.lastIndexValue. At this point, we know that if there is any repeating string at all, then it has to be of this length len. But we'll need to check for that; First, just check if len perfectly divides inputString.length (that is, inputString.length % len == 0). If yes, then check if every consecutive (non-overlapping) substring of len characters is the same or not; this operation is again of linear time complexity with respect to the length of the input string.

If it turns out that every consecutive non-overlapping substring  is the same, then the answer would be = inputString.length/ len. Otherwise, the answer is simply inputString.length, as there is no such repeating substring present.

The overall time complexity would be O(n), where n is the number of characters in the input string.

A sample code for calculating the KMP failure array is given here.

For example,

Let the input string be abcaabcaabca.

Its KMP failure array would be - [0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8].

So, our len = (12 - 8) = 4.

And every consecutive non-overlapping substring of length 4 is the same (abca).

Therefore the answer is 12/4 = 3. That is, abca is repeated 3 times repeatedly.


问:
populate html table with PHP via ajax in the same file
I'm using PHP to populate an HTML table with random numbers on page load. When button is clicked, I want to re-populate the table with new numbers by calling PHP via an ajax request. Problem is I can't use (or at least really want to avoid using) external files : PHP must be called via ajax request in the same file.

File is index.php and contains following simplified PHP code :

```<code><?php
    //code to be executed via ajax call should be placed here ?
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table">
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
<BODY>
</code>```

Here is my current ajax request :

```<code><script type="text/javascript">
function send_ajax() {
  console.log('btn clicked');
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest(); //code for IE7+, Firefox, Chrome, Opera, Safari
  }
  else {
    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //code for IE6, IE5
  }
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log('data sent');
    }
  }
  xmlhttp.open('POST', 'index.php', true);
  //xmlhttp.send(document.getElementById('input').value);
}

document.getElementById('btn').addEventListener('click', send_ajax, false);
</script>
</code>```

I'm sure I'm missing something obvious, but I have no idea how I should adapt my php code and ajax request to repopulate the table when receiving ajax call in the same file.

(Note : I know it would be very easy using external files, but this scenario is a typical example of what I need to do with ajax and PHP for more complex tasks over dozens of different files).

答:
you can check for isset($_POST['variable']) and return data in json format

e.g

```<code><?php
    //code to be executed via ajax call
  if(isset($_POST['query']) && $_POST['query'] != "")
   {
       return json_encode(mt_rand(-10, 10));
   }
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table">
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
<BODY>
</code>```

//here is the ajax code

```<code><script type="text/javascript">

    function send_ajax() {
      console.log('btn clicked');
      if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest(); //code for IE7+, Firefox, Chrome, Opera, Safari
      }
      else {
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //code for IE6, IE5
      }
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          console.log('data sent');
        }
      }
      xmlhttp.open('POST', 'index.php', true);
      var data = new FormData();
      data.append('query',document.getElementById('input').value);
      //you can append more data in same manner for sending more data
      xmlhttp.send(data);
    }

    document.getElementById('btn').addEventListener('click', send_ajax, false);
    </script>
</code>```

Body:
I'm using PHP to populate an HTML table with random numbers on page load. When button is clicked, I want to re-populate the table with new numbers by calling PHP via an ajax request. Problem is I can't use (or at least really want to avoid using) external files : PHP must be called via ajax request in the same file.

File is index.php and contains following simplified PHP code :

<?php
    //code to be executed via ajax call should be placed here ?
?>
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">

    <title>PHP test</title>

    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '
';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo ''. $values[$v] .'	';
      }
      echo '
';
   ?>

  <button id="btn">Generate new numbers</button>

Here is my current ajax request :

I'm sure I'm missing something obvious, but I have no idea how I should adapt my php code and ajax request to repopulate the table when receiving ajax call in the same file.

(Note : I know it would be very easy using external files, but this scenario is a typical example of what I need to do with ajax and PHP for more complex tasks over dozens of different files).

Body:
you can check for isset($_POST['variable']) and return data in json format

e.g

<?php
    //code to be executed via ajax call
  if(isset($_POST['query']) && $_POST['query'] != "")
   {
       return json_encode(mt_rand(-10, 10));
   }
?>
<!DOCTYPE html>

<HTML>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width">
<HEAD>
    <title>PHP test</title>
</HEAD>

<BODY>
  <table id="table">
    <?php //problem : only works once in page load
      $howMany = 10;

      $values = array();

      echo '<tr>';
      for ($v = 0; $v < $howMany; $v++) {
        $values[$v] = mt_rand(-10, 10);
        echo '<td>'. $values[$v] .'</td>';
      }
      echo '</tr>';
   ?>
  </table>

  <button id="btn">Generate new numbers</button>
<BODY>

//here is the ajax code

<script type="text/javascript">

    function send_ajax() {
      console.log('btn clicked');
      if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest(); //code for IE7+, Firefox, Chrome, Opera, Safari
      }
      else {
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //code for IE6, IE5
      }
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          console.log('data sent');
        }
      }
      xmlhttp.open('POST', 'index.php', true);
      var data = new FormData();
      data.append('query',document.getElementById('input').value);
      //you can append more data in same manner for sending more data
      xmlhttp.send(data);
    }

    document.getElementById('btn').addEventListener('click', send_ajax, false);
    </script>


问:
Change an Insert statement to an update statement in PHP/MySQL
I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I  should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.

```<code><?php
    require "conn.php";

    $patient_name = $_POST["patient_name"];
    $check_in_date = $_POST["check_in_date"];
    $room_number = $_POST["room_number"];
    $bed_number = $_POST["bed_number"];
    $notes = $_POST["notes"];

    $mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";

    if($conn->query($mysql_qry) === TRUE) {
        echo "Insert successful";
    }
    else{
        echo "Error: " . $mysql_qry . "<br>" . $conn->error;
    }
    $conn->close();
?>
</code>```

EDIT

The fixed code is below, it now updates records already in the database rather than adding new data.

```<code><?php
    require "conn.php";

    $patient_name = $_POST["patient_name"];
    $check_in_date = $_POST["check_in_date"];
    $room_number = $_POST["room_number"];
    $bed_number = $_POST["bed_number"];
    $notes = $_POST["notes"];

    $mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";

    if($conn->query($mysql_qry) === TRUE) {
        echo "Insert successful";
    }
    else{
        echo "Error: " . $mysql_qry . "<br>" . $conn->error;
    }
    $conn->close();
?>
</code>```

答:
first of all this PHP code is vulnerable to sql injection you should, no need to update your code to use either mysqli prepared statement or PDO prepared statement

secondly the easiest way I know you accomplish your goal would make a unique constraint on some columns and then use a mysql feature ON DUPLICATE UPDATE

for this example I'll assume that the unique fields determining an update instead of an insert are patient_name, check_in_date, room_number, and bed_number (in case john smith was in the same room as john smith in seprate beds) the query to update the table would be like this

```<code>ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`, `bed_number`);
</code>```

so now to address the sql injection bit and the query, I'll update the example to use mysqli statement and will assume patient_name and notes are strings (varchar/nvarchar), room_number and bed_number are integers, and check_in_date is a date

Edit My original answer had a syntax error in the query and also passing variables to the prepared statement below is the updated answer

```<code>$mysqliConn = new mysqli("localhost", "my_user", "my_password", "mydatabase");

$stmt = $mysqliConn->prepare("insert into patients
    (patient_name, check_in_date, room_number, bed_number, notes)
    values (?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE notes=values(notes)");

$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];

mysqli_stmt_bind_param($stmt, "sdiis",
    $patient_name, $check_in_date, $room_number, $bed_number, $notes);
</code>```

hope this helps

Edit
Regarding the unique key, a unique key means that all fields in the unique key have to be unique when combined so for the example above

if record 1 is
patient_name, check_in_date, room_number, bed_number, notes
'john smith', '3/1/2017'    , 413        , 2         , 'patient is sick'
and record two is
'jane doe'  , '3/1/2017'    , 413        , 2         , 'patient has wound'

these two records will note be duplicates with the above constraint but if you do need to change the constraint you can do the following

DROP the Constraint

```<code>ALTER TABLE `patients` DROP INDEX `unique_index`;
</code>```

Then recreate the constraint like this

```<code>ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`);
</code>```

also if you named your constraint something other than unique_index you can find the key_name by running the following

```<code>SHOW INDEX FROM `patients`;
</code>```

the name will be in the key_name column

additionally you may want to alter the last line of the query to be this in your php if you change the unique constraint so you can change bed number

```<code>ON DUPLICATE KEY UPDATE bed_number=values(bed_number), notes=values(notes)
</code>```

Body:
I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I  should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.

<?php
    require "conn.php";

    $patient_name = $_POST["patient_name"];
    $check_in_date = $_POST["check_in_date"];
    $room_number = $_POST["room_number"];
    $bed_number = $_POST["bed_number"];
    $notes = $_POST["notes"];

    $mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";

    if($conn->query($mysql_qry) === TRUE) {
        echo "Insert successful";
    }
    else{
        echo "Error: " . $mysql_qry . "
" . $conn->error;
    }
    $conn->close();
?>

EDIT

The fixed code is below, it now updates records already in the database rather than adding new data.

<?php
    require "conn.php";

    $patient_name = $_POST["patient_name"];
    $check_in_date = $_POST["check_in_date"];
    $room_number = $_POST["room_number"];
    $bed_number = $_POST["bed_number"];
    $notes = $_POST["notes"];

    $mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";

    if($conn->query($mysql_qry) === TRUE) {
        echo "Insert successful";
    }
    else{
        echo "Error: " . $mysql_qry . "
" . $conn->error;
    }
    $conn->close();
?>

Body:
first of all this PHP code is vulnerable to sql injection you should, no need to update your code to use either mysqli prepared statement or PDO prepared statement

secondly the easiest way I know you accomplish your goal would make a unique constraint on some columns and then use a mysql feature ON DUPLICATE UPDATE

for this example I'll assume that the unique fields determining an update instead of an insert are patient_name, check_in_date, room_number, and bed_number (in case john smith was in the same room as john smith in seprate beds) the query to update the table would be like this

ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`, `bed_number`);

so now to address the sql injection bit and the query, I'll update the example to use mysqli statement and will assume patient_name and notes are strings (varchar/nvarchar), room_number and bed_number are integers, and check_in_date is a date

Edit My original answer had a syntax error in the query and also passing variables to the prepared statement below is the updated answer

$mysqliConn = new mysqli("localhost", "my_user", "my_password", "mydatabase");

$stmt = $mysqliConn->prepare("insert into patients
    (patient_name, check_in_date, room_number, bed_number, notes)
    values (?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE notes=values(notes)");

$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];

mysqli_stmt_bind_param($stmt, "sdiis",
    $patient_name, $check_in_date, $room_number, $bed_number, $notes);

hope this helps

Edit
Regarding the unique key, a unique key means that all fields in the unique key have to be unique when combined so for the example above

if record 1 is
patient_name, check_in_date, room_number, bed_number, notes
'john smith', '3/1/2017'    , 413        , 2         , 'patient is sick'
and record two is
'jane doe'  , '3/1/2017'    , 413        , 2         , 'patient has wound'

these two records will note be duplicates with the above constraint but if you do need to change the constraint you can do the following

DROP the Constraint

ALTER TABLE `patients` DROP INDEX `unique_index`;

Then recreate the constraint like this

ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`);

also if you named your constraint something other than unique_index you can find the key_name by running the following

SHOW INDEX FROM `patients`;

the name will be in the key_name column

additionally you may want to alter the last line of the query to be this in your php if you change the unique constraint so you can change bed number

ON DUPLICATE KEY UPDATE bed_number=values(bed_number), notes=values(notes)


问:
Combining to tables and sorting by latest latest date
I am real beginner to php-mysql and am trying to figure this out.

I have two tables, as shown: a topic table and a conversation table.

I'm trying to merge the tables to:

1) display the titles that belong to a specific category (for example, if category=color, display the titles: 'Color of orange' and 'Color of banana'.)

2) display the date of the last comment made associated with each title (for, example, the latest date for 'Color of orange' is 2009

3) Sort the titles by the latest date - descending

I can manage doing part I, but I'm lost with part 2 and 3. Any help is appreciated.

答:
You'll use SELECT CASE, JOIN and subquery to achieve that.

EDIT

Lets start from begining. As I don't know your table's names I'll write some fake names. You said you have two tables: one for topics and other for replies. You also mentioned some categories but you didn't specified how it works, so I'll write it as a column of topic's table.

Table T = Topic's table + Table R = Reply's table

Also consider registry_date a TIMESTAMP column where we save the registration date of our rows.

To achieve your order by last change you need to get some info like:

Is there an answer (reply)?

If so, what's the registration date of
the latest reply?

You can answer both questions by searching for the last reply.

SELECT R.topicID, R.registry_date FROM R GROUP BY R.topicID ORDER BY R.registry_date DESC

That will be your subquery. But as you need it in your ORDER BY query you should JOIN that result with your topic's table.

SELECT T.title, T.category FROM T LEFT JOIN {subquery} AS Rs ON T.ID=Rs.topicID GROUP BY T.ID

It's not ordering yet. Please note that I called our subquery result "Rs".
Now we'll use our CASE. Different from what I wrote earlier, instead of doing SELECt CASE I'll try ORDER BY CASE, alright? That's simple.

First lets mount our CASE query.

```<code>CASE
    WHEN Rs.registry_date IS NULL THEN T.registry_date
    ELSE Rs.registry_date
END
</code>```

Our first conditional checks if there's any answer. If it's empty, we will use the topic's registration date. If it's populated, we will use the reply's registration date. Now we apply that CASE query on our ORDER BY like this:

```<code>ORDER BY {CASE} DESC
</code>```

As you probably want the last change date info we'll need to get it on our SELECT. You can use your CASE query here too.

```<code>SELECT T.title, T.category, {CASE} AS `last_change` (...)
</code>```

Then our query ends up like this:

```<code>SELECT
    T.title,
    T.category,
    CASE
        WHEN Rs.registry_date IS NULL THEN T.registry_date
        ELSE Rs.registry_date
    END AS `last_change`
FROM T
LEFT JOIN (
    SELECT
        R.topicID,
        R.registry_date
    FROM R
    GROUP BY R.topicID
    ORDER BY R.registry_date DESC
) AS Rs ON Rs.topicID=T.ID
GROUP BY T.ID
ORDER BY
    CASE
        WHEN Rs.registry_date IS NULL THEN T.registry_date
        ELSE Rs.registry_date
    END DESC
</code>```

PS: you can improve your own "WHERE" statements here.

Just as you asked, for example, WHERE T.category='color'

```<code>SELECT
    T.title,
    T.category,
    CASE
        WHEN Rs.registry_date IS NULL THEN T.registry_date
        ELSE Rs.registry_date
    END AS `last_change`
FROM T
LEFT JOIN (
    SELECT
        R.topicID,
        R.registry_date
    FROM R
    GROUP BY R.topicID
    ORDER BY R.registry_date DESC
) AS Rs ON Rs.topicID=T.ID
WHERE T.category='color'
GROUP BY T.ID
ORDER BY
    CASE
        WHEN Rs.registry_date IS NULL THEN T.registry_date
        ELSE Rs.registry_date
    END DESC
</code>```

Please let me know if something's missing.

Body:
You'll use SELECT CASE, JOIN and subquery to achieve that.

EDIT

Lets start from begining. As I don't know your table's names I'll write some fake names. You said you have two tables: one for topics and other for replies. You also mentioned some categories but you didn't specified how it works, so I'll write it as a column of topic's table.

Table T = Topic's table + Table R = Reply's table

Also consider registry_date a TIMESTAMP column where we save the registration date of our rows.

To achieve your order by last change you need to get some info like:

Is there an answer (reply)?

If so, what's the registration date of
the latest reply?

You can answer both questions by searching for the last reply.

SELECT R.topicID, R.registry_date FROM R GROUP BY R.topicID ORDER BY R.registry_date DESC

That will be your subquery. But as you need it in your ORDER BY query you should JOIN that result with your topic's table.

SELECT T.title, T.category FROM T LEFT JOIN {subquery} AS Rs ON T.ID=Rs.topicID GROUP BY T.ID

It's not ordering yet. Please note that I called our subquery result "Rs".
Now we'll use our CASE. Different from what I wrote earlier, instead of doing SELECt CASE I'll try ORDER BY CASE, alright? That's simple.

First lets mount our CASE query.

CASE
    WHEN Rs.registry_date IS NULL THEN T.registry_date
    ELSE Rs.registry_date
END

Our first conditional checks if there's any answer. If it's empty, we will use the topic's registration date. If it's populated, we will use the reply's registration date. Now we apply that CASE query on our ORDER BY like this:

ORDER BY {CASE} DESC

As you probably want the last change date info we'll need to get it on our SELECT. You can use your CASE query here too.

SELECT T.title, T.category, {CASE} AS `last_change` (...)

Then our query ends up like this:

SELECT
    T.title,
    T.category,
    CASE
        WHEN Rs.registry_date IS NULL THEN T.registry_date
        ELSE Rs.registry_date
    END AS `last_change`
FROM T
LEFT JOIN (
    SELECT
        R.topicID,
        R.registry_date
    FROM R
    GROUP BY R.topicID
    ORDER BY R.registry_date DESC
) AS Rs ON Rs.topicID=T.ID
GROUP BY T.ID
ORDER BY
    CASE
        WHEN Rs.registry_date IS NULL THEN T.registry_date
        ELSE Rs.registry_date
    END DESC

PS: you can improve your own "WHERE" statements here.

Just as you asked, for example, WHERE T.category='color'

SELECT
    T.title,
    T.category,
    CASE
        WHEN Rs.registry_date IS NULL THEN T.registry_date
        ELSE Rs.registry_date
    END AS `last_change`
FROM T
LEFT JOIN (
    SELECT
        R.topicID,
        R.registry_date
    FROM R
    GROUP BY R.topicID
    ORDER BY R.registry_date DESC
) AS Rs ON Rs.topicID=T.ID
WHERE T.category='color'
GROUP BY T.ID
ORDER BY
    CASE
        WHEN Rs.registry_date IS NULL THEN T.registry_date
        ELSE Rs.registry_date
    END DESC

Please let me know if something's missing.


问:
Parse.Cloud.afterSave not working with parse-server
I was using parse.com and had written a cloud code function that worked perfectly. When I moved to a self hosted parse-server backend, some of the cloud code function stopped working.

```<code>Parse.Cloud.afterSave("League", function (request) {

    if (request.object.get("leaderboard") == null) {

        var leaderboard = Parse.Object.extend("Leaderboard");
        var newInstance = new leaderboard();

        newInstance.save(null , {useMasterKey: true})
            .then(function (result) {
                request.object.set("leaderboard", result);
                request.object.save(null ,{useMasterKey: true});
            },
            function (error) {
                console.log("Error");
            });
        });
    }else{
        var membersRelation = request.object.relation("members");
        var membersQuery = membersRelation.query();
        membersQuery.count(null , {useMasterKey: true})
            .then(function (totalNumber) {
                request.object.set("memberCount", totalNumber)
                request.object.save(null ,{useMasterKey: true});
            }, function (error) {
                console.log("Error")
            })
     }
</code>```

As you can see, I define the afterSave hook for the League class. In my hook, I have to update the same object again when I set a new value (leaderboard and/or membersCount) so save is called save more than once.

The function saves data properly, but it causes an infinite loop too. I understand it happens because I call request.object.save() that will change the League class again so the afterSave event fires again, and so on. I don't know how I can handle this condition. Someone suggested to me to add a timeout but not sure how.  Can you please help with a solution to this problem.

Thanks

答:
Your approach has two problems:

There is a race condition on leaderboard.  When the promise of the first save resolves, there will be no leaderboard and then it'll magically be there "at some point in the future".  Much better to set the initial value in a beforeSave so that the state of league is known and predictable.

There is also a race condition on membersCount.  Imagine that two updates adding and/or removing members comes in at the same time.  Between when you read the relations and write the count, an other update could occur.  You could end up with the wrong count, or even a negative number!

To solve 1, we simply move the creation of the leaderboard into a beforeSave. To solve 2 we move the calculation of the membersCount into the beforeSave, use the supplied information on the dirty object about member adds and subtracts and finally we use increment to make sure that the update is atomic and avoid a race condition.

Below is working code with a unit test.  Note that if I were doing my own code review of this, I would a) want to test adding multiple and subtracting multiple members b) split the big first test into multiple tests where only one thing is tested per test. c) test adding and removing in the same save.

I'm using es6 constructs cause I like them ;).

Trying to put in lots of comments, but feel free to ask me if something is confusing.

PS If you don't know how to do and run unit tests on your cloud code, ask another question, cause it is invaluable for figuring out how this stuff works (and looking at the parse-server unit tests is the best documentation you'll find)

Good luck!

```<code>const addLeaderboard = function addLeaderboard(league) {
  // note the simplified object creation without using extends.
  return new Parse.Object('Leaderboard')
    // I was surprised to find that I had to save the new leaderboard
    // before saving the league. too bad & unit tests ftw.
    .save(null, { useMasterKey: true })
    // "fat arrow" function declaration.  If there's only a single
    // line in the function and you don't use {} then the result
    // of that line is the return value.  cool!
    .then(leaderboard => league.set('leaderboard', leaderboard));
}

const leagueBeforeSave = function leagueBeforeSave(request, response) {
  // Always prefer immutability to avoid bugs!
  const league = request.object;

  if (league.op('members')) {
    // Using a debugger to see what is available on the league
    // is super helpful, cause I have never seen this stuff
    // documented, but its obvious in a debugger.
    const membersAdded = league.op('members').relationsToAdd.length;
    const membersRemoved = league.op('members').relationsToRemove.length;
    const membersChange = membersAdded - membersRemoved;
    if (membersChange !== 0) {
      // by setting increment when the save is done, the
      // change in this value will be atomic.  By using a change
      // in the value rather than an absolute number
      // we avoid a race condition when paired with the atomicity of increment
      league.increment('membersCount', membersChange);
    }
  }

  if (!league.get('leaderboard')) {
    // notice we don't have to save the league, we just
    // add the leaderboard.  When we call success, the league
    // will be saved and the leaderboard will be there....
    addLeaderboard(league)
      .then(() => response.success(league))
      .catch(response.error);
  } else {
    response.success(league);
  }
};

// The rest of this is just to test our beforeSave hook.
describe('league save logic', () => {

  beforeEach(() => {
    Parse.Cloud.beforeSave('League', leagueBeforeSave);
  });

  it('should create league and increment properly', (done) => {
    Parse.Promise.when([
      new Parse.Object('Member').save(),
      new Parse.Object('Member').save(),
      new Parse.Object('Member').save(),
      new Parse.Object('Member').save(),
    ])
      .then((members) => {
        const league = new Parse.Object('League');
        const memberRelation = league.relation('members');
        memberRelation.add(members);
        // I want to use members in the next promise block,
        // there are a number of ways to do this, but I like
        // passing the value this way.  See Parse.Promise.when
        // doc if this is mysterious.
        return Parse.Promise.when(
          league.save(null, { useMasterKey: true }),
          members);
      })
      .then((league, members) => {
        expect(league.get('leaderboard').className).toBe('Leaderboard');
        expect(league.get('membersCount')).toBe(4);
        const memberRelation = league.relation('members');
        memberRelation.remove(members[0]);
        return league.save(null, { useMasterKey: true });
      })
      .then((league) => {
        expect(league.get('membersCount')).toBe(3);
        // just do a save with no change to members to make sure
        // we don't have something that breaks in that case...
        return league
          .set('foo', 'bar')
          .save(null, { useMasterKey: true })
      })
      .then(league => {
        expect(league.get('foo')).toBe('bar');
        done();
      })
      .catch(done.fail);
  });

  it('should work to create new without any members too', (done) => {
    new Parse.Object('League')
      .save() // we don't really need the useMasterKey in unit tests unless we setup `acl`s..:).
      .then((league) => {
        expect(league.get('leaderboard').className).toBe('Leaderboard');
        done();
      })
      .catch(done.fail);
  });
});
</code>```

Body:
I was using parse.com and had written a cloud code function that worked perfectly. When I moved to a self hosted parse-server backend, some of the cloud code function stopped working.

Parse.Cloud.afterSave("League", function (request) {

    if (request.object.get("leaderboard") == null) {

        var leaderboard = Parse.Object.extend("Leaderboard");
        var newInstance = new leaderboard();

        newInstance.save(null , {useMasterKey: true})
            .then(function (result) {
                request.object.set("leaderboard", result);
                request.object.save(null ,{useMasterKey: true});
            },
            function (error) {
                console.log("Error");
            });
        });
    }else{
        var membersRelation = request.object.relation("members");
        var membersQuery = membersRelation.query();
        membersQuery.count(null , {useMasterKey: true})
            .then(function (totalNumber) {
                request.object.set("memberCount", totalNumber)
                request.object.save(null ,{useMasterKey: true});
            }, function (error) {
                console.log("Error")
            })
     }

As you can see, I define the afterSave hook for the League class. In my hook, I have to update the same object again when I set a new value (leaderboard and/or membersCount) so save is called save more than once.

The function saves data properly, but it causes an infinite loop too. I understand it happens because I call request.object.save() that will change the League class again so the afterSave event fires again, and so on. I don't know how I can handle this condition. Someone suggested to me to add a timeout but not sure how.  Can you please help with a solution to this problem.

Thanks

Body:
Your approach has two problems:

There is a race condition on leaderboard.  When the promise of the first save resolves, there will be no leaderboard and then it'll magically be there "at some point in the future".  Much better to set the initial value in a beforeSave so that the state of league is known and predictable.

There is also a race condition on membersCount.  Imagine that two updates adding and/or removing members comes in at the same time.  Between when you read the relations and write the count, an other update could occur.  You could end up with the wrong count, or even a negative number!

To solve 1, we simply move the creation of the leaderboard into a beforeSave. To solve 2 we move the calculation of the membersCount into the beforeSave, use the supplied information on the dirty object about member adds and subtracts and finally we use increment to make sure that the update is atomic and avoid a race condition.

Below is working code with a unit test.  Note that if I were doing my own code review of this, I would a) want to test adding multiple and subtracting multiple members b) split the big first test into multiple tests where only one thing is tested per test. c) test adding and removing in the same save.

I'm using es6 constructs cause I like them ;).

Trying to put in lots of comments, but feel free to ask me if something is confusing.

PS If you don't know how to do and run unit tests on your cloud code, ask another question, cause it is invaluable for figuring out how this stuff works (and looking at the parse-server unit tests is the best documentation you'll find)

Good luck!

const addLeaderboard = function addLeaderboard(league) {
  // note the simplified object creation without using extends.
  return new Parse.Object('Leaderboard')
    // I was surprised to find that I had to save the new leaderboard
    // before saving the league. too bad & unit tests ftw.
    .save(null, { useMasterKey: true })
    // "fat arrow" function declaration.  If there's only a single
    // line in the function and you don't use {} then the result
    // of that line is the return value.  cool!
    .then(leaderboard => league.set('leaderboard', leaderboard));
}

const leagueBeforeSave = function leagueBeforeSave(request, response) {
  // Always prefer immutability to avoid bugs!
  const league = request.object;

  if (league.op('members')) {
    // Using a debugger to see what is available on the league
    // is super helpful, cause I have never seen this stuff
    // documented, but its obvious in a debugger.
    const membersAdded = league.op('members').relationsToAdd.length;
    const membersRemoved = league.op('members').relationsToRemove.length;
    const membersChange = membersAdded - membersRemoved;
    if (membersChange !== 0) {
      // by setting increment when the save is done, the
      // change in this value will be atomic.  By using a change
      // in the value rather than an absolute number
      // we avoid a race condition when paired with the atomicity of increment
      league.increment('membersCount', membersChange);
    }
  }

  if (!league.get('leaderboard')) {
    // notice we don't have to save the league, we just
    // add the leaderboard.  When we call success, the league
    // will be saved and the leaderboard will be there....
    addLeaderboard(league)
      .then(() => response.success(league))
      .catch(response.error);
  } else {
    response.success(league);
  }
};

// The rest of this is just to test our beforeSave hook.
describe('league save logic', () => {

  beforeEach(() => {
    Parse.Cloud.beforeSave('League', leagueBeforeSave);
  });

  it('should create league and increment properly', (done) => {
    Parse.Promise.when([
      new Parse.Object('Member').save(),
      new Parse.Object('Member').save(),
      new Parse.Object('Member').save(),
      new Parse.Object('Member').save(),
    ])
      .then((members) => {
        const league = new Parse.Object('League');
        const memberRelation = league.relation('members');
        memberRelation.add(members);
        // I want to use members in the next promise block,
        // there are a number of ways to do this, but I like
        // passing the value this way.  See Parse.Promise.when
        // doc if this is mysterious.
        return Parse.Promise.when(
          league.save(null, { useMasterKey: true }),
          members);
      })
      .then((league, members) => {
        expect(league.get('leaderboard').className).toBe('Leaderboard');
        expect(league.get('membersCount')).toBe(4);
        const memberRelation = league.relation('members');
        memberRelation.remove(members[0]);
        return league.save(null, { useMasterKey: true });
      })
      .then((league) => {
        expect(league.get('membersCount')).toBe(3);
        // just do a save with no change to members to make sure
        // we don't have something that breaks in that case...
        return league
          .set('foo', 'bar')
          .save(null, { useMasterKey: true })
      })
      .then(league => {
        expect(league.get('foo')).toBe('bar');
        done();
      })
      .catch(done.fail);
  });

  it('should work to create new without any members too', (done) => {
    new Parse.Object('League')
      .save() // we don't really need the useMasterKey in unit tests unless we setup `acl`s..:).
      .then((league) => {
        expect(league.get('leaderboard').className).toBe('Leaderboard');
        done();
      })
      .catch(done.fail);
  });
});


问:
find a substring and then replace it with something else probably with regex
I need some help on regex. I'm working on some twitter data and there are a lot of tweets that contain text like this: #something1@something2 . I'm trying to find a way to find substrings like that and replace it with #something1 @something2. I use python 3.
How can i do this? Thanks!</p>

答:
You just want to find a hashtag and a username that are not separated by a space and change them to be separated by a space. Indeed we can use a regular expression to match those.

```<code>sourceTweet = "lorem ipsum #dolor@sitamet Nullam sed est #vel@mi "
outputTweet = re.sub(r'(?<!\w)(#\w+)(@\w+)', r'\1 \2', sourceTweet)
#lorem ipsum #dolor @sitamet Nullam sed est #vel @mi
</code>```

Body:
You just want to find a hashtag and a username that are not separated by a space and change them to be separated by a space. Indeed we can use a regular expression to match those.

sourceTweet = "lorem ipsum #dolor@sitamet Nullam sed est #vel@mi "
outputTweet = re.sub(r'(?<!\w)(#\w+)(@\w+)', r'\1 \2', sourceTweet)
#lorem ipsum #dolor @sitamet Nullam sed est #vel @mi


问:
Big C# source file with Windows API method signatures, structures, constants: will they all be included in the final .exe?
I want to put all the signatures of Windows API functions I'm using in programs in one class, such as WinAPI, and in a file WinAPI.cs I will include in my projects. The class will be internal static and the methods public static extern. (Something like the huge NativeMethods.cs from the .NET Framework source code).

Let's say WinAPI.cs has one hundred native methods signatures like:

```<code>[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
</code>```

If I'm only going to use a few of them in a project (even one or two), if I include the WinAPI.cs file in my project, will the final .exe be filled with the unnecessary method declarations I'm not using (the other 99 or so)?

What about native structure declarations, If I'm not using them in the current project, will they still be included in the final .exe?

```<code>    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }
</code>```

What about constants declarations or readonly members like:

```<code>public const int WH_JOURNALPLAYBACK = 1;
public static readonly int WM_GETTEXT = 0x0D;
</code>```

答:
If I'm only going to use a few of them
  in a project (even one or two), if I
  include the WinAPI.cs file in my
  project, will the final .exe be filled
  with the unnecessary method
  declarations I'm not using (the other
  99 or so)?

Yes, all code in your project will be compiled into your assembly;

What about native structure
  declarations, If I'm not using them in
  the current project, will they still
  be included in the final .exe?

Yes. They will be included too.

```<code>   What about constants declarations or readonly members like:
</code>```

Yes. They will be included too.

ContentLicense: CC BY-SA 2.5

Body:
I want to put all the signatures of Windows API functions I'm using in programs in one class, such as WinAPI, and in a file WinAPI.cs I will include in my projects. The class will be internal static and the methods public static extern. (Something like the huge NativeMethods.cs from the .NET Framework source code).

Let's say WinAPI.cs has one hundred native methods signatures like:

[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

If I'm only going to use a few of them in a project (even one or two), if I include the WinAPI.cs file in my project, will the final .exe be filled with the unnecessary method declarations I'm not using (the other 99 or so)?

What about native structure declarations, If I'm not using them in the current project, will they still be included in the final .exe?

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }

What about constants declarations or readonly members like:

public const int WH_JOURNALPLAYBACK = 1;
public static readonly int WM_GETTEXT = 0x0D;

Body:
If I'm only going to use a few of them
  in a project (even one or two), if I
  include the WinAPI.cs file in my
  project, will the final .exe be filled
  with the unnecessary method
  declarations I'm not using (the other
  99 or so)?

Yes, all code in your project will be compiled into your assembly;

What about native structure
  declarations, If I'm not using them in
  the current project, will they still
  be included in the final .exe?

Yes. They will be included too.

   What about constants declarations or readonly members like:

Yes. They will be included too.


问:
How to get/create/impersonate InitiatorSession in AEM workflow
In AEM workflow, When i try to impersonate workflowSession to initiator this throws exception :

javax.security.auth.login.FailedLoginException: Impersonation not
  allowed.

I necessarily need initiator's session to trigger some task in my workflow, earlier i used to get this using :

```<code>initiatorSession= adminSession.impersonate(new SimpleCredentials(initiatorUser,"".toCharArray()));
</code>```

where adminSession is now deprecated and we use system users now, and so i cannot impersonate system user to initiator user, any suggestions?

答:
You need a user account that has impersonation permission. Your service account needs to be an allowed impersonator for the user it is trying to impersonate.

Try to control permissions with appropriate user groups.

Body:
In AEM workflow, When i try to impersonate workflowSession to initiator this throws exception :

javax.security.auth.login.FailedLoginException: Impersonation not
  allowed.

I necessarily need initiator's session to trigger some task in my workflow, earlier i used to get this using :

initiatorSession= adminSession.impersonate(new SimpleCredentials(initiatorUser,"".toCharArray()));

where adminSession is now deprecated and we use system users now, and so i cannot impersonate system user to initiator user, any suggestions?


问:
tvOS - Display web content
First off - our needs don't require any sort of interaction with the web view, we simply want to display content from the web.

Situation: we want to make a glorified slide show that pulls in web content.  We were intending on having a list of templates shown to the user on the TV app, they can pick one, and then the appropriate URL is hit for that template (which would live on the web). The web portion would handle things from there, navigating to a new URL every X seconds (which just displays the next set of data in the same template)

In learning that web views are restricted, and you can't sneak an app submission by apple while utilizing a web view, we've hit a dead end.  Having hundreds of templates that are all hard coded doesn't seem maintainable for us to do, plus we can't deliver a new template to users (er.. clients) without going through the potentially lengthy app approval process every time.

Does anyone have any other bright ideas for storing templates on the web, maybe even in a data format, that we can download and interpret/parse in-app to know where to position image views, labels, etc?

Thanks for any suggestions!

答:
I know I'm a little late to the party, but I wanted to answer your secondary question.  It is absolutely possible to load TVML files from the web without updating the tvOS submitted app.  We have a published tvOS app that is currently doing this.

As I recall, the tvOS app we submitted is very basic, with the only real change being the TVBaseURL.  We placed all of our TVJS files on Google App Engine and the TVML files are in the GAE Storage bucket, so the TVBaseURL points to the public URL for those files.  I have a cron job that reads an API and dynamically builds the TVML files several times a day.  When the TVOS app runs, it loads the files from the GAE Storage bucket.  The real benefit is that I can update the TVML layout and add or delete screens as needed without ever needing to go through the app submission process.

Title: tvOS - Display web content


问:
How to shuffle a character array with no two duplicates next to each other?
I was asked this question in an interview:

How to shuffle a character array with no two duplicates next to each other?

The algorithm I came up with was :

have a HashMap of Character, count of occurrence of Character pairs.
With this find the count of duplicate vs unique elements.

If duplicate > unique, cannot form a shuffled array with no 2
duplicate elements next to each other (?)

if unique >= duplicate, have 2 stacks - 1 containing unique
characters and one containing duplicate characters. Construct the
resulting array in such a way that pop an element from unique stack
first and pop an element from duplicate stack next. Repeat

For example:

```<code>[a,b,b,c] shuffled array with above algorithm - [a,b,c,b];

[b,b,b,c] unique < duplicate return error
</code>```

But I am pretty sure I am overcomplicating the logic. Is there an easier and fool proof way to do this?

答:
SCALA Code. Copy and paste this program and run.</p>

```<code>def rearrange(xs : List[Char]) : List[Char] ={
xs match {
    case Nil => Nil
    case x :: xs1 => xs1 match {
    case Nil => x :: Nil
    case y :: ys1 =>
         if (x == y)  {
              (x :: rearrange(ys1)) :+ y
         }
         else
             x :: y :: rearrange(ys1)
         }
     }
}
rearrange: (xs: List[Char])List[Char]

rearrange("hello".toList)
</code>```

Body:
I was asked this question in an interview:

How to shuffle a character array with no two duplicates next to each other?

The algorithm I came up with was :

have a HashMap of Character, count of occurrence of Character pairs.
With this find the count of duplicate vs unique elements.

If duplicate > unique, cannot form a shuffled array with no 2
duplicate elements next to each other (?)

if unique >= duplicate, have 2 stacks - 1 containing unique
characters and one containing duplicate characters. Construct the
resulting array in such a way that pop an element from unique stack
first and pop an element from duplicate stack next. Repeat

For example:

[a,b,b,c] shuffled array with above algorithm - [a,b,c,b];

[b,b,b,c] unique < duplicate return error

But I am pretty sure I am overcomplicating the logic. Is there an easier and fool proof way to do this?

Body:
SCALA Code. Copy and paste this program and run.

def rearrange(xs : List[Char]) : List[Char] ={
xs match {
    case Nil => Nil
    case x :: xs1 => xs1 match {
    case Nil => x :: Nil
    case y :: ys1 =>
         if (x == y)  {
              (x :: rearrange(ys1)) :+ y
         }
         else
             x :: y :: rearrange(ys1)
         }
     }
}
rearrange: (xs: List[Char])List[Char]

rearrange("hello".toList)


问:
Are there environment variables which are reliable always set?
Are there environment variables which are reliable always set?</p>

答:
No. One can start a program with an empty environment:</p>

```<code>env - your_application
</code>```

Body:
No. One can start a program with an empty environment:

env - your_application


问:
get input value from form doesnt work Angular2
I'm currently used modal form and when the modal is open he load the information  of my items but when I want to submit all inputs are null
this is my modal "this part works fine"

```<code><div id="modal1" class="modal">
  <form #formData='ngForm' (ngSubmit)="onSubmit(formData)">
    <div class="modal-content">
      <div class="row">
        <div class="input-field col s6">
          <input (ngModel)="productN" value="{{ObjProd.product}}"  name="productN" type="text"  >
          <label for="productN">Product Name</label>
        </div>
        <div class="input-field col s6">
          <input (ngModel)="price" value="{{ObjProd.price}}"  name="price" type="text"  >
          <label for="price">price</label>
        </div>
        <div class="input-field col s6">
          <input (ngModel)="quantity" value="{{ObjProd.quantity}}"   name="quantity" type="text"  >
          <label for="quantity">quantity</label>
        </div>
        <div class="input-field col s6">
          <input (ngModel)="photoURL" value="{{ObjProd.product}}"   name="photoURL" type="text"  >
          <label for="photoURL">photoURL</label>

        </div>
         <input type="text" placeholder="Full name" value="{{ObjProd.key}}" (ngModel)="namef" name="namef" class="txt" >
        <input type="text" (ngModel)="keyProduct"   name="keyProduct" value="{{ObjProd.key}}" >
        <input type="text" (ngModel)="typeProduct"   name="typeProduct" value="{{ObjProd.type}}" >
      </div>
    </div>
    <div class="modal-footer">
      <button type="submit"  class="modal-action modal-close waves-effect waves-green btn-flat " >Update Product</button>
    </div>
  </form>
</div>
</code>```

and this is my function Submit

```<code>  onSubmit(formData) {
    if(formData.value.typeProduct){
      console.log(formData.value.photoURL);
    }else{
      console.log(formData.value.namef, formData.value.photoURL);
    }

    }
</code>```

this is my modal works and my data
but the output doesnt work
http://imgur.com/a/b2CpI

答:
You are having the code in the index.html and using jQuery and messing up the application.

Instead you should be using modal component as a separate component as below

```<code>import {Component,Input, ViewChild} from '@angular/core';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'common-modal',
  template: `
   <div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title pull-left">{{title}}</h4>
        <button type="button" class="close pull-right" aria-label="Close" (click)="hideChildModal()">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form #formData='ngForm' (ngSubmit)="onSubmit(formData)">
    <div class="modal-content">
      <div class="row">
        <div class="input-field col s6">
          <input [(ngModel)]="productN" value="true"  name="productN" type="text"  >
          <label for="productN">Product Name</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="price" value="true"  name="price" type="text"  >
          <label for="price">price</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="quantity" value="true"   name="quantity" type="text"  >
          <label for="quantity">quantity</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="photoURL" value="true"   name="photoURL" type="text"  >
          <label for="photoURL">photoURL</label>

        </div>
         <input type="text" placeholder="Full name" value="true" [(ngModel)]="namef" name="namef" class="txt" >
        <input type="text" [(ngModel)]="keyProduct"   name="keyProduct" value="true" >
        <input type="text" [(ngModel)]="typeProduct"   name="typeProduct" value="true" >
      </div>
    </div>
    <div class="modal-footer">
      <button type="submit"  class="modal-action modal-close waves-effect waves-green btn-flat " >Update Product</button>
    </div>
  </form>
      </div>

      <div class="modal-footer">
        <div class="pull-left">
          <button class="btn btn-default" (click)="hide()"> Cancel </button>
        </div>
      </div>
    </div>
  </div>
</div>
  `,
})
export class CommonModalComponent {
   @ViewChild('childModal') public childModal:ModalDirective;
   @Input() title?:string;
  constructor() {
  }
  show(){
    this.childModal.show();
  }
  hide(){
    this.childModal.hide();
  }
  onSubmit(val){
    console.log(val);
  }
}
</code>```

LIVE DEMO

Body:
I'm currently used modal form and when the modal is open he load the information  of my items but when I want to submit all inputs are null
this is my modal "this part works fine"

  <form #formData='ngForm' (ngSubmit)="onSubmit(formData)">

          <input (ngModel)="productN" value="{{ObjProd.product}}"  name="productN" type="text"  >
          Product Name

          <input (ngModel)="price" value="{{ObjProd.price}}"  name="price" type="text"  >
          price

          <input (ngModel)="quantity" value="{{ObjProd.quantity}}"   name="quantity" type="text"  >
          quantity

          <input (ngModel)="photoURL" value="{{ObjProd.product}}"   name="photoURL" type="text"  >
          photoURL

         <input type="text" placeholder="Full name" value="{{ObjProd.key}}" (ngModel)="namef" name="namef" class="txt" >
        <input type="text" (ngModel)="keyProduct"   name="keyProduct" value="{{ObjProd.key}}" >
        <input type="text" (ngModel)="typeProduct"   name="typeProduct" value="{{ObjProd.type}}" >

      <button type="submit"  class="modal-action modal-close waves-effect waves-green btn-flat " >Update Product</button>

  </form>

and this is my function Submit

  onSubmit(formData) {
    if(formData.value.typeProduct){
      console.log(formData.value.photoURL);
    }else{
      console.log(formData.value.namef, formData.value.photoURL);
    }

    }

this is my modal works and my data
but the output doesnt work
http://imgur.com/a/b2CpI

Body:
You are having the code in the index.html and using jQuery and messing up the application.

Instead you should be using modal component as a separate component as below

import {Component,Input, ViewChild} from '@angular/core';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  selector: 'common-modal',
  template: `
   <div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title pull-left">{{title}}</h4>
        <button type="button" class="close pull-right" aria-label="Close" (click)="hideChildModal()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form #formData='ngForm' (ngSubmit)="onSubmit(formData)">
    <div class="modal-content">
      <div class="row">
        <div class="input-field col s6">
          <input [(ngModel)]="productN" value="true"  name="productN" type="text"  >
          <label for="productN">Product Name</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="price" value="true"  name="price" type="text"  >
          <label for="price">price</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="quantity" value="true"   name="quantity" type="text"  >
          <label for="quantity">quantity</label>
        </div>
        <div class="input-field col s6">
          <input [(ngModel)]="photoURL" value="true"   name="photoURL" type="text"  >
          <label for="photoURL">photoURL</label>

        </div>
         <input type="text" placeholder="Full name" value="true" [(ngModel)]="namef" name="namef" class="txt" >
        <input type="text" [(ngModel)]="keyProduct"   name="keyProduct" value="true" >
        <input type="text" [(ngModel)]="typeProduct"   name="typeProduct" value="true" >
      </div>
    </div>
    <div class="modal-footer">
      <button type="submit"  class="modal-action modal-close waves-effect waves-green btn-flat " >Update Product</button>
    </div>
  </form>
      </div>

      <div class="modal-footer">
        <div class="pull-left">
          <button class="btn btn-default" (click)="hide()"> Cancel </button>
        </div>
      </div>
    </div>
  </div>
</div>
  `,
})
export class CommonModalComponent {
   @ViewChild('childModal') public childModal:ModalDirective;
   @Input() title?:string;
  constructor() {
  }
  show(){
    this.childModal.show();
  }
  hide(){
    this.childModal.hide();
  }
  onSubmit(val){
    console.log(val);
  }
}

LIVE DEMO


问:
Caching issue with webpack-dev-server
I'm having some issues when running the webpack-dev-server. Whenever I save a file, and changes are compiled, they are not being reflected in the browser. (No errors in command line)

I'm running the following command:

webpack-dev-server --progress --color

However, if I run webpack every time I have a change, this is reflected in my browser.

I run Chrome on my Mac (latest v. of OSX), and I've enabled the "Disable cache while devtools is open" option. Needless to say, but hey - you never know, I have my DevTools open.. :)

Am I missing a simple step here?

答:
I had the same problem and I was using dist/app.js file in my html and not app.js that generated by webpack-dev-server.

Using this in my html solved the issue:

```<code><script src="vendor.js"></script>
<script src="app.js"></script>
</code>```

Title: Caching issue with webpack-dev-server

Body:
I had the same problem and I was using dist/app.js file in my html and not app.js that generated by webpack-dev-server.

Using this in my html solved the issue:

<script src="vendor.js"></script>
<script src="app.js"></script>


问:
jq: how to add an object, key/value in a nested json tree with arrays
I am pretty new to JQ ... so sorry if it seems obvious..
The bare problem first. I have this JSON file:

Link: https://github.com/mariotti/technical_interview_questions/blob/master/QUESTIONS.json

Extract.

```<code>cat QUESTIONS.json | jq '.TechQuestions.category[0,1].question[0,1]'
output:
{
ID: Q1,
categoryname: General,
idC: C1,
idCQ: C1Q1,
idQ: Q1,
title: Find the most frequent integer in an array
}
{
ID: Q21,
categoryname: Strings,
idC: C2,
idCQ: C2Q1,
idQ: Q1,
title: Find the first non-repeated character in a String
}
{
ID: Q2,
categoryname: General,
idC: C1,
idCQ: C1Q2,
idQ: Q2,
title: Find pairs in an integer array whose sum is equal to 10 (bonus; do it in linear time)
}
{
ID: Q22,
categoryname: Strings,
idC: C2,
idCQ: C2Q2,
idQ: Q2,
title: Reverse a String iteratively and recursively
}
</code>```

As you can see, this is "deep" into:

```<code>{
"TechQuestions": {
"category": [
  {
    "catname": "General",
    "idC": "C1",
    "question": [
      {
        "ID": "Q1",
        "categoryname": "General",
        "idC": "C1",
        "idCQ": "C1Q1",
        "idQ": "Q1",
        "title": "Find the most frequent integer in an array"
      },
</code>```

I want to add the key/field:

```<code>"codefile" : "a string to be defined"
</code>```

within the question[] items to get something like:

```<code>      {
        "ID": "Q1",
        "categoryname": "General",
        "idC": "C1",
        "idCQ": "C1Q1",
        "idQ": "Q1",
        "title": "Find the most frequent integer in an array",
        "codefile" : "not present"
      },
</code>```

And I want to do it programmatically as I might need to develop a bit further...

From other sources (Transforming the name of key deeper in the JSON structure with jq) I could for example rename a key with this:

```<code>cat QUESTIONS.json | jq '.' | jq '
# Apply f to composite entities recursively, and to atoms
def walk(f):
 . as $in
 | if type == "object" then
      reduce keys[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
  elif type == "array" then map( walk(f) ) | f
  else f
  end;
(.  |= walk(
           if type == "object"
           then with_entries( if .key == "name" then .key |= sub("name";"title") else . end)
           else .
           end))'
</code>```

I was trying to modify this bit without success. It seems I am unable to simply add a key/value!

I will avoid to overload you with odd references and a further list of attempts.
But maybe I give you an example of a try:

```<code>(.  |= walk(
       if type == "object"
       then with_entries(
            if .key == "question"
            then . = ( . + {"freshly": "added"})
            else .
            end)
       else .
       end))'
</code>```

The solution doesn't have to match my attempts. Actually if there is a more straight full way it is very appreciated.

答:
What's wrong with:

```<code>.TechQuestions.category[0,1].question[] += {"codefile" : "a string to be defined"}
</code>```

Using walk/1, you could consider:

```<code>walk( if type == "object" and has("question")
      then .question[] += {"codefile" : "a string to be defined"}
      else .
      end)
</code>```

Body:
I am pretty new to JQ ... so sorry if it seems obvious..
The bare problem first. I have this JSON file:

Link: https://github.com/mariotti/technical_interview_questions/blob/master/QUESTIONS.json

Extract.

cat QUESTIONS.json | jq '.TechQuestions.category[0,1].question[0,1]'
output:
{
ID: Q1,
categoryname: General,
idC: C1,
idCQ: C1Q1,
idQ: Q1,
title: Find the most frequent integer in an array
}
{
ID: Q21,
categoryname: Strings,
idC: C2,
idCQ: C2Q1,
idQ: Q1,
title: Find the first non-repeated character in a String
}
{
ID: Q2,
categoryname: General,
idC: C1,
idCQ: C1Q2,
idQ: Q2,
title: Find pairs in an integer array whose sum is equal to 10 (bonus; do it in linear time)
}
{
ID: Q22,
categoryname: Strings,
idC: C2,
idCQ: C2Q2,
idQ: Q2,
title: Reverse a String iteratively and recursively
}

As you can see, this is "deep" into:

{
"TechQuestions": {
"category": [
  {
    "catname": "General",
    "idC": "C1",
    "question": [
      {
        "ID": "Q1",
        "categoryname": "General",
        "idC": "C1",
        "idCQ": "C1Q1",
        "idQ": "Q1",
        "title": "Find the most frequent integer in an array"
      },

I want to add the key/field:

"codefile" : "a string to be defined"

within the question[] items to get something like:

      {
        "ID": "Q1",
        "categoryname": "General",
        "idC": "C1",
        "idCQ": "C1Q1",
        "idQ": "Q1",
        "title": "Find the most frequent integer in an array",
        "codefile" : "not present"
      },

And I want to do it programmatically as I might need to develop a bit further...

From other sources (Transforming the name of key deeper in the JSON structure with jq) I could for example rename a key with this:

cat QUESTIONS.json | jq '.' | jq '
# Apply f to composite entities recursively, and to atoms
def walk(f):
 . as $in
 | if type == "object" then
      reduce keys[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
  elif type == "array" then map( walk(f) ) | f
  else f
  end;
(.  |= walk(
           if type == "object"
           then with_entries( if .key == "name" then .key |= sub("name";"title") else . end)
           else .
           end))'

I was trying to modify this bit without success. It seems I am unable to simply add a key/value!

I will avoid to overload you with odd references and a further list of attempts.
But maybe I give you an example of a try:

(.  |= walk(
       if type == "object"
       then with_entries(
            if .key == "question"
            then . = ( . + {"freshly": "added"})
            else .
            end)
       else .
       end))'

The solution doesn't have to match my attempts. Actually if there is a more straight full way it is very appreciated.

Body:
What's wrong with:

.TechQuestions.category[0,1].question[] += {"codefile" : "a string to be defined"}

Using walk/1, you could consider:

walk( if type == "object" and has("question")
      then .question[] += {"codefile" : "a string to be defined"}
      else .
      end)


问:
How to access the local Django webserver from outside world
I followed the instructions here to run Django using the built-in webserver and was able to successfully run it using python manage.py runserver.  If I access 127.0.0.1:port locally from the webserver, I get the Django page indicating it worked.

I realize the Django webserver is not a production server, but it's important for me for testing purposes to be able to access it from the outside world -- i.e. not from a web browser on the server, but from a different computer.

I tried:

```<code>http://mywebserver:port_django_runs_on
</code>```

but it did not work.  I also tried using the IP instead (based on ifconfig) to access:

```<code>http://myipaddress:port_django_runs_on
</code>```

which did not work either.

The web server is running so it must be accessible from the outside, I'm just not sure how.  I am running Linux with Apache, though I have not configured Django with Apache.

Any ideas on how to do this?

答:
For AWS users.

I had to use the following steps to get there.

1) Ensure that pip and django are installed at the sudo level

sudo apt-get install python-pip

sudo pip install django

2) Ensure that security group in-bound rules includ http on port 80 for 0.0.0.0/0

configured through AWS console

3) Add Public IP and DNS to ALLOWED_HOSTS

ALLOWED_HOSTS is a list object that you can find in settings.py

ALLOWED_HOSTS = ["75.254.65.19","ec2-54-528-27-21.compute-1.amazonaws.com"]

4) Launch development server with sudo on port 80

sudo python manage.py runserver 0:80

Site now available at either of the following (no need for :80 as that is default for http):

[Public DNS] i.e. ec2-54-528-27-21.compute-1.amazonaws.com

[Public IP] i.e 75.254.65.19

Body:
I followed the instructions here to run Django using the built-in webserver and was able to successfully run it using python manage.py runserver.  If I access 127.0.0.1:port locally from the webserver, I get the Django page indicating it worked.

I realize the Django webserver is not a production server, but it's important for me for testing purposes to be able to access it from the outside world -- i.e. not from a web browser on the server, but from a different computer.

I tried:

http://mywebserver:port_django_runs_on

but it did not work.  I also tried using the IP instead (based on ifconfig) to access:

http://myipaddress:port_django_runs_on

which did not work either.

The web server is running so it must be accessible from the outside, I'm just not sure how.  I am running Linux with Apache, though I have not configured Django with Apache.

Any ideas on how to do this?