问:
Find a key in array of object
The input is JSON array of object.

```<code>[
    {
        "name": "JOHN",
        "age": "90",
        "ID": "123",
        "country": "UK",
        "email": "john@test.com"
    }, {
        "name": "PETER",
        "age": "10",
        "ID": "456",
        "country": "",
    }
]
</code>```

What is the best way in Javascript to find a key in all of the arrays and return ok if it exists. For example, does "name" exist? Yes, JOHN and PETER. Does "email" exist? Yes, john@test.com. Does "city" exist? No.

Thank you for giving tips!

答:
Iterate over array, get object's keys, scan for key, return value if found.  Filter your generated array to remove any undefined/false values afterwards (may need revision, depending on your expected values -- especially if you want to include falsy values {'ID':0}).

var arr = [{
  "name": "JOHN",
  "age": "90",
  "ID": "123",
  "country": "UK",
  "email": "john@test.com"
}, {
  "name": "PETER",
  "age": "10",
  "ID": "456",
  "country": ""
}];

var key = 'name';
var values = arr.map(obj => ~Object.keys(obj).indexOf(key) && obj[key]).filter(v => v);

console.log(values)```

Without writing a book, here are some clues to what's going on:

map iterates over the array and generates a new array using the mapping function

~ bitwise NOT, performs -(N+1), which is useful when working with indexOf() because a non-match would return -1, but the NOT operator translates -1 to 0 (false);
Math: -(-1+1)=-(0)=0

[more on bitwise NOT]
When indexOf matches it returns 0(or greater).  Using the -(N+1) mentioned above, this means ~ operator converts any match to a negative number, which is truthy.  -(0+1)=-1 or -(3+1)=-4 -- all truthy

If the ~...indexOf() is true the logical AND operator (&&) will perform the second expression, which retrieves the value from the object and returns it

Object.keys() gets the keys of the object

filter() iterates over an array and only keeps elements that the match function returns true

v=>v is the match function, which is equivalent to function(v){ return v; }, meaning if v is truthy, keep the value; if falsy, don't keep the value in the array (similar to grep of other languages)

Edit:

As RobG pointed out, in place of the ~[].indexOf(), [].includes() can now be used, making the code look something like Object.keys(obj).includes(key).  This should remove some of the less understood operators (for beginners) as well as make the code more semantic and readable.

Title: Find a key in array of object

Body:
The input is JSON array of object.

[
    {
        "name": "JOHN",
        "age": "90",
        "ID": "123",
        "country": "UK",
        "email": "john@test.com"
    }, {
        "name": "PETER",
        "age": "10",
        "ID": "456",
        "country": "",
    }
]

What is the best way in Javascript to find a key in all of the arrays and return ok if it exists. For example, does "name" exist? Yes, JOHN and PETER. Does "email" exist? Yes, john@test.com. Does "city" exist? No.

Thank you for giving tips!

Body:
Iterate over array, get object's keys, scan for key, return value if found.  Filter your generated array to remove any undefined/false values afterwards (may need revision, depending on your expected values -- especially if you want to include falsy values {'ID':0}).

var arr = [{
  "name": "JOHN",
  "age": "90",
  "ID": "123",
  "country": "UK",
  "email": "john@test.com"
}, {
  "name": "PETER",
  "age": "10",
  "ID": "456",
  "country": ""
}];

var key = 'name';
var values = arr.map(obj => ~Object.keys(obj).indexOf(key) && obj[key]).filter(v => v);

console.log(values)

Without writing a book, here are some clues to what's going on:

map iterates over the array and generates a new array using the mapping function

~ bitwise NOT, performs -(N+1), which is useful when working with indexOf() because a non-match would return -1, but the NOT operator translates -1 to 0 (false);
Math: -(-1+1)=-(0)=0

[more on bitwise NOT]
When indexOf matches it returns 0(or greater).  Using the -(N+1) mentioned above, this means ~ operator converts any match to a negative number, which is truthy.  -(0+1)=-1 or -(3+1)=-4 -- all truthy

If the ~...indexOf() is true the logical AND operator (&&) will perform the second expression, which retrieves the value from the object and returns it

Object.keys() gets the keys of the object

filter() iterates over an array and only keeps elements that the match function returns true

v=>v is the match function, which is equivalent to function(v){ return v; }, meaning if v is truthy, keep the value; if falsy, don't keep the value in the array (similar to grep of other languages)

Edit:

As RobG pointed out, in place of the ~[].indexOf(), [].includes() can now be used, making the code look something like Object.keys(obj).includes(key).  This should remove some of the less understood operators (for beginners) as well as make the code more semantic and readable.


来源: stackexchange

问:
RTMP streaming through http
I'm trying to set up a streaming service using Nginx-rtmp. The config file is

```<code>    rtmp {
    server {
        listen 1935;

        chunk_size 4000;

        # video on demand for flv files
        application vod {
            play /var/flvs;
        }

        # video on demand for mp4 files
        application vod2 {
            play /var/mp4s;
        }
    }
}
</code>```

I want the streaming service go through http not rtmp. Eventually we want client to connect to a proxy server using https and then the proxy server talk to the streaming server using rtmp. I'm testing using HTTP for now. So I set up a HAProxy using the following config:

```<code>global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

    #tune.ssl.default-dh-param 2048

    # Default SSL material locations
    ca-base /etc/ssl/certs
    crt-base /etc/ssl/private

    # Default ciphers to use on SSL-enabled listening sockets.
    # For more information, see ciphers(1SSL). This list is from:
    #  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
    ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
    ssl-default-bind-options no-sslv3

defaults
    log global
    mode    tcp
    option  httplog
    option  dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

frontend rtmp-80
        bind *:80
        default_backend rtmp-over-http

backend rtmp-over-http
        server media01 127.0.0.1:1935 check maxconn 200
</code>```

I can access the streaming service using uri of rtmp://the_ip:1935/vod2/gua.mp4 in a VLC player.
But no matter what I tried, it does not work when I tried to access the streaming using http://the_ip:80/vod2/gua.mp4.

Is this even possible?

Thanks so much!

答:
HTTP and RTMP are two different things. There is no way to transfer RTMP package through HTTP, because if a client sends an HTTP request, the server will return an HTTP response and then the client would consume HTTP package. In theory, the client can then unpack the HTTP package, but there would require extra work.

A much better solution is using HTTP Live Streaming (HLS). nginx-vod-module supports HLS. It can be easily configured in the config file. When a video is put in the server, the client can use a URL like http://127.0.0.1/vod/sample.mp4/index.m3u8. The Nginx server automatically partitions the video to HTTP package and provide a playlist. So the client can play it. HLS is widely supported by many open source players (for browsers) and mobile devices (both ios and android). And it can be easily configured with HTTPS for secure transformation.

ContentLicense: CC BY-SA 3.0

Title: RTMP streaming through http

Body:
I'm trying to set up a streaming service using Nginx-rtmp. The config file is

    rtmp {
    server {
        listen 1935;

        chunk_size 4000;

        # video on demand for flv files
        application vod {
            play /var/flvs;
        }

        # video on demand for mp4 files
        application vod2 {
            play /var/mp4s;
        }
    }
}

I want the streaming service go through http not rtmp. Eventually we want client to connect to a proxy server using https and then the proxy server talk to the streaming server using rtmp. I'm testing using HTTP for now. So I set up a HAProxy using the following config:

global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

    #tune.ssl.default-dh-param 2048

    # Default SSL material locations
    ca-base /etc/ssl/certs
    crt-base /etc/ssl/private

    # Default ciphers to use on SSL-enabled listening sockets.
    # For more information, see ciphers(1SSL). This list is from:
    #  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
    ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
    ssl-default-bind-options no-sslv3

defaults
    log global
    mode    tcp
    option  httplog
    option  dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

frontend rtmp-80
        bind *:80
        default_backend rtmp-over-http

backend rtmp-over-http
        server media01 127.0.0.1:1935 check maxconn 200

I can access the streaming service using uri of rtmp://the_ip:1935/vod2/gua.mp4 in a VLC player.
But no matter what I tried, it does not work when I tried to access the streaming using http://the_ip:80/vod2/gua.mp4.

Is this even possible?

Thanks so much!


问:
stackdump is not created if exe is not run from cygwin terminal
I have an application which is compiled in cygwin. The exe crashes once in a while. If exe is run from cygwin terminal a stackdump file is created. If exe is copied to another folder along with cygwin1.dll and the exe crashes, then no stackdump file is created.

I want a stackdump file to be created even if the exe is run not from cygwin terminal.

How can this be achieved?

答:
When you start a cygwin executable from windows, or a command prompt, the CYGWIN environment variable is usually not set. The shortcut or batch file which starts the cygwin terminal sometimes sets this variable. One of the options that can be set by this variable determines what program is called by windows when the application crashes. The /bin/dumper.exe program generates the stackdump you want.

To get around your problem, I always set the CYGWIN variable from the control panel, computer properties, advances system settings, environment variables, user variables. (Win7 - YMMV). E.g. CYGWIN=error_start=d:\cygwin64\bin\dumper.exe

See The CYGWIN Environment variable for more information.


问:
Lucene and Classic ASP?
I have a legacy app in which I need to enable search.

I was looking at either Lucene or FTS of SQL Server.

However my question is...would Lucene work with Classic ASP? Any links?

Thanks!

Vladan

答: There is no Lucene for VBScript (source), but can use the .Net implementation and access the searched records via a standard webservice or an AJAX call returning JSON.</p>

ContentLicense: CC BY-SA 2.5

Title: Lucene and Classic ASP?


问:
401 return from an API Gateway Custom Authorizer is missing 'Access-Control-Allow-Origin' header
In order to prevent users who have not logged in to call my lambda function through the AWS API Gateway, I'm using the Custom Authorizer lambda solution.

If the request is authorized (200) and I get a response from the called lambda everything works fine and I get the Access-Control-Allow-Origin header.

But if the request is not authorized, I get a 401 that has no Access-Control-Allow-Origin header, therefore preventing me from reading the 401 status of the response and redirecting the user to the log-in page.

I believe this is because the Custom Autorization mechanism is unaware that the request needs to use CORS. Does anyone know that this is actually the issue? Are you aware of any possible solution?

答:
I'm happy to announce the new Gateway Responses feature which allows you to customize the error responses for requests that don't call your integration. This allows you to ensure that CORS headers are included, even on failed auth requests.

Read more in our documentation, which includes a CORS example.

ContentLicense: CC BY-SA 4.0


问:
Write Codec for embedded documents in mongodb-java-driver
I am using mongo-java-driver in my application to read and write data to mongodb.

I have classes like this -

```<code>public A{
    private String a;
    //Getters & Setters
}

public class B{
    private String b;
    private List<A> a;
    //Getters & Setters
}

public class C{
    private String c;
    private B b;
    //Getters & Setters
}
</code>```

I have created Codec for the classes C like this -

```<code>public class CCodec implements Codec<C> {

    private Codec<Document> documentCodec;

    public CCodec(CodecRegistry registry) {
        documentCodec = registry.get(Document.class);
    }

    @Override
    public void encode(BsonWriter writer, C c, EncoderContext context)     {
        Document document = new Document();
        document.put("c",c.getC());
        document.put("b",c.getB());
        documentCodec.encode(writer, document, context);
    }
}
</code>```

Codec for class B -

```<code>public class BCodec implements Codec<B> {

        private Codec<Document> documentCodec;

        public CCodec(CodecRegistry registry) {
            documentCodec = registry.get(Document.class);
        }

        @Override
        public void encode(BsonWriter writer, B b, EncoderContext context)     {
            writer.writeStartDocument();
            writer.writeString("b",b.getB());
            //How to encode A Here
            writer.writeEndDocument();
        }
    }
</code>```

I can not do encoding in BCodec as i did for CCodec because when i say

```<code>Document document = new Document();
</code>```

It creates a new document but i wan't to have it embedded in Document C.

Now the question is how do i encode field a of type List in B class?
See encode method of BCodec class.
Needless to say i have added all the Codec in CodecProvider.

Any help is appreciated.

答:
You can try using the DocumentCodec.encode method as follows -

```<code>@Override
public void encode(BsonWriter writer, B b, EncoderContext context) {
    org.bson.Document bsonDocument = new org.bson.Document();
    List<A> a = B.getA();
    bsonDocument.put("a", a);
    ...
    documentCodec.encode(writer, bsonDocument, encoderContext);
}
</code>```

and as you decode :

```<code>@Override
public B decode(BsonReader reader, DecoderContext decoderContext) {
    org.bson.Document bsonDocument = documentCodec.decode(reader, decoderContext);
    B b = new B();
    b.setA((List)bsonDocument.getString("a"));
    ...
    return b;
}
</code>```

Body:
I am using mongo-java-driver in my application to read and write data to mongodb.

I have classes like this -

public A{
    private String a;
    //Getters & Setters
}

public class B{
    private String b;
    private List a;
    //Getters & Setters
}

public class C{
    private String c;
    private B b;
    //Getters & Setters
}

I have created Codec for the classes C like this -

public class CCodec implements Codec<C> {

    private Codec<Document> documentCodec;

    public CCodec(CodecRegistry registry) {
        documentCodec = registry.get(Document.class);
    }

    @Override
    public void encode(BsonWriter writer, C c, EncoderContext context)     {
        Document document = new Document();
        document.put("c",c.getC());
        document.put("b",c.getB());
        documentCodec.encode(writer, document, context);
    }
}

Codec for class B -

public class BCodec implements Codec {

        private Codec<Document> documentCodec;

        public CCodec(CodecRegistry registry) {
            documentCodec = registry.get(Document.class);
        }

        @Override
        public void encode(BsonWriter writer, B b, EncoderContext context)     {
            writer.writeStartDocument();
            writer.writeString("b",b.getB());
            //How to encode A Here
            writer.writeEndDocument();
        }
    }

I can not do encoding in BCodec as i did for CCodec because when i say

Document document = new Document();

It creates a new document but i wan't to have it embedded in Document C.

Now the question is how do i encode field a of type List in B class?
See encode method of BCodec class.
Needless to say i have added all the Codec in CodecProvider.

Any help is appreciated.

Body:
You can try using the DocumentCodec.encode method as follows -

@Override
public void encode(BsonWriter writer, B b, EncoderContext context) {
    org.bson.Document bsonDocument = new org.bson.Document();
    List<A> a = B.getA();
    bsonDocument.put("a", a);
    ...
    documentCodec.encode(writer, bsonDocument, encoderContext);
}

and as you decode :

@Override
public B decode(BsonReader reader, DecoderContext decoderContext) {
    org.bson.Document bsonDocument = documentCodec.decode(reader, decoderContext);
    B b = new B();
    b.setA((List)bsonDocument.getString("a"));
    ...
    return b;
}


问:
Unable to set position of Angular Material 2 dialog using MdDialogConfig
Any idea how to set the position of an MdDialog?

```<code>  openDialog() {
let config = new MdDialogConfig();
config.height = '15px';
config.position.left = '5px';
let dialogRef = this.dialog.open(BasicAlertDialog, config);
dialogRef.componentInstance.title = this.dialogTitle ;
dialogRef.componentInstance.text = this.dialogText ;
dialogRef.componentInstance.yes = this.dialogYes ;
dialogRef.componentInstance.no = this.dialogNo ;
</code>```

I can set the height, but setting the position results in the error "ERROR TypeError: Cannot set property 'left' of undefined
    at AppComponent.webpackJsonp.267.AppComponent.openDialog (app.component.ts:385)". Line 385 is where I try to set the left position to 5px.

答:
you can set like that. does this help!

```<code>    openDialog() {
       let config = new MdDialogConfig();

       config.height = '15px';
       config.position = {
                left: '5px'
            };
       let dialogRef = this.dialog.open(BasicAlertDialog, config);
       dialogRef.componentInstance.title = this.dialogTitle ;
       dialogRef.componentInstance.text = this.dialogText ;
       dialogRef.componentInstance.yes = this.dialogYes ;
       dialogRef.componentInstance.no = this.dialogNo ;
   }
</code>```

Body:
Any idea how to set the position of an MdDialog?

  openDialog() {
let config = new MdDialogConfig();
config.height = '15px';
config.position.left = '5px';
let dialogRef = this.dialog.open(BasicAlertDialog, config);
dialogRef.componentInstance.title = this.dialogTitle ;
dialogRef.componentInstance.text = this.dialogText ;
dialogRef.componentInstance.yes = this.dialogYes ;
dialogRef.componentInstance.no = this.dialogNo ;

I can set the height, but setting the position results in the error "ERROR TypeError: Cannot set property 'left' of undefined
    at AppComponent.webpackJsonp.267.AppComponent.openDialog (app.component.ts:385)". Line 385 is where I try to set the left position to 5px.

Body:
you can set like that. does this help!

    openDialog() {
       let config = new MdDialogConfig();

       config.height = '15px';
       config.position = {
                left: '5px'
            };
       let dialogRef = this.dialog.open(BasicAlertDialog, config);
       dialogRef.componentInstance.title = this.dialogTitle ;
       dialogRef.componentInstance.text = this.dialogText ;
       dialogRef.componentInstance.yes = this.dialogYes ;
       dialogRef.componentInstance.no = this.dialogNo ;
   }


问:
Get the Entity Name when calling SaveChanges in Entity Framework 6.1.3
I am trying to override the SaveChanges() method in my DbContext class, this because I try to get the name of the entity with a row added, deleted or updated an the respective ID of the row and the action performed.

I don't know how to do this.

This is with logs actions purposes.

Greetings in advance.

答:
You need to override SaveChanges method of DbContext and use ChangeTracker to track the changes made to entities before it gets saved to database.public

```<code>public class ChangeLog
{
    public string EntityName { get; set; }
    public string PropertyName { get; set; }
    public string OldValue { get; set; }
    public string NewValue { get; set; }
}

public override int SaveChanges()
{
    var modifiedEntities = ChangeTracker.Entries()
        .Where(p => p.State == EntityState.Modified).ToList();

    foreach (var change in modifiedEntities)
    {
        var entityName = change.Entity.GetType().Name;

        foreach(var prop in change.OriginalValues.PropertyNames)
        {
            var originalValue = change.OriginalValues[prop].ToString();
            var currentValue = change.CurrentValues[prop].ToString();
            if (originalValue != currentValue)
            {
                ChangeLog log = new ChangeLog()
                {
                    EntityName = entityName,
                    PropertyName = prop,
                    OldValue = originalValue,
                    NewValue = currentValue,
                };
                ChangeLogs.Add(log);
            }
        }
    }
    return base.SaveChanges();
}
</code>```

In above snippet we have queried change tracker api to fetch the entities that are modified

```<code>var modifiedEntities = ChangeTracker.Entries()
        .Where(p => p.State == EntityState.Modified).ToList();
</code>```

Same way you can query entities that are added and deleted.

Edit

```<code>object GetPrimaryKeyValue(DbEntityEntry entry)
{
        var stateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
        return stateEntry.EntityKey.EntityKeyValues[0].Value;
}
</code>```

Note: If you have Identity Insert set to On then for added entity above snippet will not work.

Body:
You need to override SaveChanges method of DbContext and use ChangeTracker to track the changes made to entities before it gets saved to database.public

public class ChangeLog
{
    public string EntityName { get; set; }
    public string PropertyName { get; set; }
    public string OldValue { get; set; }
    public string NewValue { get; set; }
}

public override int SaveChanges()
{
    var modifiedEntities = ChangeTracker.Entries()
        .Where(p => p.State == EntityState.Modified).ToList();

    foreach (var change in modifiedEntities)
    {
        var entityName = change.Entity.GetType().Name;

        foreach(var prop in change.OriginalValues.PropertyNames)
        {
            var originalValue = change.OriginalValues[prop].ToString();
            var currentValue = change.CurrentValues[prop].ToString();
            if (originalValue != currentValue)
            {
                ChangeLog log = new ChangeLog()
                {
                    EntityName = entityName,
                    PropertyName = prop,
                    OldValue = originalValue,
                    NewValue = currentValue,
                };
                ChangeLogs.Add(log);
            }
        }
    }
    return base.SaveChanges();
}

In above snippet we have queried change tracker api to fetch the entities that are modified

var modifiedEntities = ChangeTracker.Entries()
        .Where(p => p.State == EntityState.Modified).ToList();

Same way you can query entities that are added and deleted.

Edit

object GetPrimaryKeyValue(DbEntityEntry entry)
{
        var stateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
        return stateEntry.EntityKey.EntityKeyValues[0].Value;
}

Note: If you have Identity Insert set to On then for added entity above snippet will not work.


问:
sync cookies and sessions in different subdomains (asp.net)
I am building a site in asp.net and have multiple subdomains. For example,
one.cookies.com
two.cookies.com

I want my users to be able to login at either subdomain and be logged in for both websites. In addition, I'd like the sessions and cookies to be in sync. So far I haven't found a reliable way to do this.

答: I beleive make the cookie for http://cookies.com.  (No subdomain or www listed)</p>

OwnerDisplayName: dan

LastEditorDisplayName: dan

OwnerDisplayName: jhoven


问:
How to use the Azure Gatekeeper design pattern?
I've found the following official documentation by MS. But I'm not sure how to implement this?
Gatekeeper Deisgn Pattern

Do I have to create this pattern manually? or is it already available in Azure as a service which I can use? If so, how to make use of it?

答:
The pattern described in the link above is a generic pattern, use it as you see fit.  There is no "gatekeeper service" per-say in Azure, but there are several tools in the Azure toolbox that you can use to employ that pattern.  A couple of examples:

API Management

Azure Application Gateway

How you incorporate this pattern in your solution is ultimately up to you.  I'm sure there are other 3rd party solutions deployed from the marketplace.


问:
R: Validate Data for Numeric and Non-Numeric Variables
I got problem with R that I cant figure it out.

Here's my dataframe "test1"
dataframe1

I would like to validate if the data follows the rules
(Rule1: if Q1=1, Q2=Blank
 Rule2: if Q1!=1, Q2!=Blank)
so that I can have the results as below
results

However, I got the warning error "the condition has length > 1 and only the first element will be used".

Can anyone helps me with this?

Thanks a lot.

Body:
Based on the rules

df1$Result <- with(df1, (Q1==1 & Q2 == "")|(Q1 !=1 & Q2 !=""))

data

df1 <- data.frame(i..key = 1:9, Q1 = c(1:3, 1, 2, 2, 3, 1, 3),
  Q2 = c("", "abc", "fgdgg", "", "fdg", "", "dsfdsfds", "dfds", ""), stringsAsFactors=FALSE)


问:
Hide window until the top window is displayed
I am facing a little annoying design problem. Not easy to give a title of my question.

I must display two windows, one over another one. The first one is a Cocoa window, the second is made with Qt. In the second window, an action is performed, but the user can choose to close this window. He must fall back on the first window.

To display my first window, which is actually a SFAuthorizationPluginView, I do:

```<code>[myview displayView];
</code>```

then, to display the window made with Qt on top of first window:

```<code>QWidget* w = openMyScreen();
NSView* v = (NSView*)w->winId();
[[v window] setLevel:2003];
</code>```

This works well, however there is a small delay before the second window is displayed. We can thus see for a very short time the first window.

I need that the second window stays on top of the first window, because the user can close the second window and must have access to the first window.

Any ideas on a trick how to hide the first window, just the time, the second window appears?

Thanks in advance

答:
NSDisableScreenUpdates and NSEnableScreenUpdates (link) might be useful in this situation. The documentation says:

You typically call this function so that operations on multiple windows appear atomic to the user.

which seems to describe your situation.

A word of unrelated advice though: Don't go setting window levels willy-nilly. A window level of 2003 will likely cause the window to appear over things like the dock or even the menu bar, which would definitely be strange. You should stick to the standard levels declared in NSWindow.h unless you have good reason. NSFloatingWindowLevel might be appropriate (although I'm not sure what level the SFAuthorizationPluginView window is displayed at).

Body:
I am facing a little annoying design problem. Not easy to give a title of my question.

I must display two windows, one over another one. The first one is a Cocoa window, the second is made with Qt. In the second window, an action is performed, but the user can choose to close this window. He must fall back on the first window.

To display my first window, which is actually a SFAuthorizationPluginView, I do:

[myview displayView];

then, to display the window made with Qt on top of first window:

QWidget* w = openMyScreen();
NSView* v = (NSView*)w->winId();
[[v window] setLevel:2003];

This works well, however there is a small delay before the second window is displayed. We can thus see for a very short time the first window.

I need that the second window stays on top of the first window, because the user can close the second window and must have access to the first window.

Any ideas on a trick how to hide the first window, just the time, the second window appears?

Thanks in advance


问:
Simple C function returns nonsense
I need to make simple function that converts binary number (string) to decimal number (long). When it returns result, it's nonsense. I've tried to return all others variables and it returned correct numbers. There is something wrong with my result variable.</p>

```<code>#include "stdio.h"
#include "string.h"
#include "math.h"

long bintodec(const char *bin_num) {
        long DIGIT, SUBTOTAL, RESULT = 0, I, LEN;
        LEN = strlen(bin_num);
        for(I = 0; I != LEN; I++) {
                sscanf(&bin_num[I], "%li", &DIGIT);
                SUBTOTAL = DIGIT * pow(2, LEN - I - 1);
                RESULT = RESULT + SUBTOTAL;
        }
        return RESULT;
}

main() {
        clrscr();
        printf("%li", bintodec("101"));
        getch();
}
</code>```

答:
You can convert string to long in one go, no need to iterate in loop. Changing your code like below can give you desired output</p>

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

long bintodec(const char *bin_num)
{
  long DIGIT, SUBTOTAL, RESULT = 0, I, LEN, REM;
  LEN = strlen(bin_num);

  sscanf(bin_num, "%li", &DIGIT);
  printf("DIGIT = %li\n", DIGIT);

  for (I = 0; I < LEN; I++)
  {
    REM = DIGIT%10;
    RESULT += REM * pow(2, I);

    DIGIT /= 10;
  }

  return RESULT;
}

int main() {
  printf("%li", bintodec("101"));
}
</code>```

Title: Simple C function returns nonsense

Body:
I need to make simple function that converts binary number (string) to decimal number (long). When it returns result, it's nonsense. I've tried to return all others variables and it returned correct numbers. There is something wrong with my result variable.

#include "stdio.h"
#include "string.h"
#include "math.h"

long bintodec(const char *bin_num) {
        long DIGIT, SUBTOTAL, RESULT = 0, I, LEN;
        LEN = strlen(bin_num);
        for(I = 0; I != LEN; I++) {
                sscanf(&bin_num[I], "%li", &DIGIT);
                SUBTOTAL = DIGIT * pow(2, LEN - I - 1);
                RESULT = RESULT + SUBTOTAL;
        }
        return RESULT;
}

main() {
        clrscr();
        printf("%li", bintodec("101"));
        getch();
}

Body:
You can convert string to long in one go, no need to iterate in loop. Changing your code like below can give you desired output

#include <stdio.h>
#include <string.h>
#include <math.h>

long bintodec(const char *bin_num)
{
  long DIGIT, SUBTOTAL, RESULT = 0, I, LEN, REM;
  LEN = strlen(bin_num);

  sscanf(bin_num, "%li", &DIGIT);
  printf("DIGIT = %li\n", DIGIT);

  for (I = 0; I < LEN; I++)
  {
    REM = DIGIT%10;
    RESULT += REM * pow(2, I);

    DIGIT /= 10;
  }

  return RESULT;
}

int main() {
  printf("%li", bintodec("101"));
}


问:
How to use BindableProperty.Create in Xamarin.Forms?
In xaml in Xamarin.Forms, I have a custom control, I want to add property of type int. I think I have to use Bindable properties, so later I can bind a property from ViewModel.

I found this topic, but I'm not sure how to use it.. there is:

```<code>BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,
    propertyChanged: OnItemsSourcePropertyChanged);
</code>```

what's "BindablePicker"? Is it the view where property is declared?

Here's my try:

```<code>    public int WedgeRating
    {
        get
        {
            return (int)GetValue(WedgeRatingProperty);
        }
        set
        {
            try
            {
                SetValue(WedgeRatingProperty, value);
            }
            catch (ArgumentException ex)
            {
                // We need to do something here to let the user know
                // the value passed in failed databinding validation
            }
        }
    }

    public static readonly BindableProperty WedgeRatingProperty =
       BindableProperty.Create(nameof(WedgeRating), typeof(int), typeof(GameCocosSharpView), null, propertyChanged: OnItemsSourcePropertyChanged);

    private static void OnItemsSourcePropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
    }
</code>```

I didn't even use it in xaml, and it already doesn't work. No particular exception. Only the page where the custom control is initialized doesn't loead. When I comment line I pasted here, it works.

答:
Your code is good, just change your default value from null to 0 or default(int). You have it as null but an int property could never be null. This was the reason of the "crash".

```<code>public static readonly BindableProperty WedgeRatingProperty =
    BindableProperty.Create (nameof (WedgeRating), typeof (int), typeof (GameCocosSharpView), default(int), propertyChanged: OnItemsSourcePropertyChanged);
</code>```

Hope this helps!

Body:
In xaml in Xamarin.Forms, I have a custom control, I want to add property of type int. I think I have to use Bindable properties, so later I can bind a property from ViewModel.

I found this topic, but I'm not sure how to use it.. there is:

BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(BindablePicker), null,
    propertyChanged: OnItemsSourcePropertyChanged);

what's "BindablePicker"? Is it the view where property is declared?

Here's my try:

    public int WedgeRating
    {
        get
        {
            return (int)GetValue(WedgeRatingProperty);
        }
        set
        {
            try
            {
                SetValue(WedgeRatingProperty, value);
            }
            catch (ArgumentException ex)
            {
                // We need to do something here to let the user know
                // the value passed in failed databinding validation
            }
        }
    }

    public static readonly BindableProperty WedgeRatingProperty =
       BindableProperty.Create(nameof(WedgeRating), typeof(int), typeof(GameCocosSharpView), null, propertyChanged: OnItemsSourcePropertyChanged);

    private static void OnItemsSourcePropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
    }

I didn't even use it in xaml, and it already doesn't work. No particular exception. Only the page where the custom control is initialized doesn't loead. When I comment line I pasted here, it works.

Body:
Your code is good, just change your default value from null to 0 or default(int). You have it as null but an int property could never be null. This was the reason of the "crash".

public static readonly BindableProperty WedgeRatingProperty =
    BindableProperty.Create (nameof (WedgeRating), typeof (int), typeof (GameCocosSharpView), default(int), propertyChanged: OnItemsSourcePropertyChanged);

Hope this helps!


问:
Protractor flake next attempt and showing last report only
I am using protractor-flake to re run failure test cases. For reporting with screenshot I am using protractor-jasmine2-screenshot-reporter. I am wondering if there is any option to show all reports even there is next attempt from protractor flake.

For example,

100 test cases -1st attempt - all success -> Report showing 100 test
  cases -> OK

100 test cases - 1st attempt - 90 success & 10 failures - 2nd attempt all success (10 specs those failed on 1st attempt)
   -> Report showing only 10 specs -> Incomplete Report

I know protractor screen shot reporter replaced the reports every time in destination folder. Possibly that is the reason to showing only final attempt report.

For report perspective it is incomplete to showing only last attempt spec. Is it possible to storing every attempt's success and last attempt failure specs report and showing all report at once or any other reporting plugin which handle such situation?

Below is my configuration for report,

```<code>   var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
    var htmlReporter = new HtmlScreenshotReporter({
            dest: 'e2e/testreports',
            filename: 'e2eReport.html',
            reportOnlyFailedSpecs: false,
            captureOnlyFailedSpecs: true,
            showSummary: true,
            showQuickLinks: true
    });

  exports.config = {
    .....
    onPrepare: function() {
        ....
        jasmine.getEnv().addReporter(htmlReporter);
        ....
    },
    beforeLaunch: function() {
        return new Promise(function(resolve){
            htmlReporter.beforeLaunch(resolve);
        });
    },

   ...
};
</code>```

答:
As you said this is the "basic limitation" of the reporter setup you've implemented. What it now does is create a report with filename e2eReport.html for each run.

What if you add a timestamp to is when it is generated, so it becomes more unique. You will then get Date.now() + '-e2eReport.html' => 1496809660080-e2eReport.html and for example 1496809686906-e2eReport.html.

Hope it helps

Body:
I am using protractor-flake to re run failure test cases. For reporting with screenshot I am using protractor-jasmine2-screenshot-reporter. I am wondering if there is any option to show all reports even there is next attempt from protractor flake.

For example,

100 test cases -1st attempt - all success -> Report showing 100 test
  cases -> OK

100 test cases - 1st attempt - 90 success & 10 failures - 2nd attempt all success (10 specs those failed on 1st attempt)
   -> Report showing only 10 specs -> Incomplete Report

I know protractor screen shot reporter replaced the reports every time in destination folder. Possibly that is the reason to showing only final attempt report.

For report perspective it is incomplete to showing only last attempt spec. Is it possible to storing every attempt's success and last attempt failure specs report and showing all report at once or any other reporting plugin which handle such situation?

Below is my configuration for report,

   var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
    var htmlReporter = new HtmlScreenshotReporter({
            dest: 'e2e/testreports',
            filename: 'e2eReport.html',
            reportOnlyFailedSpecs: false,
            captureOnlyFailedSpecs: true,
            showSummary: true,
            showQuickLinks: true
    });

  exports.config = {
    .....
    onPrepare: function() {
        ....
        jasmine.getEnv().addReporter(htmlReporter);
        ....
    },
    beforeLaunch: function() {
        return new Promise(function(resolve){
            htmlReporter.beforeLaunch(resolve);
        });
    },

   ...
};


问:
What is the purpose of Format[T] if you have a Reads[T] and Writes [T]?
I'm only hours into exploring the Play Framework (2.5.1) and I'm confused why you would create a Format when you've already defined Reads and Writes. By defining the Reads and Writes for your class, haven't you defined all the functionality needed to convert the class to and from JsValue?

答:
As mentioned in the play-framework documentation here

Format[T] is just a mix of the Reads and Writes traits and can be used
  for implicit conversion in place of its components.

Format is a combination of Reads[T] and Writes[T]. So you can define a single implicit Format[T] for type T and use it to read and write Json instead of defining a separate implicit Reads[T] and Writes[T] for type T. Thus if you already have Reads[T] and Writes[T] defined for your type T then Format[T] is not required and vice versa.

One advantage with Format is that you can define a single Implicit Format[T] for your type T instead of defining two separate Reads[T] and Writes[T] if they are both symmetrical (i.e. the Reads and Writes). So Format makes your JSON Structure definition less repetitive. For example you can do something like this

```<code>implicit val formater: Format[Data] = (
    (__ \ "id").format[Int] and
    (__ \ "name").format[String] and
    (__ \ "value").format[String]
  ) (Data.apply, unlift(Data.unapply))
</code>```

Instead of this.

```<code>implicit val dataWriter: Writes[Data] = (
    (__ \ "id").write[Int] and
    (__ \ "name").write[String] and
    (__ \ "file_type").write[String]
  ) (Data.apply)

implicit val dataWriter: Reads[Data] = (
    (__ \ "id").read[Int] and
    (__ \ "name").read[String] and
    (__ \ "file_type").read[String]
  ) (unlift(Data.unapply))
</code>```

Body:
As mentioned in the play-framework documentation here

Format[T] is just a mix of the Reads and Writes traits and can be used
  for implicit conversion in place of its components.

Format is a combination of Reads[T] and Writes[T]. So you can define a single implicit Format[T] for type T and use it to read and write Json instead of defining a separate implicit Reads[T] and Writes[T] for type T. Thus if you already have Reads[T] and Writes[T] defined for your type T then Format[T] is not required and vice versa.

One advantage with Format is that you can define a single Implicit Format[T] for your type T instead of defining two separate Reads[T] and Writes[T] if they are both symmetrical (i.e. the Reads and Writes). So Format makes your JSON Structure definition less repetitive. For example you can do something like this

implicit val formater: Format[Data] = (
    (__ \ "id").format[Int] and
    (__ \ "name").format[String] and
    (__ \ "value").format[String]
  ) (Data.apply, unlift(Data.unapply))

Instead of this.

implicit val dataWriter: Writes[Data] = (
    (__ \ "id").write[Int] and
    (__ \ "name").write[String] and
    (__ \ "file_type").write[String]
  ) (Data.apply)

implicit val dataWriter: Reads[Data] = (
    (__ \ "id").read[Int] and
    (__ \ "name").read[String] and
    (__ \ "file_type").read[String]
  ) (unlift(Data.unapply))


问:
Invoke-command Missing Expression Operator '-'
```<code>invoke-command -computer hq128804 -scriptblock {powershell.exe -nonprofile -executionpolicy Bypass c:\Install-WMF5.ps1}
</code>```

The Error:

```<code>Missing expression after unary operator '-'.
    + CategoryInfo          : NotSpecified: (Missing express...y operator '-'.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : hq128804

At line:1 char:2
+ - <<<< nonprofile -executionpolicy Bypass c:\Install-WMF5.ps1
    + CategoryInfo          : ParserError: (-:String) [], ParentContainsErrorR
   ecordException
    + FullyQualifiedErrorId : MissingExpressionAfterOperator
NotSpecified: (:) [], RemoteException
</code>```

I am trying to run a script that is located on the root file system of another remote PC. I want to be able to execute this and update PowerShell for 2000 machines. I have the update files on each system, I just need a way to execute the .ps1 file Microsoft provides from my machine.

答:
You should do something like this:

```<code>Invoke-command -ComputerName hq128804 -scriptblock{powershell.exe -noprofile -executionpolicy Bypass -Command "& { c:\Install-WMF5.ps1}" }
</code>```

Note: Make sure you are having the ps1 properly placed in the mentioned path

Body:
invoke-command -computer hq128804 -scriptblock {powershell.exe -nonprofile -executionpolicy Bypass c:\Install-WMF5.ps1}

The Error:

Missing expression after unary operator '-'.
    + CategoryInfo          : NotSpecified: (Missing express...y operator '-'.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : hq128804

At line:1 char:2
+ - <<<< nonprofile -executionpolicy Bypass c:\Install-WMF5.ps1
    + CategoryInfo          : ParserError: (-:String) [], ParentContainsErrorR
   ecordException
    + FullyQualifiedErrorId : MissingExpressionAfterOperator
NotSpecified: (:) [], RemoteException

I am trying to run a script that is located on the root file system of another remote PC. I want to be able to execute this and update PowerShell for 2000 machines. I have the update files on each system, I just need a way to execute the .ps1 file Microsoft provides from my machine.

Body:
You should do something like this:

Invoke-command -ComputerName hq128804 -scriptblock{powershell.exe -noprofile -executionpolicy Bypass -Command "& { c:\Install-WMF5.ps1}" }

Note: Make sure you are having the ps1 properly placed in the mentioned path


问:
In a Javascript key value object, how to remove quotes from value
From a remote db, I retrieve the schema of a table and get a a JSON object of the following form:

```<code>{ Id:
   { type: 'INT',
     allowNull: false,
     defaultValue: null,
     primaryKey: false },
  Prefix:
   { type: 'NVARCHAR',
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
  FirstName:
   { type: 'NVARCHAR',
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
  Assets:
   { type: 'INT',
     allowNull: false,
     defaultValue: null,
     primaryKey: false },
  Role:
   { type: 'NVARCHAR',
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
}
</code>```

I want to transform the type of every column (Id, Prefix, FirstName, Assets, Role in this example) to something in the form DataTypes.INTEGER or DataTypes.STRING so at the end we get:

```<code> { Id:
   { type: DataTypes.INTEGER,
     allowNull: false,
     defaultValue: null,
     primaryKey: false },
  Prefix:
   { type: DataTypes.STRING,
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
  FirstName:
   { type: DataTypes.STRING,
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
  Assets:
   { type: DataTypes.INTEGER,
     allowNull: false,
     defaultValue: null,
     primaryKey: false },
  Role:
   { type: DataTypes.STRING,
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
}
</code>```

Please note the difference, the type value is no longer a string.

Initially i was trying the following:

```<code>var DataTypes = {
    NVARCHAR: 'STRING',
    INT: 'INTEGER',
    VARCHAR: 'STRING',
    DATETIME: 'DATE',
    FLOAT: 'FLOAT',
    NCHAR: 'STRING'
}

Object.keys(schema).forEach(function(fieldName) {
        types[schema[fieldName]['type']] ? schema[fieldName]['type'] = 'DataTypes.'+types[schema[fieldName]['type']] : console.log('Could not find type: ' + schema[fieldName]['type'])
    })
</code>```

but then I would get "DataTypes.STRING" instead of DataTypes.STRING

答:
I have never used the link you have mentioned in your comment which is Sequelize, but a quick look at their documentation shows this is how you define a new model:

```<code>const WhateverYouWant = sequelize.define('whatever', {
  Id : { type: DataTypes.INTEGER, allowNull: false,
         defaultValue: null, primaryKey: false},

  // other columns you have...
});
</code>```

Looking at that example, it seems DataTypes is an object and INTEGER is property within their library. So if you reference their library, then you will be able to use those types.

Body:
From a remote db, I retrieve the schema of a table and get a a JSON object of the following form:

{ Id:
   { type: 'INT',
     allowNull: false,
     defaultValue: null,
     primaryKey: false },
  Prefix:
   { type: 'NVARCHAR',
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
  FirstName:
   { type: 'NVARCHAR',
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
  Assets:
   { type: 'INT',
     allowNull: false,
     defaultValue: null,
     primaryKey: false },
  Role:
   { type: 'NVARCHAR',
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
}

I want to transform the type of every column (Id, Prefix, FirstName, Assets, Role in this example) to something in the form DataTypes.INTEGER or DataTypes.STRING so at the end we get:

 { Id:
   { type: DataTypes.INTEGER,
     allowNull: false,
     defaultValue: null,
     primaryKey: false },
  Prefix:
   { type: DataTypes.STRING,
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
  FirstName:
   { type: DataTypes.STRING,
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
  Assets:
   { type: DataTypes.INTEGER,
     allowNull: false,
     defaultValue: null,
     primaryKey: false },
  Role:
   { type: DataTypes.STRING,
     allowNull: true,
     defaultValue: null,
     primaryKey: false },
}

Please note the difference, the type value is no longer a string.

Initially i was trying the following:

var DataTypes = {
    NVARCHAR: 'STRING',
    INT: 'INTEGER',
    VARCHAR: 'STRING',
    DATETIME: 'DATE',
    FLOAT: 'FLOAT',
    NCHAR: 'STRING'
}

Object.keys(schema).forEach(function(fieldName) {
        types[schema[fieldName]['type']] ? schema[fieldName]['type'] = 'DataTypes.'+types[schema[fieldName]['type']] : console.log('Could not find type: ' + schema[fieldName]['type'])
    })

but then I would get "DataTypes.STRING" instead of DataTypes.STRING

Body:
I have never used the link you have mentioned in your comment which is Sequelize, but a quick look at their documentation shows this is how you define a new model:

const WhateverYouWant = sequelize.define('whatever', {
  Id : { type: DataTypes.INTEGER, allowNull: false,
         defaultValue: null, primaryKey: false},

  // other columns you have...
});

Looking at that example, it seems DataTypes is an object and INTEGER is property within their library. So if you reference their library, then you will be able to use those types.


问:
DrawerOpen in 'header' using StackNavigator and DrawerNavigator
I want to use DrawerOpen in header using React Navigation. I is showing error "undefined is not an object(evaluating this.props.navigation)". I am using StackNavigator and DrawerNavigator.

Source: https://reactnavigation.org/docs/navigators/drawer.

Please help.

```<code>header:{
    right: <Button onPress={() =>
    this.props.navigation.navigate('DrawerOpen')}
    title="Info" />
},

...
const SimpleApp = StackNavigator({
    Dashboard: { screen: DashboardScreen },
    Chat: { screen: ChatScreen },
});

const App = DrawerNavigator({
  Stack1:{screen:SimpleApp},
});
</code>```

答:
Try using:</p>

```<code>navigationOptions: ({navigation}) => ({
    title:'title',
    headerLeft: <Button title="button" onPress={() => navigation.navigate('DrawerOpen')} />
})
</code>```

Body:
I want to use DrawerOpen in header using React Navigation. I is showing error "undefined is not an object(evaluating this.props.navigation)". I am using StackNavigator and DrawerNavigator.

Source: https://reactnavigation.org/docs/navigators/drawer.

Please help.

header:{
    right: <Button onPress={() =>
    this.props.navigation.navigate('DrawerOpen')}
    title="Info" />
},

...
const SimpleApp = StackNavigator({
    Dashboard: { screen: DashboardScreen },
    Chat: { screen: ChatScreen },
});

const App = DrawerNavigator({
  Stack1:{screen:SimpleApp},
});

Body:
Try using:

navigationOptions: ({navigation}) => ({
    title:'title',
    headerLeft: <Button title="button" onPress={() => navigation.navigate('DrawerOpen')} />
})


问:
How do you use the jquery 'load' method to load a page fragment when passing a variable?
Not sure if this has been asked, but here it goes, given the following code...

```<code>$('#infoPane').load('showInfo.php #info');
</code>```

How do a pass variable to the page yet only just load the page fragment?

```<code>$('#imgPane').load('showInfo.php?q='+$q+ '#picture');
</code>```

The above code does not work so any help would be appreciated

答:
The resulting URL does not follow the "magic" syntax: <url> #<id-of-fragment-to-load>, but comes out as showInfo.php?q=<value-of-$q>#picture (no space). Try:

```<code>$('#imgPane').load('showInfo.php?q='+$q+' #picture');
</code>```

Alternatively, did you try passing the value via the second argument (data)?

```<code>$('#imgPane').load('showInfo.php #picture', {q: $q});
</code>```

Body:
Not sure if this has been asked, but here it goes, given the following code...

$('#infoPane').load('showInfo.php #info');

How do a pass variable to the page yet only just load the page fragment?

$('#imgPane').load('showInfo.php?q='+$q+ '#picture');

The above code does not work so any help would be appreciated

Body:
The resulting URL does not follow the "magic" syntax: <url> #<id-of-fragment-to-load>, but comes out as showInfo.php?q=<value-of-$q>#picture (no space). Try:

$('#imgPane').load('showInfo.php?q='+$q+' #picture');

Alternatively, did you try passing the value via the second argument (data)?

$('#imgPane').load('showInfo.php #picture', {q: $q});


问:
How to access attachment data programmatically in outlook if attachment is itself a mail
I am programmatically trying to get the attachment data in C# in following way :--

```<code>Microsoft.Office.Interop.Outlook.Attachment attachment = objMail.Attachments[attachmentIndex];

if (attachment.DisplayName.Equals("Test"))

{

   const string PR_ATTACH_DATA = "http://schemas.microsoft.com/mapi/proptag/0x37010102";

    byte[] attachmentData = attachment.PropertyAccessor.GetProperty(PR_ATTACH_DATA);

}
</code>```

Now my code is working fine if attachment is text file or image file. But if attachment is itself a mail, it throws the exception that property is unknown or can not be found.

Please suggest in which cases / type of attachments, this property "http://schemas.microsoft.com/mapi/proptag/0x37010102" will not work and in those cases, what would be alternative property / method to get the attachment data in byte array ?

Thanks

答:
PR_ATTACH_DATA_BIN is only present for the regular by-value attachments (PR_ATTACH_METHOD == ATTACH_BY_VALUE). Embedded message or OLE attachments do not expose that property - they use PR_ATTACH_DATA_OBJ which must be opened using IAttach::OpenProperty(IID_IStorage, ...) - take a look at the existing messages using OutlookSpy - I am its author - select the message, click IMessage button, go to GetAttachmentTable tab, double click on the attachment.

Also keep in mind that PropertyAccessor.GetProperty would only be able to retrieve that property for small attachments. For large attachments, PR_ATTACH_DATA_BIN must be opened as IStream using IAttach::OpenProperty(IID_IStorage, ...) - PropertyAccessor.GetProperty does not do that. You will need to use Extended MAPI (C++ or Delphi) or Redemption (I am its author) - it exposes RDOAttachment.AsArray / AsText / AsStream properties.

Body:
I am programmatically trying to get the attachment data in C# in following way :--

Microsoft.Office.Interop.Outlook.Attachment attachment = objMail.Attachments[attachmentIndex];

if (attachment.DisplayName.Equals("Test"))

{

   const string PR_ATTACH_DATA = "http://schemas.microsoft.com/mapi/proptag/0x37010102";

    byte[] attachmentData = attachment.PropertyAccessor.GetProperty(PR_ATTACH_DATA);

}

Now my code is working fine if attachment is text file or image file. But if attachment is itself a mail, it throws the exception that property is unknown or can not be found.

Please suggest in which cases / type of attachments, this property "http://schemas.microsoft.com/mapi/proptag/0x37010102" will not work and in those cases, what would be alternative property / method to get the attachment data in byte array ?

Thanks


问:
Why would SQL be very slow when doing updates?
Suddenly doing updates into a few tables have gotten 10 times slower than they used to be.  What are some good recommendations to determine root cause and optimization?  Could it be that indexing certain columns are causing updates to be slow?  Any other recommendations?

I guess more important than guesses would be help on the process of identifying the root cause or metrics around performance.

Is there anything in Fluent NHibernate that you can use to help identify the root cause of performance issues?

答:
1- First check if the table does not have locks

2- Recently implemented triggers

3- Database refresh may need index rebuilt.

4- Some predefind jobs is in process.

5- ANY UNKNOWN REASONS

Use some query analzer tools to see what is actually happening.


问:
How to copy to clipboard with GWT?
Couldn't find anything on this with a Google Search.

Does anyone know how to copy some text to the clipboard through GWT Java code?
I'd like to avoid the raw javascript injection solution.

Any help or pointers appreciated.

答:
Just wrap the provided answer https://stackoverflow.com/a/30810322/106261.

So, you pass in any text to a javascript native function/method, the js function creates a new element and copies to clipboard, and removes the element after copying.

No need for any libs with new browsers.

so :

```<code>public static native void copyTextToClipboard(String text) /*-{
        var textArea = document.createElement("textarea");
        //
        // *** This styling is an extra step which is likely not required. ***
        //
        // Why is it here? To ensure:
        // 1. the element is able to have focus and selection.
        // 2. if element was to flash render it has minimal visual impact.
        // 3. less flakyness with selection and copying which **might** occur if
        //    the textarea element is not visible.
        //
        // The likelihood is the element won't even render, not even a flash,
        // so some of these are just precautions. However in IE the element
        // is visible whilst the popup box asking the user for permission for
        // the web page to copy to the clipboard.
        //

        // Place in top-left corner of screen regardless of scroll position.
        textArea.style.position = 'fixed';
        textArea.style.top = 0;
        textArea.style.left = 0;

        // Ensure it has a small width and height. Setting to 1px / 1em
        // doesn't work as this gives a negative w/h on some browsers.
        textArea.style.width = '2em';
        textArea.style.height = '2em';

        // We don't need padding, reducing the size if it does flash render.
        textArea.style.padding = 0;

        // Clean up any borders.
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';

        // Avoid flash of white box if rendered for any reason.
        textArea.style.background = 'transparent';

        textArea.value = text;

        document.body.appendChild(textArea);

        textArea.select();

        try {
            var successful = document.execCommand('copy');
        } catch (err) {
            console.log('Unable to copy');
        }
        document.body.removeChild(textArea);
    }-*/;
</code>```

Title: How to copy to clipboard with GWT?

Body:
Just wrap the provided answer https://stackoverflow.com/a/30810322/106261.

So, you pass in any text to a javascript native function/method, the js function creates a new element and copies to clipboard, and removes the element after copying.

No need for any libs with new browsers.

so :

public static native void copyTextToClipboard(String text) /*-{
        var textArea = document.createElement("textarea");
        //
        // *** This styling is an extra step which is likely not required. ***
        //
        // Why is it here? To ensure:
        // 1. the element is able to have focus and selection.
        // 2. if element was to flash render it has minimal visual impact.
        // 3. less flakyness with selection and copying which **might** occur if
        //    the textarea element is not visible.
        //
        // The likelihood is the element won't even render, not even a flash,
        // so some of these are just precautions. However in IE the element
        // is visible whilst the popup box asking the user for permission for
        // the web page to copy to the clipboard.
        //

        // Place in top-left corner of screen regardless of scroll position.
        textArea.style.position = 'fixed';
        textArea.style.top = 0;
        textArea.style.left = 0;

        // Ensure it has a small width and height. Setting to 1px / 1em
        // doesn't work as this gives a negative w/h on some browsers.
        textArea.style.width = '2em';
        textArea.style.height = '2em';

        // We don't need padding, reducing the size if it does flash render.
        textArea.style.padding = 0;

        // Clean up any borders.
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';

        // Avoid flash of white box if rendered for any reason.
        textArea.style.background = 'transparent';

        textArea.value = text;

        document.body.appendChild(textArea);

        textArea.select();

        try {
            var successful = document.execCommand('copy');
        } catch (err) {
            console.log('Unable to copy');
        }
        document.body.removeChild(textArea);
    }-*/;


问:
jQuery code works for last iteration of php loop generated button
I'm creating a forum where people can vote on posts. The vote is called 'consents'.

```<code><?php
$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT 10";
$done = mysqli_query($conn, $postshow);
//$show = mysqli_fetch_assoc($done);

while ($show = mysqli_fetch_assoc($done)) {
    echo"<div class = 'comments'>";
    echo"<br>";
    echo"<br>";
    echo $show['post'];
    echo"<br>";
    echo"<p class = 'counter'>";
    echo $show['consents'];
    echo"</p>";
    echo"<br>";
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];
      $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){
    echo"<button id = \"consents$postid\">Consent This</button>";
      }
    echo"</div>";

}
?>
<script>
    var posterid = "<?php echo $userid;?>"
    var postid = "<?php echo $postid;?>"
    var voterid = "<?php echo $id;?>"
    var consents = "<?php echo $consents;?>"

$(document).ready(function () {
   $('#consents' + postid).click(function(){
    $(this).hide();
    $.post ("consentsideas.php", {
        dept: "ideas",
        task: "1",
        postid: postid,
        voterid: voterid,
        consents: consents,
        posterid: posterid
    });
    $(".counter").html(++consents);
   });
   $(".answer").mousedown(function(){
            $(".post_answer").show();
            });
   $(document).click(function(event) {
    if(!$(event.target).closest('.post_answer').length) {
        if($('.post_answer').is(":visible")) {
            $('.post_answer').hide();
        }
    }
});
  $(".post_answer").click(function(){
    var answer = $(".answer").val();
    $.post ("answerideas.php", {
        answer: answer,
        id: voterid
            });
    $(".answer").val('');
    });
}
  );
</script>
</code>```

But any button looped by the while loop, when clicked, only updates the CONSENTS counter for the last iteration of the while loop.
As you can see, I've made the button's id unique(I hope I did that correctly). So could anyone tell me where's the problem?

答:
```<code>echo"<button class = 'consents' data-postid = '$postid' data-posterid ='$userid' data-voterid = '$id' data-consents = '$consents' >Consent This</button>";
      }

}
?>
<script>

$(document).ready(function () {

   $('.consents').click(function(){
    var posterid = $(this).data('posterid');
   var postid = $(this).data('postid');
   var voterid = $(this).data('voterid');
  var consents = $(this).data('consents');

    $(this).hide();
    $.post ("consentsideas.php", {
        dept: "ideas",
        task: "1",
        postid: postid,
        voterid: voterid,
        consents: consents,
        posterid: posterid
    });
    $(".counter").html(++consents);
   });
   $(".answer").mousedown(function(){
            $(".post_answer").show();
            });
   $(document).click(function(event) {
    if(!$(event.target).closest('.post_answer').length) {
        if($('.post_answer').is(":visible")) {
            $('.post_answer').hide();
        }
    }
});
  $(".post_answer").click(function(){
    var answer = $(".answer").val();
    $.post ("answerideas.php", {
        answer: answer,
        id: voterid
            });
    $(".answer").val('');
    });
}
  );
</script>
</code>```

Now the consent button won't work. And also, I'm not seeing my 'post' button($(".post_answer"))

Body:
I'm creating a forum where people can vote on posts. The vote is called 'consents'.

<?php
$postshow = "SELECT * FROM ideas_1 ORDER BY consents DESC LIMIT 10";
$done = mysqli_query($conn, $postshow);
//$show = mysqli_fetch_assoc($done);

while ($show = mysqli_fetch_assoc($done)) {
    echo"
";
    echo"
";
    echo"
";
    echo $show['post'];
    echo"
";
    echo"
";
    echo $show['consents'];
    echo"
";
    echo"
";
    $postid = $show['postid'];
    $userid = $show['userid'];
    $consents = $show['consents'];
      $asd = "SELECT * FROM consents WHERE dept = 'ideas' and task = '1' and postid = '$postid' and voterid = '$id'";
      $doit = mysqli_query($conn, $asd);
      $exist = mysqli_num_rows($doit);
      if ($exist == 0){
    echo"<button id = \"consents$postid\">Consent This</button>";
      }
    echo"
";

}
?>

But any button looped by the while loop, when clicked, only updates the CONSENTS counter for the last iteration of the while loop.
As you can see, I've made the button's id unique(I hope I did that correctly). So could anyone tell me where's the problem?

Body:
echo"<button class = 'consents' data-postid = '$postid' data-posterid ='$userid' data-voterid = '$id' data-consents = '$consents' >Consent This</button>";
      }

}
?>
<script>

$(document).ready(function () {

   $('.consents').click(function(){
    var posterid = $(this).data('posterid');
   var postid = $(this).data('postid');
   var voterid = $(this).data('voterid');
  var consents = $(this).data('consents');

    $(this).hide();
    $.post ("consentsideas.php", {
        dept: "ideas",
        task: "1",
        postid: postid,
        voterid: voterid,
        consents: consents,
        posterid: posterid
    });
    $(".counter").html(++consents);
   });
   $(".answer").mousedown(function(){
            $(".post_answer").show();
            });
   $(document).click(function(event) {
    if(!$(event.target).closest('.post_answer').length) {
        if($('.post_answer').is(":visible")) {
            $('.post_answer').hide();
        }
    }
});
  $(".post_answer").click(function(){
    var answer = $(".answer").val();
    $.post ("answerideas.php", {
        answer: answer,
        id: voterid
            });
    $(".answer").val('');
    });
}
  );
</script>

Now the consent button won't work. And also, I'm not seeing my 'post' button($(".post_answer"))


问:
Airflow dag bash task lag on remote executions
I am experimenting with Airflow to replace our existing cron orchestration and everything looks promising.   I have successfully installed and gotten a dag to be scheduled and executed, but I noticed that their is a significant delay between each of the tasks I have specified (at least 15 minutes to 60 minutes).

My dag is defined as follows

Am I missing something to make them run one right after the other?

I am not using celery
both scheduler and webserver are running on the same host
and yes - need to call for a remote execution (working on some form of local until then)
and no cannot install airflow on the remote server
Dag should run once a day at 1 am UTC, follow the set path of tasks I have given it.

```<code>import airflow
from builtins import range
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.models import DAG
from datetime import datetime, timedelta

args = {
    'owner': 'user1',
    'depends_on_past': False,
    'start_date': airflow.utils.dates.days_ago(2),
    'email': ['data-etl-errors@user1.com'],
    'email_on_failure': True,
    'email_on_retry': False,
    'wait_for_downstream': True,
    'schedule_interval': None,
    'depends_on_past': True,
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

 dag = DAG(
       dag_id='airflow_pt1'
     , default_args=args
     , schedule_interval='0 1 * * *'
     , dagrun_timeout=timedelta(hours=8))

 task1 = BashOperator(
       task_id='task1'
     , bash_command='ssh user1@remoteserver /path/to/remote/execution/script_task1.sh'
     , dag=dag,env=None, output_encoding='utf-8')

 task2 = BashOperator(
       task_id='task2'
     , bash_command='ssh user1@remoteserver /path/to/remote/execution/script_task2.sh'
     , dag=dag,env=None, output_encoding='utf-8')

 task3 = BashOperator(
       task_id='task3'
     , bash_command='ssh user1@remoteserver /path/to/remote/execution/script_task3.sh'
     , dag=dag,env=None, output_encoding='utf-8')

 task4 = BashOperator(
       task_id='task4'
     , bash_command='ssh user1@remoteserver /path/to/remote/execution/script_task4.sh'
     , dag=dag,env=None, output_encoding='utf-8')

 task2.set_upstream(task1)
 task3.set_upstream(task1)
 task4.set_upstream(task2)
</code>```

Note I have not executed airflow backfill (is that important?)

答:
Found the issue
I had not altered the configuration from sequential to localExecutor in airflow.cfg file

I found my answer through https://stlong0521.github.io/20161023%20-%20Airflow.html

and watching the detailed video in https://www.youtube.com/watch?v=Pr0FrvIIfTU

Body:
I am experimenting with Airflow to replace our existing cron orchestration and everything looks promising.   I have successfully installed and gotten a dag to be scheduled and executed, but I noticed that their is a significant delay between each of the tasks I have specified (at least 15 minutes to 60 minutes).

My dag is defined as follows

Am I missing something to make them run one right after the other?

I am not using celery
both scheduler and webserver are running on the same host
and yes - need to call for a remote execution (working on some form of local until then)
and no cannot install airflow on the remote server
Dag should run once a day at 1 am UTC, follow the set path of tasks I have given it.

import airflow
from builtins import range
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.models import DAG
from datetime import datetime, timedelta

args = {
    'owner': 'user1',
    'depends_on_past': False,
    'start_date': airflow.utils.dates.days_ago(2),
    'email': ['data-etl-errors@user1.com'],
    'email_on_failure': True,
    'email_on_retry': False,
    'wait_for_downstream': True,
    'schedule_interval': None,
    'depends_on_past': True,
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

 dag = DAG(
       dag_id='airflow_pt1'
     , default_args=args
     , schedule_interval='0 1 * * *'
     , dagrun_timeout=timedelta(hours=8))

 task1 = BashOperator(
       task_id='task1'
     , bash_command='ssh user1@remoteserver /path/to/remote/execution/script_task1.sh'
     , dag=dag,env=None, output_encoding='utf-8')

 task2 = BashOperator(
       task_id='task2'
     , bash_command='ssh user1@remoteserver /path/to/remote/execution/script_task2.sh'
     , dag=dag,env=None, output_encoding='utf-8')

 task3 = BashOperator(
       task_id='task3'
     , bash_command='ssh user1@remoteserver /path/to/remote/execution/script_task3.sh'
     , dag=dag,env=None, output_encoding='utf-8')

 task4 = BashOperator(
       task_id='task4'
     , bash_command='ssh user1@remoteserver /path/to/remote/execution/script_task4.sh'
     , dag=dag,env=None, output_encoding='utf-8')

 task2.set_upstream(task1)
 task3.set_upstream(task1)
 task4.set_upstream(task2)

Note I have not executed airflow backfill (is that important?)


问:
How do I repeat the number of times in a PHP loop?
There is an array of any with the keys permissible from 1 to 10.

There is a cycle from 1 to the current day (let's say the number today is 7 every day corresponds to a new day).

How to make it so that in the cycle from one to today we receive the body of the array by the key?

From 1 to 10 it is understandable, but how to repeat the array keys in a loop. Suppose there will be a thirtieth day, it should show the body of the array with key 10.

```<code>        public function getRation($getration)
{
    //ration - it's day
    $ration = RationDay::all()->toArray();
    $count = count($ration);
    $s=1;
    for ($i=0; $i<$getration; $i++)
    {
        $kekes = $s++;
        if($s<=$count){
         if($kekes>=$count){
             $kekes = 1;
         }else{
        if(isset($ration[$kekes])){
                $s=1;
        }else{
            $kek = $ration[$kekes];
        }
        }
    }
</code>```

This is one of several solutions.

Thank you in advance!

P.S. The day goes separately from the array, the day I get from angularjs through request. If the day is larger than the array, then it should repeat the output of the keys is valid. Example: Day 13 - Key = 3.

I for example tried to do it all through for, but something is not successful.

Upd. There was an interesting idea, to receive the remainder of the division. But the remainder of the division will not work, because if there is an array with keys from 1 to 6. Then let's say it does not work out that 9 day is the key 3.

UPD 2. Here's the solution if anyone should. Thank you all for the response!

```<code>//get array
$ration = RationDay::all()->toArray();

$count = count($ration);
//getration - it day
$day = $getration;

if ($day >= ($maxDay = max(array_keys($ration)))) {
    $day = $day % $maxDay;
}

$getting = $ration[$day];

return $getting;
</code>```

答:
Here's the solution if anyone should. Thank you all for the response!</p>

```<code>    //get array
    $ration = RationDay::all()->toArray();

    $count = count($ration);
    //getration - it day
    $day = $getration;

    if ($day >= ($maxDay = max(array_keys($ration)))) {
        $day = $day % $maxDay;
    }

    $getting = $ration[$day];

    return $getting;
</code>```

Body:
There is an array of any with the keys permissible from 1 to 10.

There is a cycle from 1 to the current day (let's say the number today is 7 every day corresponds to a new day).

How to make it so that in the cycle from one to today we receive the body of the array by the key?

From 1 to 10 it is understandable, but how to repeat the array keys in a loop. Suppose there will be a thirtieth day, it should show the body of the array with key 10.

        public function getRation($getration)
{
    //ration - it's day
    $ration = RationDay::all()->toArray();
    $count = count($ration);
    $s=1;
    for ($i=0; $i<$getration; $i++)
    {
        $kekes = $s++;
        if($s<=$count){
         if($kekes>=$count){
             $kekes = 1;
         }else{
        if(isset($ration[$kekes])){
                $s=1;
        }else{
            $kek = $ration[$kekes];
        }
        }
    }

This is one of several solutions.

Thank you in advance!

P.S. The day goes separately from the array, the day I get from angularjs through request. If the day is larger than the array, then it should repeat the output of the keys is valid. Example: Day 13 - Key = 3.

I for example tried to do it all through for, but something is not successful.

Upd. There was an interesting idea, to receive the remainder of the division. But the remainder of the division will not work, because if there is an array with keys from 1 to 6. Then let's say it does not work out that 9 day is the key 3.

UPD 2. Here's the solution if anyone should. Thank you all for the response!

//get array
$ration = RationDay::all()->toArray();

$count = count($ration);
//getration - it day
$day = $getration;

if ($day >= ($maxDay = max(array_keys($ration)))) {
    $day = $day % $maxDay;
}

$getting = $ration[$day];

return $getting;


问:
Can't send JSON String to server in API 25
Hey I want to send JSON string to server and get the response in JSON array ,

Please help me figure out what to use to send the json array and get the response back in json format my code is

```<code>public class Welcome extends AppCompatActivity {
    private static final String LOGIN_REQUEST_URL = "http://demo4u.org/leaveapp/ws/login.php";
    JSONObject request = new JSONObject();

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

        final EditText user_email = (EditText) findViewById(R.id.username);
        final EditText user_password = (EditText) findViewById(R.id.password);
        final Button signin = (Button) findViewById(R.id.signin);
        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String uname = user_email.getText().toString();
                final String pass = user_password.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            try {
                                JSONObject jsonresponse = new JSONObject(response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                request.put("user_email", uname);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                request.put("user_password", pass);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            final TextView show = (TextView) findViewById(R.id.res);
                            String jsonstring = request.toString();
                            JsonObjectRequest jsonobjreq = new JsonObjectRequest(
                                    Method.POST, LOGIN_REQUEST_URL, jsonstring,
                                    new Response.Listener<JSONObject>() {
                                        @Override
                                        public void onResponse(JSONObject response) {
                                            //Log.d(Tag, toString());
                                            Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                            show.setText(response.toString());
                                        }
                                    }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    //Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                    VolleyLog.d(Tag, "Error : " + error.getMessage());
                                }
                            }) {
                                @Override
                                public Map<String, String> getHeaders() throws AuthFailureError {
                                    HashMap<String, String> headers = new HashMap<String, String>();
                                    headers.put("Content-Type", "application/json; charset=utf-8");
                                    return headers;
                                }

                            };

                        } catch (JSONException e) {
                        }
</code>```

Please write the code that I have to replace with the above code.

答:
If you are getting JSONArray in return then your

```<code> new Response.Listener<JSONObject>() {
                                    @Override
                                    public void onResponse(JSONObject response) {
                                        //Log.d(Tag, toString());
                                        Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                        show.setText(response.toString());
                                    }
                                }
</code>```

Should be like:

```<code> new Response.Listener<JSONArray>() {
                                    @Override
                                    public void onResponse(JSONArray response) {
                                        //Log.d(Tag, toString());
                                        Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                        show.setText(response.toString());
                                    }
                                }
</code>```

And if you want to send JSONArray with request then you should use JsonArrayRequest instead of JsonObjectRequest.

Body:
Hey I want to send JSON string to server and get the response in JSON array ,

Please help me figure out what to use to send the json array and get the response back in json format my code is

public class Welcome extends AppCompatActivity {
    private static final String LOGIN_REQUEST_URL = "http://demo4u.org/leaveapp/ws/login.php";
    JSONObject request = new JSONObject();

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

        final EditText user_email = (EditText) findViewById(R.id.username);
        final EditText user_password = (EditText) findViewById(R.id.password);
        final Button signin = (Button) findViewById(R.id.signin);
        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String uname = user_email.getText().toString();
                final String pass = user_password.getText().toString();
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            try {
                                JSONObject jsonresponse = new JSONObject(response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                request.put("user_email", uname);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                request.put("user_password", pass);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            final TextView show = (TextView) findViewById(R.id.res);
                            String jsonstring = request.toString();
                            JsonObjectRequest jsonobjreq = new JsonObjectRequest(
                                    Method.POST, LOGIN_REQUEST_URL, jsonstring,
                                    new Response.Listener<JSONObject>() {
                                        @Override
                                        public void onResponse(JSONObject response) {
                                            //Log.d(Tag, toString());
                                            Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                            show.setText(response.toString());
                                        }
                                    }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    //Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                    VolleyLog.d(Tag, "Error : " + error.getMessage());
                                }
                            }) {
                                @Override
                                public Map<String, String> getHeaders() throws AuthFailureError {
                                    HashMap<String, String> headers = new HashMap<String, String>();
                                    headers.put("Content-Type", "application/json; charset=utf-8");
                                    return headers;
                                }

                            };

                        } catch (JSONException e) {
                        }

Please write the code that I have to replace with the above code.

Body:
If you are getting JSONArray in return then your

 new Response.Listener<JSONObject>() {
                                    @Override
                                    public void onResponse(JSONObject response) {
                                        //Log.d(Tag, toString());
                                        Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                        show.setText(response.toString());
                                    }
                                }

Should be like:

 new Response.Listener<JSONArray>() {
                                    @Override
                                    public void onResponse(JSONArray response) {
                                        //Log.d(Tag, toString());
                                        Toast.makeText(Welcome.this,"Volley Error",Toast.LENGTH_LONG).show();
                                        show.setText(response.toString());
                                    }
                                }

And if you want to send JSONArray with request then you should use JsonArrayRequest instead of JsonObjectRequest.


问:
keep selected tab on page refresh using angular 2 dynamic routing
I am trying to refresh selected tab(suppose tab2 ) but only i am getting UI load for the same tab and its highlights to tab1. I am not getting to refresh same tab in angular 2 using dynamic routing and bootstrap.

Here is my code for your reference

```<code><a routerLink="/tab1" class="placeholder col-xs-2 item"  (click)="onMenuClick('tab1')" *ngIf="authorizationService.isTab1View">
            <span class="placeholderimg"><i id="tabCust" class="fa fa-users fa-menu-top" [style.color]="tab1Selected"></i></span>
            <p class="placeholdertext">{{ 'MENU.tab1' | translate }}</p>
        </a>

        <a routerLink="/tab2" class="placeholder col-xs-2 item" (click)="onMenuClick('tab2')" *ngIf="authorizationService.isTab2View">
            <span class="placeholderimg"><i id="tabSite" class="fa fa-building-o fa-menu-top" [style.color]="tab2Selected"></i></span>
            <p class="placeholdertext">{{ 'MENU.tab2' | translate }}</p>
        </a>
</code>```

I am new in angular 2. Can anyone help me to resolve the problem.

答:
Use routerLinkActive directive in your anchor tag like this -

```<code><a routerLink="/tab1" routerLinkActive="active-link" class="placeholder col-xs-2 item"  (click)="onMenuClick('tab1')" *ngIf="authorizationService.isTab1View">
    <span class="placeholderimg"><i id="tabCust" class="fa fa-users fa-menu-top" [style.color]="tab1Selected"></i></span>
    <p class="placeholdertext">{{ 'MENU.tab1' | translate }}</p>
</a>

<a routerLink="/tab2" routerLinkActive="active-link" class="placeholder col-xs-2 item" (click)="onMenuClick('tab2')" *ngIf="authorizationService.isTab2View">
    <span class="placeholderimg"><i id="tabSite" class="fa fa-building-o fa-menu-top" [style.color]="tab2Selected"></i></span>
    <p class="placeholdertext">{{ 'MENU.tab2' | translate }}</p>
</a>
</code>```

Where active-link is a css class that you can use to customize your active anchor tag.

Body:
I am trying to refresh selected tab(suppose tab2 ) but only i am getting UI load for the same tab and its highlights to tab1. I am not getting to refresh same tab in angular 2 using dynamic routing and bootstrap.

Here is my code for your reference

{{ 'MENU.tab1' | translate }}

{{ 'MENU.tab2' | translate }}

I am new in angular 2. Can anyone help me to resolve the problem.

Body:
Use routerLinkActive directive in your anchor tag like this -

<a routerLink="/tab1" routerLinkActive="active-link" class="placeholder col-xs-2 item"  (click)="onMenuClick('tab1')" *ngIf="authorizationService.isTab1View">
    <span class="placeholderimg"><i id="tabCust" class="fa fa-users fa-menu-top" [style.color]="tab1Selected"></i></span>
    <p class="placeholdertext">{{ 'MENU.tab1' | translate }}</p>
</a>

<a routerLink="/tab2" routerLinkActive="active-link" class="placeholder col-xs-2 item" (click)="onMenuClick('tab2')" *ngIf="authorizationService.isTab2View">
    <span class="placeholderimg"><i id="tabSite" class="fa fa-building-o fa-menu-top" [style.color]="tab2Selected"></i></span>
    <p class="placeholdertext">{{ 'MENU.tab2' | translate }}</p>
</a>

Where active-link is a css class that you can use to customize your active anchor tag.


问:
Input refs vs Input.value for React JS
I am following a reactJS tutorial series and I am confused about the difference between finding the input tags value vs having an input ref='thing' in ReactJS for form handling.

For example...

```<code><input id='user' name='username'/>
</code>```

vs

```<code><input id='user' ref='username'/>
</code>```

is there any difference between doing:

```<code>formHandleFunction(){
//handle document.getElementById('user').value;
}
</code>```

vs

```<code>formHandleFunction(){
//handle this.refs.username.value;
}
</code>```

答:
Typically we use 'value' with a controlled component and 'ref' with an uncontrolled component.

From FB Documentation:

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

Go through these links to get a better understanding.

https://facebook.github.io/react/docs/uncontrolled-components.html
https://facebook.github.io/react/docs/forms.html#controlled-components

Title: Input refs vs Input.value for React JS

Body:
I am following a reactJS tutorial series and I am confused about the difference between finding the input tags value vs having an input ref='thing' in ReactJS for form handling.

For example...

<input id='user' name='username'/>

vs

<input id='user' ref='username'/>

is there any difference between doing:

formHandleFunction(){
//handle document.getElementById('user').value;
}

vs

formHandleFunction(){
//handle this.refs.username.value;
}


问:
How to find elements in array that contain a given substring?
I have 3 strings, I would like to get only the equal strings of them, something like this:

```<code>$Var1 = "Sant";
$Array[] = "Hello Santa Claus";   // Name_1
$Array[] = "Santa Claus";         // Name_2
</code>```

I would like to get both of them because they match "Sant".

With my code I only get Name_2

```<code>$len = strlen($Var1);
foreach($Array as $name)
{
   if (  stristr($Var1, substr($name, 0, $len)))
   {
     echo $name;
   }
}
</code>```

I understand why I only get Name_2, but I don't know how to solve this situation.

答:
If you want to "filter" your "array", I recommend using the php function called array_filter() like this:

Code:

```<code>$Var1 = "Sant";
$Array=["Hello Santa Claus","Easter Bunny","Santa Claus"];

var_export(array_filter($Array,function($v)use($Var1){return strpos($v,$Var1)!==false;}));
</code>```

Output:

```<code>array (
  0 => 'Hello Santa Claus',
  2 => 'Santa Claus',
)
</code>```

array_filter() needs the array as the first parameter, and the search term inside of use().  The return portion tells the function to retain the element if true and remove the element if false.

The benefit to this function over a foreach loop is that no output variables needs to be declared (unless you want one).  It performs the same iterative action.

Body:
I have 3 strings, I would like to get only the equal strings of them, something like this:

$Var1 = "Sant";
$Array[] = "Hello Santa Claus";   // Name_1
$Array[] = "Santa Claus";         // Name_2

I would like to get both of them because they match "Sant".

With my code I only get Name_2

$len = strlen($Var1);
foreach($Array as $name)
{
   if (  stristr($Var1, substr($name, 0, $len)))
   {
     echo $name;
   }
}

I understand why I only get Name_2, but I don't know how to solve this situation.

Body:
If you want to "filter" your "array", I recommend using the php function called array_filter() like this:

Code:

$Var1 = "Sant";
$Array=["Hello Santa Claus","Easter Bunny","Santa Claus"];

var_export(array_filter($Array,function($v)use($Var1){return strpos($v,$Var1)!==false;}));

Output:

array (
  0 => 'Hello Santa Claus',
  2 => 'Santa Claus',
)

array_filter() needs the array as the first parameter, and the search term inside of use().  The return portion tells the function to retain the element if true and remove the element if false.

The benefit to this function over a foreach loop is that no output variables needs to be declared (unless you want one).  It performs the same iterative action.


问:
Using TemplateBinding in ObjectAnimationUsingKeyFrames
I try to set the background color of a control when mouse is over it. I try to do it via the visual state manager. I was able to get the following code running:

```<code><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Control.Background" Storyboard.TargetName="BorderBackground">
    <DiscreteObjectKeyFrame KeyTime="0">
        <DiscreteObjectKeyFrame.Value>
            <SolidColorBrush Color="#FF123456" />
        </DiscreteObjectKeyFrame.Value>
    </DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</code>```

But i do not want to set the color in the template, but bind it to a value of the control. I tried it with the 'Tag'-property in the following way:

```<code><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Control.Background" Storyboard.TargetName="BorderBackground">
    <DiscreteObjectKeyFrame KeyTime="0">
        <DiscreteObjectKeyFrame.Value>
            <SolidColorBrush Color="{TemplateBinding Tag}" />
        </DiscreteObjectKeyFrame.Value>
    </DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</code>```

and setting the Tag-Property of the control that is using this style to '#FF123456'.

But this doesn't work. It doesn't left me an error message, it simply doesn't change the backgroundcolor. Anybody knows, what the problem might be?

Thanks in advance,

Frank

答: Unfortunately the way you're trying to do it won't work in Silverlight. The VisualStateManager animations are not part of the display tree, so you can't use binding. You have options though, StaticResources (aka setting up colours in the resource dictionary) and code based animations are different workarounds (depending on exactly what you want to do). For the latter check out a thread where I asked a similar question: How can I animate a property dynamically in a Silverlight 4 UserControl?</p>

Body:
I try to set the background color of a control when mouse is over it. I try to do it via the visual state manager. I was able to get the following code running:

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Control.Background" Storyboard.TargetName="BorderBackground">
    <DiscreteObjectKeyFrame KeyTime="0">
        <DiscreteObjectKeyFrame.Value>
            <SolidColorBrush Color="#FF123456" />
        </DiscreteObjectKeyFrame.Value>
    </DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>

But i do not want to set the color in the template, but bind it to a value of the control. I tried it with the 'Tag'-property in the following way:

<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Control.Background" Storyboard.TargetName="BorderBackground">
    <DiscreteObjectKeyFrame KeyTime="0">
        <DiscreteObjectKeyFrame.Value>
            <SolidColorBrush Color="{TemplateBinding Tag}" />
        </DiscreteObjectKeyFrame.Value>
    </DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>

and setting the Tag-Property of the control that is using this style to '#FF123456'.

But this doesn't work. It doesn't left me an error message, it simply doesn't change the backgroundcolor. Anybody knows, what the problem might be?

Thanks in advance,

Frank