问:
Can an ActionBlock link to another ActionBlock with more parameters in it?
I am still getting a hang of TPL DataFlow so bear with me.

My application requires that queue is executed upon in parallel while retaining its order. This led me to the DataFlow library and what I am trying to do. I am wondering if there is a way to link one ActionBlock to another and the second taking a value from the first to operate on.

Pseudo-example:

```<code>var block1 = new ActionBlock<ByteBuffer>(buffer => {
   // code generating a hash of the byte buffer to pass to next block
    ulong hash = generateHash(buffer);
   // this is what i would like to pass to the next ActionBlock
    var tup = Tuple<ByteBuffer, ulong>(buffer, along);
}, dataFlowOpts);
var block2 = new ActionBlock<Tuple<ByteBuffer, ulong>(tup => {
    /* code to act on the buffer and hash */
}, dataFlowOpts);

block1.LinkTo(block2); // Is there something like this that would use the correct params?
</code>```

Is what I'm trying to do possible? Does this even make sense? The reason I have these separated into two ActionBlocks is I would like to reuse block2 in another codepath (hashing the contents of a different ByteBuffer differently.)

Maybe there is a better way? Really, I am just trying to hash objects as they come in in a concurrent fashion while retaining FIFO order as it's way too slow to hash these synchronously.

答:
Just use the TransformBlock:

```<code>var block1 = new TransformBlock<ByteBuffer, Tuple<ByteBuffer, ulong>>(buffer => {
    // code generating a hash of the byte buffer to pass to next block
    ulong hash = generateHash(buffer);
    // this is what i would like to pass to the next ActionBlock
    return Tuple<ByteBuffer, ulong>(buffer, along);
}, dataFlowOpts);
var block2 = new ActionBlock<Tuple<ByteBuffer, ulong>(tup => {
    /* code to act on the buffer and hash */
}, dataFlowOpts);

block1.LinkTo(block2); // Is there something like this that would use the correct params?
</code>```

Or, probably better option to use a DTO class with two properties: buffer and hash, as Tuple isn't much readable. Also, consider a new C# feature about named tuples.

Body:
I am still getting a hang of TPL DataFlow so bear with me.

My application requires that queue is executed upon in parallel while retaining its order. This led me to the DataFlow library and what I am trying to do. I am wondering if there is a way to link one ActionBlock to another and the second taking a value from the first to operate on.

Pseudo-example:

var block1 = new ActionBlock<ByteBuffer>(buffer => {
   // code generating a hash of the byte buffer to pass to next block
    ulong hash = generateHash(buffer);
   // this is what i would like to pass to the next ActionBlock
    var tup = Tuple<ByteBuffer, ulong>(buffer, along);
}, dataFlowOpts);
var block2 = new ActionBlock<Tuple<ByteBuffer, ulong>(tup => {
    /* code to act on the buffer and hash */
}, dataFlowOpts);

block1.LinkTo(block2); // Is there something like this that would use the correct params?

Is what I'm trying to do possible? Does this even make sense? The reason I have these separated into two ActionBlocks is I would like to reuse block2 in another codepath (hashing the contents of a different ByteBuffer differently.)

Maybe there is a better way? Really, I am just trying to hash objects as they come in in a concurrent fashion while retaining FIFO order as it's way too slow to hash these synchronously.

Body:
Just use the TransformBlock:

var block1 = new TransformBlock<ByteBuffer, Tuple<ByteBuffer, ulong>>(buffer => {
    // code generating a hash of the byte buffer to pass to next block
    ulong hash = generateHash(buffer);
    // this is what i would like to pass to the next ActionBlock
    return Tuple<ByteBuffer, ulong>(buffer, along);
}, dataFlowOpts);
var block2 = new ActionBlock<Tuple<ByteBuffer, ulong>(tup => {
    /* code to act on the buffer and hash */
}, dataFlowOpts);

block1.LinkTo(block2); // Is there something like this that would use the correct params?

Or, probably better option to use a DTO class with two properties: buffer and hash, as Tuple isn't much readable. Also, consider a new C# feature about named tuples.


来源: stackexchange

问:
checking for URL validity in VB.net
I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :

```<code>Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate

    Try
        Dim uri As New Uri(args.Value)
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim reader As String = New StreamReader(stream).ReadToEnd()
        args.IsValid = True
    Catch ex As Exception
        args.IsValid = False
    End Try

End Sub
</code>```

I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".

What is wrong with this code ?

Update :

I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)

```<code>function testURLValide(sender, args)
{
    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("HEAD", args.Value, false);
    xmlhttp.send(null);

    if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}
</code>```

答:
I put your code into LINQPad and tested it out and it worked just fine...
The only difference is args.Value.

```<code>Dim uri As New Uri("http://www.google.com")
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(uri)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Dim reader As String = New StreamReader(stream).ReadToEnd()

reader.Dump()
</code>```

<!doctype html><meta
  http-equiv="content-type"
  content="text/html;
  charset=ISO-8859-1"><title>Google</title>............

ContentLicense: CC BY-SA 2.5

Title: checking for URL validity in VB.net

Body:
I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :

Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate

    Try
        Dim uri As New Uri(args.Value)
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim reader As String = New StreamReader(stream).ReadToEnd()
        args.IsValid = True
    Catch ex As Exception
        args.IsValid = False
    End Try

End Sub

I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".

What is wrong with this code ?

Update :

I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)

function testURLValide(sender, args)
{
    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("HEAD", args.Value, false);
    xmlhttp.send(null);

    if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}

Body:
I put your code into LINQPad and tested it out and it worked just fine...
The only difference is args.Value.

Dim uri As New Uri("http://www.google.com")
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(uri)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Dim reader As String = New StreamReader(stream).ReadToEnd()

reader.Dump()

<!doctype html><html><head><meta
  http-equiv="content-type"
  content="text/html;
  charset=ISO-8859-1"><title>Google</title>............


问:
Android Studio execution failed for task 'app\build\intermediates\transforms\proguard\debug\jars\3\1f\main.jar'.'
I updated android studio from 2.1.2 to 2.3 and and gradle from 2.14.1 to 3.4.
After I run my project I am encountering the following error

```<code>Error:Execution failed for task ':app:packageDebug'.
> java.io.IOException: Failed to read zip file 'D:\MyAndroidProject\app\build\intermediates\transforms\proguard\debug\jars\3\1f\main.jar'.
</code>```

Any feedback is welcomed

答:
It looks like a bug in the gradle plugin, try to downgrade used plugin:
In project level build.gradle use gradle plugin version 2.2.3 - it works for me:

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

Restart Android studio after change and it should works.

ContentLicense: CC BY-SA 3.0

Body:
I updated android studio from 2.1.2 to 2.3 and and gradle from 2.14.1 to 3.4.
After I run my project I am encountering the following error

Error:Execution failed for task ':app:packageDebug'.
> java.io.IOException: Failed to read zip file 'D:\MyAndroidProject\app\build\intermediates\transforms\proguard\debug\jars\3\1f\main.jar'.

Any feedback is welcomed

Body:
It looks like a bug in the gradle plugin, try to downgrade used plugin:
In project level build.gradle use gradle plugin version 2.2.3 - it works for me:

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

Restart Android studio after change and it should works.


问:
Replace empty alt tag on  tag
I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags.
For example:

What I wish to have:

So:
I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

```<code>preg_match_all('/<img[^>]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }
</code>```

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?

答:
You can use DOMDocument to achieve your requirement. Below is one of the sample code for your reference:

```<code><?php
$html = '<a href="http://example.com" rel="nofollow external">test</a>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//a[contains(concat(' ', normalize-space(@rel), ' '), ' external ')]");
foreach($nodes as $node) {
    $node->setAttribute('href', 'http://example.org');
}

?>
</code>```

Title: Replace empty alt tag on <img> tag

Body:
I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags.
For example:

What I wish to have:

So:
I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

preg_match_all('/]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?

Body:
You can use DOMDocument to achieve your requirement. Below is one of the sample code for your reference:

<?php
$html = '<a href="http://example.com" rel="nofollow external">test</a>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//a[contains(concat(' ', normalize-space(@rel), ' '), ' external ')]");
foreach($nodes as $node) {
    $node->setAttribute('href', 'http://example.org');
}

?>


问:
Xaml pass bound property to command
I have a TextBox bound to a string property on the ViewModel, and I have a Button with a Command. Now I want to pass the property itself if possible as a CommandParameter.
Is this possible?

Xaml part:

```<code><TextBox Text="{Binding FilePath, UpdateSourceTrigger=PropertyChanged}"/>
<Button Command="{Binding BrowseCommand}" CommandParameter="{Binding FilePath}" Content="..." />
</code>```

And the Command looks like this, but what type do I have to put instead of the RelayCommand<?> and what do I need to bind the CommandParameter to?

```<code>public ICommand BrowseCommand => this.browseCommand ?? (this.browseCommand = new RelayCommand<?>(this.Browse));
</code>```

答:
This should work if you are using the RelayCommand<T> class from MvvmLight:

```<code>public ICommand BrowseCommand => this.browseCommand ?? (this.browseCommand = new RelayCommand<string>(this.Browse));

private void Browse(string obj)
{

}
</code>```

Title: Xaml pass bound property to command

Body:
I have a TextBox bound to a string property on the ViewModel, and I have a Button with a Command. Now I want to pass the property itself if possible as a CommandParameter.
Is this possible?

Xaml part:

<TextBox Text="{Binding FilePath, UpdateSourceTrigger=PropertyChanged}"/>
<Button Command="{Binding BrowseCommand}" CommandParameter="{Binding FilePath}" Content="..." />

And the Command looks like this, but what type do I have to put instead of the RelayCommand<?> and what do I need to bind the CommandParameter to?

public ICommand BrowseCommand => this.browseCommand ?? (this.browseCommand = new RelayCommand<?>(this.Browse));

Body:
This should work if you are using the RelayCommand<T> class from MvvmLight:

public ICommand BrowseCommand => this.browseCommand ?? (this.browseCommand = new RelayCommand<string>(this.Browse));

private void Browse(string obj)
{

}


问:
PG::ConnectionBad: FATAL: password authentication failed for user "alphauser"
I'm working on an application in Rails for my college. The application was started by the students from previous year and now it's me and my colleagues turn to continue work on it. I took the application from github, I run bundle install, but when to run rake db:migrate I got this PG::ConnectionBad: FATAL:  password authentication failed for user "alphauser".
In  database.yml I have these

```<code> development:
  adapter: postgresql
  encoding: unicode
  database: alpha_database
  host: localhost
  pool: 5
  username: alphauser
  password: alphapassword
</code>```

I don't know what to do in this case.

答:
Try to use:

sudo -u postgres createuser --interactive --pwprompt

to add the role and the password

Body:
I'm working on an application in Rails for my college. The application was started by the students from previous year and now it's me and my colleagues turn to continue work on it. I took the application from github, I run bundle install, but when to run rake db:migrate I got this PG::ConnectionBad: FATAL:  password authentication failed for user "alphauser".
In  database.yml I have these

 development:
  adapter: postgresql
  encoding: unicode
  database: alpha_database
  host: localhost
  pool: 5
  username: alphauser
  password: alphapassword

I don't know what to do in this case.


问:
Why does this Javascript example copy the variable value instead of pass by reference?
In Javascript The Good Parts, it states:

So I would expect the following code example to output 1001 since "objects are never copied but passed around by reference", so why does it output 0000?

```<code>var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
page_item.access_groups.member = '0000';
var member = page_item.access_groups.member;
member = '1001';

$('p#test').html(page_item.access_groups.member); //should be "1001" but is "0000"
</code>```

Added:

@Gareth @David, thanks, this is what I was trying to show in this example, works:

```<code>var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
var page_item2 = page_item;
page_item2.access_groups.developer = '1001';

$('p#test').html(page_item.access_groups.developer); //is '1001'
</code>```

答:
This is probably getting bashed by JS-Gurus but basically it goes down like this:

Objects are passed by reference.

Strings (numbers, etc... basically 1 dimensional variables) are passed by value.

I did try and understand the lengthy explanations on data types but I seriously needed some work done and haven't gotten time to look at it more closely.

Body:
In Javascript The Good Parts, it states:

So I would expect the following code example to output 1001 since "objects are never copied but passed around by reference", so why does it output 0000?

var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
page_item.access_groups.member = '0000';
var member = page_item.access_groups.member;
member = '1001';

$('p#test').html(page_item.access_groups.member); //should be "1001" but is "0000"

Added:

@Gareth @David, thanks, this is what I was trying to show in this example, works:

var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
var page_item2 = page_item;
page_item2.access_groups.developer = '1001';

$('p#test').html(page_item.access_groups.developer); //is '1001'


问:
How to see publisher logs from browser in AEM?
How to see publisher logs from browser ?

I tried with "http://localhost:4503/bin/crxde/logs?tail=1000".
But i didn't get logs. Is there any way to enable this?

答:
Use this

http://localhost:4503/system/console/slinglog/tailer.txt?tail=600&name=/logs/error.log

Change error.log to other file as needed.


问:
Wrong LINQ request
Please look at my code below

```<code>        var result = (from c in db.vCompanies
                      where id == c.id
                      from user in db.Users
                      select new ViewCompanyModel()
                      {
                          Id = c.id,
                          Descripton = c.Descripton,
                          Name = c.Name,
                          ImageLink = c.ImageLink,
                          AdminEmail = c.Email,
                          Users = db.eUsers
                          .Where(o => o.CompanyName.Equals(c.Name))
                          .Select(o => new UserManageViewModel.UserViewModel
                          {
                              Id = o.UserId,
                              Name = o.LastName,
                              Email = o.Email,
                              Company = o.CompanyName,
                              ListOfRoles = user.AspNetUsers.AspNetRoles.Select(x=>x.Name).ToList()
                          })
                      }).FirstOrDefault();
</code>```

I receive not correct data in ListOfRoles - I receive data only of first user.
I tried to add something like this

```<code>Where(x=>x.UserId == o.UserId)
</code>```

I also tried change for this

ListOfRoles = db.Users.Where(x=>x.UserId == o.UserId).Select(x=>x.AspNetUsers.AspNetRoles)

But in this case I can't select x.Name.
I am doing something wrong.
Please advise me.

答:
```<code>if(result != null)
        {
        foreach (var user in result.Users)
        {
            var roles = db.Users.Where(x => x.UserId == user.Id).Select(x => x.AspNetUsers.AspNetRoles).FirstOrDefault();
            user.ListOfRoles = roles.Select(x => x.Name).ToList();
        }
        }
</code>```

This is the answer! It's work!

Title: Wrong LINQ request

Body:
Please look at my code below

        var result = (from c in db.vCompanies
                      where id == c.id
                      from user in db.Users
                      select new ViewCompanyModel()
                      {
                          Id = c.id,
                          Descripton = c.Descripton,
                          Name = c.Name,
                          ImageLink = c.ImageLink,
                          AdminEmail = c.Email,
                          Users = db.eUsers
                          .Where(o => o.CompanyName.Equals(c.Name))
                          .Select(o => new UserManageViewModel.UserViewModel
                          {
                              Id = o.UserId,
                              Name = o.LastName,
                              Email = o.Email,
                              Company = o.CompanyName,
                              ListOfRoles = user.AspNetUsers.AspNetRoles.Select(x=>x.Name).ToList()
                          })
                      }).FirstOrDefault();

I receive not correct data in ListOfRoles - I receive data only of first user.
I tried to add something like this

Where(x=>x.UserId == o.UserId)

I also tried change for this

ListOfRoles = db.Users.Where(x=>x.UserId == o.UserId).Select(x=>x.AspNetUsers.AspNetRoles)

But in this case I can't select x.Name.
I am doing something wrong.
Please advise me.

Body:
if(result != null)
        {
        foreach (var user in result.Users)
        {
            var roles = db.Users.Where(x => x.UserId == user.Id).Select(x => x.AspNetUsers.AspNetRoles).FirstOrDefault();
            user.ListOfRoles = roles.Select(x => x.Name).ToList();
        }
        }

This is the answer! It's work!


问:
Different between 'o' and arrow symbol used in .cto file?
I am bit confused between 'o' and '-->' used in Model file, For example :

```<code>asset Field identified by assetId {
    o String assetId
    o Customer owner
    --> Customer custId
}

participant Customer identified by customerId {
    o String customerId
}
</code>```

what is difference between "o Customer owner" and "--> Customer custId"?

答:
The o indicates that this is an owned property of a class. Aka a "field". That means that when the instance of the class is removed, so are all its properties.

The --> indicates that this is a relationship to another addressable resource. Aka a pointer or primary/foreign key entity relationship.

In your example, your asset Field has a property or type Customer called owner. When instances of Field are deleted the instances of Customer that they are storing in the owner property are also deleted.

The Field asset also has a relationship to a Customer instance stored in a property called custId. Deleting an instance of Field will not delete the instance of Customer that is being pointed to by the relationship.

Composer relationships are essentially typed-pointers. They are a fully-qualified type name of the resource that is being pointed to, as well as the identified of the instance that is being pointed to.

In Composer relationships do not cascade-delete, and there is no referential integrity checking for relationships. It is up to the application to check whether the resource that is at the end of a relationship exists or not, and to respond appropriately.

Note that in the future we may prevent using o with assets and participants. It really doesn't make much sense and is confusing for people that expect to find them in their respective registries. For assets and participants people should use -->.

ContentLicense: CC BY-SA 4.0

Body:
I am bit confused between 'o' and '-->' used in Model file, For example :

asset Field identified by assetId {
    o String assetId
    o Customer owner
    --> Customer custId
}

participant Customer identified by customerId {
    o String customerId
}

what is difference between "o Customer owner" and "--> Customer custId"?


问:
Get the names of all schemas with Psycopg2
I'm trying to iterate all tables of a Postgresql DB in Python, to execute a query in each of them. I need to get the schema and table name of each of them in order to execute the queries, so I'd like to get a list of strings like this: "schema.tablename".

I've used this, but it only lists the names of tables, so it is of no help.

```<code>select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';
</code>```

I'm sure there must be a more simple way, but I have been looking for something with no success...

Any help appreciated, thanks!!

答:
you want to join it against pg_namespace:</p>

```<code>t=# select nspname||'.'||relname from pg_class join pg_namespace on relnamespace = pg_namespace.oid where relkind='r' and relname !~ '^(pg_|sql_)' limit 5;
     ?column?
-------------------
 public.s141
 public.events
 public.tg_rep_que
 public.t4
 public.menupoint
(5 rows)
</code>```

Body:
I'm trying to iterate all tables of a Postgresql DB in Python, to execute a query in each of them. I need to get the schema and table name of each of them in order to execute the queries, so I'd like to get a list of strings like this: "schema.tablename".

I've used this, but it only lists the names of tables, so it is of no help.

select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';

I'm sure there must be a more simple way, but I have been looking for something with no success...

Any help appreciated, thanks!!

Body:
you want to join it against pg_namespace:

t=# select nspname||'.'||relname from pg_class join pg_namespace on relnamespace = pg_namespace.oid where relkind='r' and relname !~ '^(pg_|sql_)' limit 5;
     ?column?
-------------------
 public.s141
 public.events
 public.tg_rep_que
 public.t4
 public.menupoint
(5 rows)


问:
AWS Lex Access Denied after lambda redeployed. Wrong default IAM role
I created an AWS Lex bot and added an intent recently. Then I uploaded a simple AWS Lambda, which has an administrator access (I will lower it later, no worries) and then also added some trusted entities:

Trusted entities

The identity provider(s) apigateway.amazonaws.com

The identity provider(s) lambda.amazonaws.com

The identity provider(s) events.amazonaws.com

The identity provider(s) lex.amazonaws.com

Then I added the lambda function to the intent and build the bot, start testing it. It worked just fine.
Next step was (in 10 minutes) to update the lambda function (test new functionality). I added a new version and went back to AWS Lex and start writing messages and the following error message came up:

An error has occurred: Access denied while invoking lambda function arn:aws:lambda:us-east-1:99999999999:function:lex-test from arn:aws:lex:us-east-1:888888888:intent:test:3. Please check the policy on this function.

First, I thought it was my mistake, and started looking into the problem, but then, I noticed the AWSServiceRoleForLexBots role's policy is not right.

```<code>{
    "Version": "2012-10-17",
        "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "polly:SynthesizeSpeech"
            ],
            "Resource": [
                "*"
            ]
        }
        ]
}
</code>```

I can't change it because "This service-linked role cannot be modified in IAM. You can modify this role from the AWS service that depends on this role."
If I click through every intent again and remove the lambda function and then add it again and then build and publish it, it will work until the next update.

However, this is a nightmare. Do you have any idea how could I fix this?

Thanks.

答:
Using AWS CLI try this:

```<code>aws lambda add-permission --function-name lex-test --statement-id chatbot-fulfillment --action "lambda:InvokeFunction" --principal "lex.amazonaws.com"
</code>```

And take a look: Using Resource-Based Policies for AWS Lambda (Lambda Function Policies)

Body:
I created an AWS Lex bot and added an intent recently. Then I uploaded a simple AWS Lambda, which has an administrator access (I will lower it later, no worries) and then also added some trusted entities:

Trusted entities

The identity provider(s) apigateway.amazonaws.com

The identity provider(s) lambda.amazonaws.com

The identity provider(s) events.amazonaws.com

The identity provider(s) lex.amazonaws.com

Then I added the lambda function to the intent and build the bot, start testing it. It worked just fine.
Next step was (in 10 minutes) to update the lambda function (test new functionality). I added a new version and went back to AWS Lex and start writing messages and the following error message came up:

An error has occurred: Access denied while invoking lambda function arn:aws:lambda:us-east-1:99999999999:function:lex-test from arn:aws:lex:us-east-1:888888888:intent:test:3. Please check the policy on this function.

First, I thought it was my mistake, and started looking into the problem, but then, I noticed the AWSServiceRoleForLexBots role's policy is not right.

{
    "Version": "2012-10-17",
        "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "polly:SynthesizeSpeech"
            ],
            "Resource": [
                "*"
            ]
        }
        ]
}

I can't change it because "This service-linked role cannot be modified in IAM. You can modify this role from the AWS service that depends on this role."
If I click through every intent again and remove the lambda function and then add it again and then build and publish it, it will work until the next update.

However, this is a nightmare. Do you have any idea how could I fix this?

Thanks.

Body:
Using AWS CLI try this:

aws lambda add-permission --function-name lex-test --statement-id chatbot-fulfillment --action "lambda:InvokeFunction" --principal "lex.amazonaws.com"

And take a look: Using Resource-Based Policies for AWS Lambda (Lambda Function Policies)


问:
how to design a communicate channel of game server
I am planning to design a game server. I wish it could take a very heavy load, reusable, flexiable, but easy to programming, I want to get a balance of those points.

I decide to use nodejs and redis, the data formate of protocal is JSON, websocket

I have experience of web development, but have no idea of game server development, I notice that game server is very Real-Time, and the message is not peer to peer, but pub-sub channel,

Does nodejs, redis, JSON is a good choice for design the communicate channel, does websocket support by most browser?

Maybe there are too many questions, the only question is how to design a communicate channel for a game server?

答:
You seem to be under-generalizing a great deal. There certainly are game protocols that are point-to-point, it all depends on the game's design, whether it uses a centralized server or not.

Also, many games use binary protocols, with bitstreams being quite common to conserve bandwidth. JSON is at least a few orders of magnitude from that world, so perhaps you should limit your scope from "games" to something more limited. Here, it seems you're over-generalizing instead.


问:
Prevent Bootstrap dropdown from collapsing until button is clicked
Please comment with with clarifying questions. I suspect this question is poorly worded, but it's complicated so it is a tough question to ask.

I currently have a dropup on bootstrap navbar that I've converted to a toolbar. I've moved 2 bootstrap datepickers into the dropup in order to select a range.

The problem is that once I select the date for one of the datepicker inputs, the dropup closes. I'd like it to stay open until the OK button is clicked or I click out of the dropup.

If you don't have them, here are the BOOTSTRAP DOCS
The line that closes the drop down is on line 798 of bootstrap.js in the clearMenus() fuction:

```<code>$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
</code>```

I've been learning Javascript, but this problem is over my head.

Front-end

```<code>...
<div class="dropup mobilewidth mobilebottom">
  <button class="btn btn-default dropdown-toggle mobilewidth" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Date Range
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu datepicWidth" aria-labelledby="dropdownMenu2">
    <div class="dpInputs">
      <div class="input-group" style="padding-bottom: 4px;">
        <span class="input-group-addon datepic1stChld">From:</span>
        <input class="datepicker dp1 datepic2ndChld" readonly="true" name="startDate">
      </div>
      <div class="input-group">
        <span class="input-group-addon datepic1stChld">To: </span>
        <input class="datepicker dp2 datepic2ndChld" readonly="true" name="endDate">
      </div>
    </div>
    <div class="dpSubmit">
      <button type="submit" id="dpSubmitBtn">OK</button>
    </div>
    </ul>
  </div>
</div>
...
</code>```

My css

```<code>.navbar {
  border-radius: 0px;
}

.dropup{
    display: inline-block;
}

.dropdown-menu {
    padding: 4px 4px 4px 4px;
    min-width: 30px;
}
.navbar-default2 {
  background-color: #f8f8f8;
  border-color: #e7e7e7;
  position: fixed;
  bottom: 0px;
  width: 100%;
  margin-bottom: 0px;
  vertical-align: middle;
}
.navbar-default2 .navbar-brand {
  color: #777;
}
.navbar-default2 .navbar-toggle:hover,
.navbar-default2 .navbar-toggle:focus {
  background-color: #ddd;
}
.navbar-default2 .navbar-toggle {
  border-color: #ddd;
}
.navbar-default2 .navbar-toggle .icon-bar {
  background-color: #888;
}

@media (min-width: 768px) {
  .navbar-footer {
    float: left;
  }
}
.container > .navbar-footer,
.container-fluid > .navbar-footer,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
  margin-right: -15px;
  margin-left: -15px;
}
@media (min-width: 768px) {
  .container > .navbar-footer,
  .container-fluid > .navbar-footer,
  .container > .navbar-collapse,
  .container-fluid > .navbar-collapse {
    margin-right: 0;
    margin-left: 0;
  }
}

 .navbar-nav .open .dropdown-menu > li > a,
  .navbar-nav .open .dropdown-menu .dropdown-footer {
    padding: 5px 15px 5px 25px;
  }

button {
    margin-top: 8px;
}
.onlyMobile {
  display: none;
}
.datepic1stChld{
  width: 63px;
}
.datepic2ndChld{
  width: 100%;
  border-radius: 0px;
  border: 1px solid #ccc;
}

.datepicWidth {
  width: 280px;
  left: -165px;
}
.dpInputs{
  width: 200px;
  float: left;
}
.dpSubmit{
  width: 68px;
  float: left;
}
#dpSubmitBtn{
  margin: 0px 2px 2px 3px;
  width: 100%;
  height: 64px;
  border: 1px solid #ccc;
  background-color: #eee;
}
@media (max-width: 767px) {
  .btn-default{
    font-size: 17px;
  }
  .three{
    width: 33.333333333%;
  }
  .mobilewidth{
    width: 100%;
  }
  .onlyMobile{
    display: block;
  }
  .mobilebottom {
    padding-bottom: 8px;
  }
  .WM3MY{
    width: 16.75%;
  }
  .fullwidth{
    width: 100%;
    font-size: 18px;
  }
  .input-group{
      width: 100%;
  }
  .datepicWidth {
    width: 100%;
    left: 0px;
  }
  .dpInputs{
     width: 73%
  }
  .dpSubmit{
      width: 26%;
  }
  #dpSubmitBtn{
    font-size: 18px;
    height: 74px;
    border-radius: 1px;
  }
  .datepic1stChld{
    width: 72px;
  }
  .datepic2ndChld{
    font-size: 18px;
  }
  .input-group-addon{
     font-size: 18px;
  }

}

.navbar-collapse.in {
    overflow-y: visible;
}
</code>```

I don't think you'll need them but here are the DATEPICKER DOCS

答:
Instead of writing some javascript or jquery code(reinventing the wheel). The above scenario can be managed by bootstrap auto-close option.
You can provide either of the values to auto-close:

always - (Default) automatically closes the dropdown when any of its elements is clicked.

outsideClick - closes the dropdown automatically only when the user clicks any element outside the dropdown.

disabled - disables the auto close

Take a look at the following plunkr :

http://plnkr.co/edit/gnU8M2fqlE0GscUQtCWa?p=preview

Set

```<code>uib-dropdown auto-close="disabled"
</code>```

Hope this helps :)

Body:
Please comment with with clarifying questions. I suspect this question is poorly worded, but it's complicated so it is a tough question to ask.

I currently have a dropup on bootstrap navbar that I've converted to a toolbar. I've moved 2 bootstrap datepickers into the dropup in order to select a range.

The problem is that once I select the date for one of the datepicker inputs, the dropup closes. I'd like it to stay open until the OK button is clicked or I click out of the dropup.

If you don't have them, here are the BOOTSTRAP DOCS
The line that closes the drop down is on line 798 of bootstrap.js in the clearMenus() fuction:

$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)

I've been learning Javascript, but this problem is over my head.

Front-end

...

  <button class="btn btn-default dropdown-toggle mobilewidth" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Date Range

  </button>

        From:
        <input class="datepicker dp1 datepic2ndChld" readonly="true" name="startDate">

        To:
        <input class="datepicker dp2 datepic2ndChld" readonly="true" name="endDate">

      <button type="submit" id="dpSubmitBtn">OK</button>

...

My css

.navbar {
  border-radius: 0px;
}

.dropup{
    display: inline-block;
}

.dropdown-menu {
    padding: 4px 4px 4px 4px;
    min-width: 30px;
}
.navbar-default2 {
  background-color: #f8f8f8;
  border-color: #e7e7e7;
  position: fixed;
  bottom: 0px;
  width: 100%;
  margin-bottom: 0px;
  vertical-align: middle;
}
.navbar-default2 .navbar-brand {
  color: #777;
}
.navbar-default2 .navbar-toggle:hover,
.navbar-default2 .navbar-toggle:focus {
  background-color: #ddd;
}
.navbar-default2 .navbar-toggle {
  border-color: #ddd;
}
.navbar-default2 .navbar-toggle .icon-bar {
  background-color: #888;
}

@media (min-width: 768px) {
  .navbar-footer {
    float: left;
  }
}
.container > .navbar-footer,
.container-fluid > .navbar-footer,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
  margin-right: -15px;
  margin-left: -15px;
}
@media (min-width: 768px) {
  .container > .navbar-footer,
  .container-fluid > .navbar-footer,
  .container > .navbar-collapse,
  .container-fluid > .navbar-collapse {
    margin-right: 0;
    margin-left: 0;
  }
}

 .navbar-nav .open .dropdown-menu > li > a,
  .navbar-nav .open .dropdown-menu .dropdown-footer {
    padding: 5px 15px 5px 25px;
  }

button {
    margin-top: 8px;
}
.onlyMobile {
  display: none;
}
.datepic1stChld{
  width: 63px;
}
.datepic2ndChld{
  width: 100%;
  border-radius: 0px;
  border: 1px solid #ccc;
}

.datepicWidth {
  width: 280px;
  left: -165px;
}
.dpInputs{
  width: 200px;
  float: left;
}
.dpSubmit{
  width: 68px;
  float: left;
}
#dpSubmitBtn{
  margin: 0px 2px 2px 3px;
  width: 100%;
  height: 64px;
  border: 1px solid #ccc;
  background-color: #eee;
}
@media (max-width: 767px) {
  .btn-default{
    font-size: 17px;
  }
  .three{
    width: 33.333333333%;
  }
  .mobilewidth{
    width: 100%;
  }
  .onlyMobile{
    display: block;
  }
  .mobilebottom {
    padding-bottom: 8px;
  }
  .WM3MY{
    width: 16.75%;
  }
  .fullwidth{
    width: 100%;
    font-size: 18px;
  }
  .input-group{
      width: 100%;
  }
  .datepicWidth {
    width: 100%;
    left: 0px;
  }
  .dpInputs{
     width: 73%
  }
  .dpSubmit{
      width: 26%;
  }
  #dpSubmitBtn{
    font-size: 18px;
    height: 74px;
    border-radius: 1px;
  }
  .datepic1stChld{
    width: 72px;
  }
  .datepic2ndChld{
    font-size: 18px;
  }
  .input-group-addon{
     font-size: 18px;
  }

}

.navbar-collapse.in {
    overflow-y: visible;
}

I don't think you'll need them but here are the DATEPICKER DOCS

Body:
Instead of writing some javascript or jquery code(reinventing the wheel). The above scenario can be managed by bootstrap auto-close option.
You can provide either of the values to auto-close:

always - (Default) automatically closes the dropdown when any of its elements is clicked.

outsideClick - closes the dropdown automatically only when the user clicks any element outside the dropdown.

disabled - disables the auto close

Take a look at the following plunkr :

http://plnkr.co/edit/gnU8M2fqlE0GscUQtCWa?p=preview

Set

uib-dropdown auto-close="disabled"

Hope this helps :)


问:
Android ViewPager loading same images
I am using ViewPager to load images from server.When it is swiped the first image is shown again and again.I checked the urls in the browser and it shows different images.I then tried loading images from drawable.Here the last image is being loaded repeatedly.Below is the complete code:

ImagePagerAdapter.java:

```<code> public class ImagePagerAdapter extends PagerAdapter {
    TaxiDisplayData taxiDisplayData;
    LinearLayout pager_lyt;
    ImageView imageView;
    LayoutInflater layoutInflater;
    Context context;
    String category;
    int count;
    LinearLayout linearLayout;
    View view;
    ImageLoaderConfiguration config;
    ArrayList images;

    public ImagePagerAdapter(Context context,String ctgry){
        Log.e("I","T");
        config = new ImageLoaderConfiguration.Builder(context).build();
        ImageLoader.getInstance().init(config);
        images =new ArrayList();
        this.context=context;
        this.category=ctgry;
        if (category.equalsIgnoreCase("taxi")){
            count= taxiDisplayData.getInstance().imagecount();
        }
        layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }
    @Override
    public int getCount() {

        Log.e("Count",Integer.toString(count));
        return count;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        view=layoutInflater.inflate(R.layout.srch_dsply_pager,container,false);
        linearLayout=(LinearLayout) view.findViewById(R.id.pgr_lyt);
         imageView=(ImageView) view.findViewById(R.id.image1);
        if (category.equalsIgnoreCase("taxi"))
        {  images =taxiDisplayData.getInstance().getArrayList();
            if(count!=0){

                Iterator iterator= images.iterator();
                while (iterator.hasNext())
                {
                    Log.e("I","Z");
                    Picasso.with(context).load("http://example.com/xxxx/"+(String) iterator.next())
                            .placeholder(R.drawable.doctors)
                            .fit().into(imageView);
                }
            }}
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View)object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        Log.e("I","f");
        return view==object;
    }}
</code>```

srch_dsply_pager.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/pgr_lyt">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="@dimen/prsnl_img_dimen"
    android:id="@+id/image1"
    android:scaleType="fitXY"
   />
</LinearLayout>
</code>```

答:
instantiateItem() Creates one view and adds it in the view pager. In your source you are iterating trough the whole array, load only the last one and return the view. Instead the while you should have something like

```<code>String url = images.get(position);
Picasso.load(url).into(imageview);
</code>```

Title: Android ViewPager loading same images

Body:
I am using ViewPager to load images from server.When it is swiped the first image is shown again and again.I checked the urls in the browser and it shows different images.I then tried loading images from drawable.Here the last image is being loaded repeatedly.Below is the complete code:

ImagePagerAdapter.java:

 public class ImagePagerAdapter extends PagerAdapter {
    TaxiDisplayData taxiDisplayData;
    LinearLayout pager_lyt;
    ImageView imageView;
    LayoutInflater layoutInflater;
    Context context;
    String category;
    int count;
    LinearLayout linearLayout;
    View view;
    ImageLoaderConfiguration config;
    ArrayList images;

    public ImagePagerAdapter(Context context,String ctgry){
        Log.e("I","T");
        config = new ImageLoaderConfiguration.Builder(context).build();
        ImageLoader.getInstance().init(config);
        images =new ArrayList();
        this.context=context;
        this.category=ctgry;
        if (category.equalsIgnoreCase("taxi")){
            count= taxiDisplayData.getInstance().imagecount();
        }
        layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }
    @Override
    public int getCount() {

        Log.e("Count",Integer.toString(count));
        return count;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        view=layoutInflater.inflate(R.layout.srch_dsply_pager,container,false);
        linearLayout=(LinearLayout) view.findViewById(R.id.pgr_lyt);
         imageView=(ImageView) view.findViewById(R.id.image1);
        if (category.equalsIgnoreCase("taxi"))
        {  images =taxiDisplayData.getInstance().getArrayList();
            if(count!=0){

                Iterator iterator= images.iterator();
                while (iterator.hasNext())
                {
                    Log.e("I","Z");
                    Picasso.with(context).load("http://example.com/xxxx/"+(String) iterator.next())
                            .placeholder(R.drawable.doctors)
                            .fit().into(imageView);
                }
            }}
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View)object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        Log.e("I","f");
        return view==object;
    }}

srch_dsply_pager.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/pgr_lyt">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="@dimen/prsnl_img_dimen"
    android:id="@+id/image1"
    android:scaleType="fitXY"
   />
</LinearLayout>

Body:
instantiateItem() Creates one view and adds it in the view pager. In your source you are iterating trough the whole array, load only the last one and return the view. Instead the while you should have something like

String url = images.get(position);
Picasso.load(url).into(imageview);


问:
aws datapipeline start stop ec2 instances
this example: https://aws.amazon.com/premiumsupport/knowledge-center/stop-start-ec2-instances/
does not seem to work. I followed the example and the pipeline is always canceled. There are no logs created, i did set up logging. the only "error message" i could find is.
Error MessageUnable to create resource for @Ec2Instance_2017-06-07T09:58:49 due to: No subnets found for the default VPC 'vpc-f7dxxxx'. Please specify a subnet. (Service: AmazonEC2; Status Code: 400; Error Code: MissingInput; Request ID: ebeeae6d-9537-4627-8a56-e832999a1940)

All i am trying to do is execute a aws ec2 start-instances aws cli command as outlined in the example. the instances do exist, they are in a "stopped" state. Has anyone been successful in setting up a pipeline to start and stop existing instances? How did you do it? Thanks for the help

答: yes, that was it. after you finish going through the example you need to look at the pipeline and edit it. Look for the EC2Resource area. Click on it. then add a subnet. place the micro instance in the same subnet as the ec2 instances you need to start or stop. The example does not address this</p>


问:
Event click after append a template in Es6
I'm using templating in es6 to reuse my HTML elements.

My Template inside a template.js:

```<code>const checkbox = (id, name) => {
    return `
        <div class="checkbox-group">
            <input class="checkbox-input-hidden" type="checkbox" name="index[]" value="${id}">
            <a href="#" class="form-field-input checkbox-custom-field">
                <span class="checkbox-label">${name}</span>
                <span class="icon-check"></span>
            </a>
        </div>`;
};

export { checkbox };
</code>```

Now, I have another js that is responsible for the view and it has a method for rendering the checkbox:

```<code>renderCheckbox (data) {
    for(var i in data) {
        this.checkboxContainer.append(
            checkbox(
                data[i].id,
                data[i].name
            )
        );
    }
}
</code>```

How can I assign a click for these elements that I'm appending to the DOM?

答:
You can first create a DOM element by passing the HTML string to $, then assign an event listener to it, and then append it to the container.

$(checkbox(data[i].id, data[i].name))
  .click(() => {
    // ...
  })
  .appendTo(this.checkboxContainer);
```

<p>By the way, you can simplify your loop by changing it to <code>for...of</code> and using destructuring.</p>

<pre class="lang-js prettyprint-override"><code>renderCheckbox (data) {
  for (const {id, name} of data) {
    $(checkbox(id, name))
      .click(() => {
        // ...
      })
      .appendTo(this.checkboxContainer);
  }
}
</code>```

Body:
I'm using templating in es6 to reuse my HTML elements.

My Template inside a template.js:

const checkbox = (id, name) => {
    return `

            <input class="checkbox-input-hidden" type="checkbox" name="index[]" value="${id}">

                ${name}

`;
};

export { checkbox };

Now, I have another js that is responsible for the view and it has a method for rendering the checkbox:

renderCheckbox (data) {
    for(var i in data) {
        this.checkboxContainer.append(
            checkbox(
                data[i].id,
                data[i].name
            )
        );
    }
}

How can I assign a click for these elements that I'm appending to the DOM?

Body:
You can first create a DOM element by passing the HTML string to $, then assign an event listener to it, and then append it to the container.

$(checkbox(data[i].id, data[i].name))
  .click(() => {
    // ...
  })
  .appendTo(this.checkboxContainer);

By the way, you can simplify your loop by changing it to for...of and using destructuring.

renderCheckbox (data) {
  for (const {id, name} of data) {
    $(checkbox(id, name))
      .click(() => {
        // ...
      })
      .appendTo(this.checkboxContainer);
  }
}


答:
Using Regex is not a good approach you should use DOMDocument for parsing HTML. Here we are querying on those elements whose alt attribute is empty which is actually asked in question.

Try this code snippet here

```<code><?php

ini_set('display_errors', 1);

$string=<<<HTML
<img src="assets/img/test1.png" alt="" title="I'am a title tag" width="100" height="100" />
<img src="assets/img/test2.png" alt="" title="I'am a title tag" width="100" height="100" />
<img src="assets/img/test3.png" alt="" title="I'am a title tag" width="100" height="100" />
HTML;

$domDocument = new DOMDocument();
$domDocument->loadHTML($string,LIBXML_HTML_NODEFDTD);

$domXPath = new DOMXPath($domDocument);
$results = $domXPath->query('//img[@alt=""]');
foreach($results as $result)
{
    $title=$result->getAttribute("title");
    $result->setAttribute("alt",$title);
    echo $domDocument->saveHTML($result);
    echo PHP_EOL;
}
</code>```

Title: Replace empty alt tag on <img> tag

Body:
I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags.
For example:

What I wish to have:

So:
I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

preg_match_all('/]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?

Body:
Using Regex is not a good approach you should use DOMDocument for parsing HTML. Here we are querying on those elements whose alt attribute is empty which is actually asked in question.

Try this code snippet here

<?php

ini_set('display_errors', 1);

$string=<<<HTML
<img src="assets/img/test1.png" alt="" title="I'am a title tag" width="100" height="100" />
<img src="assets/img/test2.png" alt="" title="I'am a title tag" width="100" height="100" />
<img src="assets/img/test3.png" alt="" title="I'am a title tag" width="100" height="100" />
HTML;

$domDocument = new DOMDocument();
$domDocument->loadHTML($string,LIBXML_HTML_NODEFDTD);

$domXPath = new DOMXPath($domDocument);
$results = $domXPath->query('//img[@alt=""]');
foreach($results as $result)
{
    $title=$result->getAttribute("title");
    $result->setAttribute("alt",$title);
    echo $domDocument->saveHTML($result);
    echo PHP_EOL;
}


问:
Record Count (Nested??)
I have a SQL select statement which works perfectly except I need to embed a count function (line 7 & 8).

```<code>select '1' = DYN_PORDERS.ID, '2' = DYN_PORDERS.SupplierID,'3' =
DYN_PORDERS.Revision2,
'4' = DYN_PORDERS.ItemID,  '5' = DYN_PORDERS.OrderNumber, '12' = '',
'6' = SYS_SUPPLIERS.SCompany, '7' = SYS_SUPPLIERS.SCode, '8' =
SYS_SUPPLIERS.SCIPEMail, '9' = SYS_SUPPLIERS.SCIPContact,
'10' = SYS_SUPPLIERS.SPDRemitType, '11' = SYS_SUPPLIERS.SCIPFax,
(SELECT count(DYN_PORDERS.OrderNumber) FROM DYN_PORDERS where OrderNumber =
'5') AS column3
from DYN_PORDERS
inner join  SYS_SUPPLIERS
on SYS_SUPPLIERS.ID = DYN_PORDERS.SupplierID
where DYN_PORDERS.OrderStatus1 = 1 and DYN_PORDERS.ItemID = 1
order by DYN_PORDERS.OrderNumber asc, DYN_PORDERS.itemid asc
</code>```

The nested select count statement returns 0 but we have four records in the table.

I have tried to reference the Variable or Column Name '5' from the first select statement in the embedded one, but it returns 0.

Any help would be much appreciated.
Mike

答:
If you want to access ordernumber in the subquery, then use this name. Use table aliases to tell the outer table from the inner one.

```<code>select
  p.id as "1",
  p.supplierid as "2",
  p.revision2 as "3",
  p.itemid as "4",
  p.ordernumber as "5",
  '' as "12",
  s.scompany as "6",
  s.scode as "7",
  s.scipemail as "8",
  s.scipcontact as "9",
  s.spdremittype as "10",
  s.scipfax as "11",
  (select count(*) from dyn_porders p2 where p2.ordernumber = p.ordernumber) as column3
from dyn_porders p
inner join sys_suppliers s on s.id = p.supplierid
where p.orderstatus1 = 1
  and p.itemid = 1
order by p.ordernumber asc, p.itemid asc;
</code>```

Please note that single quotes are for string literals and double quotes for names.

Title: Record Count (Nested??)

Body:
I have a SQL select statement which works perfectly except I need to embed a count function (line 7 & 8).

select '1' = DYN_PORDERS.ID, '2' = DYN_PORDERS.SupplierID,'3' =
DYN_PORDERS.Revision2,
'4' = DYN_PORDERS.ItemID,  '5' = DYN_PORDERS.OrderNumber, '12' = '',
'6' = SYS_SUPPLIERS.SCompany, '7' = SYS_SUPPLIERS.SCode, '8' =
SYS_SUPPLIERS.SCIPEMail, '9' = SYS_SUPPLIERS.SCIPContact,
'10' = SYS_SUPPLIERS.SPDRemitType, '11' = SYS_SUPPLIERS.SCIPFax,
(SELECT count(DYN_PORDERS.OrderNumber) FROM DYN_PORDERS where OrderNumber =
'5') AS column3
from DYN_PORDERS
inner join  SYS_SUPPLIERS
on SYS_SUPPLIERS.ID = DYN_PORDERS.SupplierID
where DYN_PORDERS.OrderStatus1 = 1 and DYN_PORDERS.ItemID = 1
order by DYN_PORDERS.OrderNumber asc, DYN_PORDERS.itemid asc

The nested select count statement returns 0 but we have four records in the table.

I have tried to reference the Variable or Column Name '5' from the first select statement in the embedded one, but it returns 0.

Any help would be much appreciated.
Mike

Body:
If you want to access ordernumber in the subquery, then use this name. Use table aliases to tell the outer table from the inner one.

select
  p.id as "1",
  p.supplierid as "2",
  p.revision2 as "3",
  p.itemid as "4",
  p.ordernumber as "5",
  '' as "12",
  s.scompany as "6",
  s.scode as "7",
  s.scipemail as "8",
  s.scipcontact as "9",
  s.spdremittype as "10",
  s.scipfax as "11",
  (select count(*) from dyn_porders p2 where p2.ordernumber = p.ordernumber) as column3
from dyn_porders p
inner join sys_suppliers s on s.id = p.supplierid
where p.orderstatus1 = 1
  and p.itemid = 1
order by p.ordernumber asc, p.itemid asc;

Please note that single quotes are for string literals and double quotes for names.


问:
Why does the "+" operator consider the number as string when added
Why does the + operator consider the number as string when added

Ex :

```<code>'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"
</code>```

答:
When using + with 2 numbers: Math.

When using + with a string: Concatenation.

```<code>3 + 4 = 7
7 + '5' = '75'
</code>```

Body:
Why does the + operator consider the number as string when added

Ex :

'3' + 4 + 5;  // "345"
 3 + 4 + '5'; // "75"

Body:
When using + with 2 numbers: Math.

When using + with a string: Concatenation.

3 + 4 = 7
7 + '5' = '75'


问:
Express.js Unauthorized error
I have method

```<code>router.post('/user',passport.authenticate('jwt', { session: false }), function (request, res) {
  res.send(request.user);
});
</code>```

and authorization token

```<code>"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQi"
</code>```

when i send request to this route from postman everything is working.

but when i send request from angular application with same token its throw with error unauthorized

```<code>    getUser() {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', localStorage.getItem('token'));
    return this.http.post('localhost:8000/api/user/', {
      headers
    })
      .map((data: Response) => data.json())
      .catch((error: Response) => Observable.throw(error.json()));
  }
</code>```

答:
Instead of sending headers like an header object, use RequestOptions to wrap it and then send it via your post request.

your code will be like:

```<code>import { Http, Headers, RequestOptions } from '@angular/http';
getUser() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', localStorage.getItem('token'));
    let options = new RequestOptions({ headers: headers });
    return this.http.post('https://dropali.com/api/user/',options)
        .map((data: Response) => data.json())
        .catch((error: Response) => Observable.throw(error.json()));
}
</code>```

Also a suggestion instead of getting your token while your post request retrieve it first in a variable and check if it's there or not, If not then do whatever is necessary if it is successfully retrieved then make post request.

Title: Express.js Unauthorized error

Body:
I have method

router.post('/user',passport.authenticate('jwt', { session: false }), function (request, res) {
  res.send(request.user);
});

and authorization token

"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQi"

when i send request to this route from postman everything is working.

but when i send request from angular application with same token its throw with error unauthorized

    getUser() {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', localStorage.getItem('token'));
    return this.http.post('localhost:8000/api/user/', {
      headers
    })
      .map((data: Response) => data.json())
      .catch((error: Response) => Observable.throw(error.json()));
  }

Body:
Instead of sending headers like an header object, use RequestOptions to wrap it and then send it via your post request.

your code will be like:

import { Http, Headers, RequestOptions } from '@angular/http';
getUser() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', localStorage.getItem('token'));
    let options = new RequestOptions({ headers: headers });
    return this.http.post('https://dropali.com/api/user/',options)
        .map((data: Response) => data.json())
        .catch((error: Response) => Observable.throw(error.json()));
}

Also a suggestion instead of getting your token while your post request retrieve it first in a variable and check if it's there or not, If not then do whatever is necessary if it is successfully retrieved then make post request.


问:
Timepicker not showing time on a single click
I have two input boxes one is for selecting date and another for time. I am trying to validate these two boxes based on some conditions, such that if the date is not selected, the time should not get selected.

I'm using eonasdan datetimepicker, I'm getting the desired output but not with the single click on a timepicker. Can some one help me out with this?

Here's what I have done so far:

function starttime(){
  $('#starttime').datetimepicker({
    format: 'HH:mm',
    minDate: new Date()
  });
}

$('.start_time_addon').on('click keyup',function(){
  var x = $('#start').val();
  if (x == '') {
    alert('please select startdate first');
    return false;
  }
  else{
    starttime();
  }
});

var datePickerSix= $('.datetimepicker6');
$(datePickerSix).datetimepicker({
  format: 'DD/MM/YYYY',
  minDate: new Date()
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker-standalone.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>

<div class="row">
  <div class="col-xs-6">
    <div class="form-group">
      <label>Start Date</label><br>
      <div class='input-group date datetimepicker6'>
        <input type='text' class="form-control" id="start" name="date_end" placeholder="DD/MM/YYYY"/>
        <span class="input-group-addon">
          <span class="glyphicon glyphicon-calendar"></span>
        </span>
      </div>
      <div class="col-xs-6">
        <div class="form-group">
          <label for="start_time" class="col-form-label">Start Time</label>
          <div class='input-group date start_time_addon' id='starttime'>
            <input type='text' class="form-control" placeholder="HH : MM" id="Start_Time" required />
            <span class="input-group-addon">
              <span class="glyphicon glyphicon-time"></span>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

答:
The problem is that you initialize the time picker only after a click on it, so on the first click the datetimepicker is not already built. Move starttime initialization from starttime to document.ready.

I suggest to disable starttime datetimepicker when the user can not select hours. You can use disable() and enable() method of the datetimepicker.

Use date() method to get datetimepicker selected date and you can listen to dp.change event to known when the user selects a date.

Here a complete example:

$('#startdate').datetimepicker({
  format: 'DD/MM/YYYY',
  minDate: new Date()
}).on('dp.change', function(e){
  if( e.date ){
    // Enable timepicker only if date is selected
    $('#starttime').data("DateTimePicker").enable();
  } else {
    $('#starttime').data("DateTimePicker").disable();
  }
});

$('#starttime').datetimepicker({
  format: 'HH:mm',
  minDate: new Date(),
  useCurrent: false
});
// Disable time picker
$('#starttime').data("DateTimePicker").disable();

$('.start_time_addon').on('click keyup',function(){
  var x = $('#startdate').data("DateTimePicker").date();
  if ( !x ) {
    alert('please select startdate first');
    return false;
  }
});
        ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>

<div class="row">
  <div class="col-xs-6">
    <div class="form-group">
      <label>Start Date</label><br>
      <div class='input-group date datetimepicker6' id="startdate">
        <input type='text' class="form-control" id="start" name="date_end" placeholder="DD/MM/YYYY"/>
        <span class="input-group-addon">
          <span class="glyphicon glyphicon-calendar"></span>
        </span>
      </div>
      <div class="col-xs-6">
        <div class="form-group">
          <label for="start_time" class="col-form-label">Start Time</label>
          <div class='input-group date start_time_addon' id='starttime'>
            <input type='text' class="form-control" placeholder="HH : MM" id="Start_Time" required />
            <span class="input-group-addon">
              <span class="glyphicon glyphicon-time"></span>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

I've added useCurrent: false option to timepicker to prevent getting current time.

Body:
I have two input boxes one is for selecting date and another for time. I am trying to validate these two boxes based on some conditions, such that if the date is not selected, the time should not get selected.

I'm using eonasdan datetimepicker, I'm getting the desired output but not with the single click on a timepicker. Can some one help me out with this?

Here's what I have done so far:

function starttime(){
  $('#starttime').datetimepicker({
    format: 'HH:mm',
    minDate: new Date()
  });
}

$('.start_time_addon').on('click keyup',function(){
  var x = $('#start').val();
  if (x == '') {
    alert('please select startdate first');
    return false;
  }
  else{
    starttime();
  }
});

var datePickerSix= $('.datetimepicker6');
$(datePickerSix).datetimepicker({
  format: 'DD/MM/YYYY',
  minDate: new Date()
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker-standalone.min.css" rel="stylesheet"/>

      Start Date

        <input type='text' class="form-control" id="start" name="date_end" placeholder="DD/MM/YYYY"/>

          Start Time

            <input type='text' class="form-control" placeholder="HH : MM" id="Start_Time" required />

Body:
The problem is that you initialize the time picker only after a click on it, so on the first click the datetimepicker is not already built. Move starttime initialization from starttime to document.ready.

I suggest to disable starttime datetimepicker when the user can not select hours. You can use disable() and enable() method of the datetimepicker.

Use date() method to get datetimepicker selected date and you can listen to dp.change event to known when the user selects a date.

Here a complete example:

$('#startdate').datetimepicker({
  format: 'DD/MM/YYYY',
  minDate: new Date()
}).on('dp.change', function(e){
  if( e.date ){
    // Enable timepicker only if date is selected
    $('#starttime').data("DateTimePicker").enable();
  } else {
    $('#starttime').data("DateTimePicker").disable();
  }
});

$('#starttime').datetimepicker({
  format: 'HH:mm',
  minDate: new Date(),
  useCurrent: false
});
// Disable time picker
$('#starttime').data("DateTimePicker").disable();

$('.start_time_addon').on('click keyup',function(){
  var x = $('#startdate').data("DateTimePicker").date();
  if ( !x ) {
    alert('please select startdate first');
    return false;
  }
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>

<div class="row">
  <div class="col-xs-6">
    <div class="form-group">
      <label>Start Date</label><br>
      <div class='input-group date datetimepicker6' id="startdate">
        <input type='text' class="form-control" id="start" name="date_end" placeholder="DD/MM/YYYY"/>
        <span class="input-group-addon">
          <span class="glyphicon glyphicon-calendar"></span>
        </span>
      </div>
      <div class="col-xs-6">
        <div class="form-group">
          <label for="start_time" class="col-form-label">Start Time</label>
          <div class='input-group date start_time_addon' id='starttime'>
            <input type='text' class="form-control" placeholder="HH : MM" id="Start_Time" required />
            <span class="input-group-addon">
              <span class="glyphicon glyphicon-time"></span>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

I've added useCurrent: false option to timepicker to prevent getting current time.


问:
Make generic Interface in typescript
The Generic part in below line in abc which is in <> .

Actually as I am coming from Javascript side to Typescript side in angular 2 .

That's why I am not seen these Generic part in Javascript .

```<code>export interface Animals<abc>

export class WaterAnimal <abc> implements Animals<abc> { }
</code>```

Things which I get :

Generic Part helps to maintain the type which we are sending and achieving from any function will be of same type that type can be any Object,String,Number or Array.

Eg :-

```<code>function identity<T>(arg: T): T {
    return arg;
}
</code>```

Things I want to Ask:-

When We come in Classes and Interfaces :- by passing the parameters in
Interface as in Animals interface what is the purpose of it .

If there is any purpose which i don't aware of yet ,now if we implements that Animal Interface to WaterAnimal Class then I want to write <abc> infront of Animal Interface because while defining that Interface I have pass that thing as parameter into it .So Why complier is forcing me to define <abc> with the WaterAnimal Class ..Is there is any Reason behind this..

Any help will be appreciated .

答:
A good example of Generics exists in the language itself.

Most languages had forms on un-typed lists, like the JavaScript Array:

```<code>var arr = [
    1,
    "str",
    new Customer()
];
</code>```

But a much more useful object is an array that only contains a single type - because then you can iterate the array knowing everything is the same:

```<code>var arr: NumberArray = [
    1,
    3,
    5
];
</code>```

But we would need to create a new type for each kind of array, so we would end up with NumberArray, StringArray, CustomerArray... and so on.

So instead of creating a nearly infinite number of types, we create a generic one. We then specify what type we intend to use:

```<code>var arr: Array<number>= [
    1,
    3,
    5
];
</code>```

The type argument (number) allows us to re-use the Array class or interface rather than create new kinds. The condition on this is that Array cannot know anything about this type unless we specify a type constraint.

To understand how this can be used within a generic class, here is a quick fake example:

```<code>class ArrayOfOne<T> {
    private item: T;

    add(item: T) {
        this.item = item;
    }

    retrieve() : T {
        return this.item;
    }
}
</code>```

In this example, the ArrayOfOne class doesn't need to know what T is, but if you use it, T will be strongly typed.

```<code>var arr = new ArrayOfOne<string>();
arr.add("str"); // ok
arr.add(1); //not ok

var str: string = arr.retrieve(); // ok
var num: number = arr.retrieve(); // not ok
</code>```

Title: Make generic Interface in typescript

Body:
The Generic part in below line in abc which is in <> .

Actually as I am coming from Javascript side to Typescript side in angular 2 .

That's why I am not seen these Generic part in Javascript .

export interface Animals<abc>

export class WaterAnimal <abc> implements Animals<abc> { }

Things which I get :

Generic Part helps to maintain the type which we are sending and achieving from any function will be of same type that type can be any Object,String,Number or Array.

Eg :-

function identity<T>(arg: T): T {
    return arg;
}

Things I want to Ask:-

When We come in Classes and Interfaces :- by passing the parameters in
Interface as in Animals interface what is the purpose of it .

If there is any purpose which i don't aware of yet ,now if we implements that Animal Interface to WaterAnimal Class then I want to write <abc> infront of Animal Interface because while defining that Interface I have pass that thing as parameter into it .So Why complier is forcing me to define <abc> with the WaterAnimal Class ..Is there is any Reason behind this..

Any help will be appreciated .

Body:
A good example of Generics exists in the language itself.

Most languages had forms on un-typed lists, like the JavaScript Array:

var arr = [
    1,
    "str",
    new Customer()
];

But a much more useful object is an array that only contains a single type - because then you can iterate the array knowing everything is the same:

var arr: NumberArray = [
    1,
    3,
    5
];

But we would need to create a new type for each kind of array, so we would end up with NumberArray, StringArray, CustomerArray... and so on.

So instead of creating a nearly infinite number of types, we create a generic one. We then specify what type we intend to use:

var arr: Array<number>= [
    1,
    3,
    5
];

The type argument (number) allows us to re-use the Array class or interface rather than create new kinds. The condition on this is that Array cannot know anything about this type unless we specify a type constraint.

To understand how this can be used within a generic class, here is a quick fake example:

class ArrayOfOne<T> {
    private item: T;

    add(item: T) {
        this.item = item;
    }

    retrieve() : T {
        return this.item;
    }
}

In this example, the ArrayOfOne class doesn't need to know what T is, but if you use it, T will be strongly typed.

var arr = new ArrayOfOne<string>();
arr.add("str"); // ok
arr.add(1); //not ok

var str: string = arr.retrieve(); // ok
var num: number = arr.retrieve(); // not ok


答:
pyexcel version:</p>

```<code>import pyexcel as p

p.get_dict(file_name='test.csv')
</code>```

Title: convert csv to dictionary

Body:
I have the following csv file(total 20000 lines)

ozone,paricullate_matter,carbon_monoxide,sulfure_dioxide,nitrogen_dioxide,longitude,latitude,timestamp,avg_measured_time,avg_speed,median_measured_time,timestamp:1,vehicle_count,lat1,long1,lat2,long2,distance_between_2_points,duration_of_measurement,ndt_in_kmh
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1089513576227,10.1823955595246,56.1048021343541,10.1988040846558,1124,65,62
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.10986429895,10.1627288048935,56.1089513576227,10.1823955595246,1254,71,64
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1425188527673,10.1868802625656,56.1417522836526,10.1927236478157,521,62,30
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,18,84,18,1407575099.99998,1,56.1395320665735,10.1772034087371,56.1384485157567,10.1791506011887,422,50,30

I want to convert this into a dictionary like

{'ozone': [99,99,99,99], 'paricullate_matter': [99,99,99,99],'carbon_monoxide': [98,98,98,98],etc....}

What i have tried

import csv

reader = csv.DictReader(open('resulttable.csv'))

output = open("finalprojdata.py","w")

result = {}
for row in reader:
    for column, value in row.iteritems():
        result.setdefault(column, []).append(float(value))
output.write(str(result))

The output am getting is consisting of only few dictionaries. Like from

{'vehicle_count': [0,0,0,1], 'lat1': etc}

The whole csv file is not getting converted to dictionary.

Body:
pyexcel version:

import pyexcel as p

p.get_dict(file_name='test.csv')


问:
Angular CLI rebuild process takes a long time
Issue:
i have an angular app with latest versions as of (June 2017)

once I make a small change or big changes in many files and save

the rebuild process kicks and 8 out of 10 times it takes more than 60 seconds. mostly in the assets folder.

I looked in SO and Github but none with a valid solution.

PS: assets folder being large should not have impacted the performance as per comments from github.

OS:
Windows 10

Versions:

```<code>@angular/cli: 1.1.0

node: 6.10.3

os: win32 x64

@angular/animations: 4.1.3

@angular/common: 4.1.3

@angular/compiler: 4.1.3

@angular/core: 4.1.3

@angular/forms: 4.1.3

@angular/http: 4.1.3

@angular/platform-browser: 4.1.3

@angular/platform-browser-dynamic: 4.1.3

@angular/router: 4.1.3

@angular/cli: 1.1.0

@angular/compiler-cli: 4.1.3
</code>```

答:
SOLVED: uninstall and reinstall node. thanks @Bean0341

removed 64bit version and installed 32Bit.

Body:
Issue:
i have an angular app with latest versions as of (June 2017)

once I make a small change or big changes in many files and save

the rebuild process kicks and 8 out of 10 times it takes more than 60 seconds. mostly in the assets folder.

I looked in SO and Github but none with a valid solution.

PS: assets folder being large should not have impacted the performance as per comments from github.

OS:
Windows 10

Versions:

@angular/cli: 1.1.0

node: 6.10.3

os: win32 x64

@angular/animations: 4.1.3

@angular/common: 4.1.3

@angular/compiler: 4.1.3

@angular/core: 4.1.3

@angular/forms: 4.1.3

@angular/http: 4.1.3

@angular/platform-browser: 4.1.3

@angular/platform-browser-dynamic: 4.1.3

@angular/router: 4.1.3

@angular/cli: 1.1.0

@angular/compiler-cli: 4.1.3


问:
Filter in pandas using operators
I have Three variables as

```<code>a='col1'
b='=='
c=2
</code>```

I have Pandas dataframe as

```<code>df = pd.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]},dtype=object)
</code>```

And I wanted to filter for col1=2, So I wrote

```<code>df.query("@a @b @c")
</code>```

Which is throwing below error

```<code>File "<unknown>", line 1
    __pd_eval_local_a __pd_eval_local_b __pd_eval_local_c
                                      ^
SyntaxError: invalid syntax
</code>```

Can some one help me how to achieve this using these three variables?

Thanks,

Title: Filter in pandas using operators

Body:
I have Three variables as

a='col1'
b='=='
c=2

I have Pandas dataframe as

df = pd.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]},dtype=object)

And I wanted to filter for col1=2, So I wrote

df.query("@a @b @c")

Which is throwing below error

File "<unknown>", line 1
    __pd_eval_local_a __pd_eval_local_b __pd_eval_local_c
                                      ^
SyntaxError: invalid syntax

Can some one help me how to achieve this using these three variables?

Thanks,

Body:
In [214]: df
Out[214]:
  col1 col2 col3
0    0   10  aaa
1    1   11  bbb
2    2   12  ccc

In [215]: a='col1'; b='=='; c=2   # <--- `c` is `int`

In [216]: df.query(a + b + '@c')
Out[216]:
  col1 col2 col3
2    2   12  ccc

In [217]: a='col3'; b='=='; c='aaa'   # <--- `c` is `str`

In [218]: df.query(a + b + '@c')
Out[218]:
  col1 col2 col3
0    0   10  aaa

it will also work with datetime dtypes, as .query() would take care of dtypes:

In [226]: df['col4'] = pd.date_range('2017-01-01', freq='99D', periods=len(df))

In [227]: df
Out[227]:
  col1 col2 col3       col4
0    0   10  aaa 2017-01-01
1    1   11  bbb 2017-04-10
2    2   12  ccc 2017-07-18

In [228]: a='col4'; b='=='; c='2017-01-01'

In [229]: df.query(a + b + '@c')
Out[229]:
  col1 col2 col3       col4
0    0   10  aaa 2017-01-01


答:
I think you want something like this:

```<code>select p.ID as col_1, p.SupplierID as col_2, p.Revision2 as col_3,
       p.ItemID as col_4, p.OrderNumber as col_5, '' as col_12,
       s.SCompany as col_6, s.SCode as col_7, s.SCIPEMail as col_8,
       s.SCIPContact as col_9, s.SPDRemitType as col_10, s.SCIPFax as col_11,
       (select count(*)
        from DYN_PORDERS p2
        WHERE p2.OrderNumber = 5
       ) as column3
from DYN_PORDERS  p inner join
     SYS_SUPPLIERS s
     on s.ID = p.SupplierID
where p.OrderStatus1 = 1 and p.ItemID = 1
order by p.OrderNumber asc, p.itemid asc;
</code>```

Notes:

I strongly recommend that you not name columns as numbers.  This is just confusing and requires escape characters (which might vary by database).

Use table aliases that are abbreviations of the table names.  Queries are easier to write and to read.

Don't use single quotes around numeric constants.

Title: Record Count (Nested??)

Body:
I think you want something like this:

select p.ID as col_1, p.SupplierID as col_2, p.Revision2 as col_3,
       p.ItemID as col_4, p.OrderNumber as col_5, '' as col_12,
       s.SCompany as col_6, s.SCode as col_7, s.SCIPEMail as col_8,
       s.SCIPContact as col_9, s.SPDRemitType as col_10, s.SCIPFax as col_11,
       (select count(*)
        from DYN_PORDERS p2
        WHERE p2.OrderNumber = 5
       ) as column3
from DYN_PORDERS  p inner join
     SYS_SUPPLIERS s
     on s.ID = p.SupplierID
where p.OrderStatus1 = 1 and p.ItemID = 1
order by p.OrderNumber asc, p.itemid asc;

Notes:

I strongly recommend that you not name columns as numbers.  This is just confusing and requires escape characters (which might vary by database).

Use table aliases that are abbreviations of the table names.  Queries are easier to write and to read.

Don't use single quotes around numeric constants.


问:
MapView to show all annotations and zoom in as much as possible of the map
I basically have a map where I add two annotations and they are shown as expected.

Then I´m using the following code:

```<code>let annotations = [start, end]
mapView?.showAnnotations(annotations, animated: false)
</code>```

And this zooms to show my map with the two annotations, but the map could be zoomed in much more and show a more detailed map view.

This is what I get today and this is the expected result that I want.

As you can see the map could be zoomed in a lot more.

Any ideas how to achieve this?

答:
Use this:

```<code>extension MKMapView {
    /// when we call this function, we have already added the annotations to the map, and just want all of them to be displayed.
    func fitAll() {
        var zoomRect            = MKMapRectNull;
        for annotation in annotations {
            let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
            let pointRect       = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.01, 0.01);
            zoomRect            = MKMapRectUnion(zoomRect, pointRect);
        }
        setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(100, 100, 100, 100), animated: true)
    }

    /// we call this function and give it the annotations we want added to the map. we display the annotations if necessary
    func fitAll(in annotations: [MKAnnotation], andShow show: Bool) {
        var zoomRect:MKMapRect  = MKMapRectNull

        for annotation in annotations {
            let aPoint          = MKMapPointForCoordinate(annotation.coordinate)
            let rect            = MKMapRectMake(aPoint.x, aPoint.y, 0.1, 0.1)

            if MKMapRectIsNull(zoomRect) {
                zoomRect = rect
            } else {
                zoomRect = MKMapRectUnion(zoomRect, rect)
            }
        }
        if(show) {
            addAnnotations(annotations)
        }
        setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100), animated: true)
    }

}
</code>```

then, after creating an outlet for your MapView, for example as map, and with you annotations either added to the map of in an array called annotations, access the above methods like so:

```<code>map.fitAll()
</code>```

OR

```<code>map.fitAll(in:annotations, true)
</code>```

respectively.

Use true or false in the last statement depending on whether you had added the annotations to the map before or not...

Body:
I basically have a map where I add two annotations and they are shown as expected.

Then I´m using the following code:

let annotations = [start, end]
mapView?.showAnnotations(annotations, animated: false)

And this zooms to show my map with the two annotations, but the map could be zoomed in much more and show a more detailed map view.

This is what I get today and this is the expected result that I want.

As you can see the map could be zoomed in a lot more.

Any ideas how to achieve this?

Body:
Use this:

extension MKMapView {
    /// when we call this function, we have already added the annotations to the map, and just want all of them to be displayed.
    func fitAll() {
        var zoomRect            = MKMapRectNull;
        for annotation in annotations {
            let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
            let pointRect       = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.01, 0.01);
            zoomRect            = MKMapRectUnion(zoomRect, pointRect);
        }
        setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(100, 100, 100, 100), animated: true)
    }

    /// we call this function and give it the annotations we want added to the map. we display the annotations if necessary
    func fitAll(in annotations: [MKAnnotation], andShow show: Bool) {
        var zoomRect:MKMapRect  = MKMapRectNull

        for annotation in annotations {
            let aPoint          = MKMapPointForCoordinate(annotation.coordinate)
            let rect            = MKMapRectMake(aPoint.x, aPoint.y, 0.1, 0.1)

            if MKMapRectIsNull(zoomRect) {
                zoomRect = rect
            } else {
                zoomRect = MKMapRectUnion(zoomRect, rect)
            }
        }
        if(show) {
            addAnnotations(annotations)
        }
        setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100), animated: true)
    }

}

then, after creating an outlet for your MapView, for example as map, and with you annotations either added to the map of in an array called annotations, access the above methods like so:

map.fitAll()

OR

map.fitAll(in:annotations, true)

respectively.

Use true or false in the last statement depending on whether you had added the annotations to the map before or not...


问:
Java: XML to Object (or Array)
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

```<code>DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();
</code>```

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?

答: I recommend using XStream for XML (de)serialization. It's way simpler than using Java's built-in XML APIs.

Title: Java: XML to Object (or Array)

Body:
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:

DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();

Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?


问:
CakePHP get action name
In CakePHP, it is possible to get the called function string using the

```<code>$this->action
</code>```

syntax. It returns the literal string of whatever is called, so if the URL is /do_this, it returns do_this, and if it's doThis it'll return doThis. Regardless of the called method's real name.

What I am looking for, on the other hand, is the called method's actual name, no matter the URL syntax.

Is there a way to find it out?

I'd preferably be able to do this in the beforeFilter method.

答:
The params array (CakePHP >= 3.4) is deprecated The correct way to get the current action within a controller is :

```<code>$currentAction = $this->request->getParam('action');
</code>```

Title: CakePHP get action name

Body:
In CakePHP, it is possible to get the called function string using the

$this->action

syntax. It returns the literal string of whatever is called, so if the URL is /do_this, it returns do_this, and if it's doThis it'll return doThis. Regardless of the called method's real name.

What I am looking for, on the other hand, is the called method's actual name, no matter the URL syntax.

Is there a way to find it out?

I'd preferably be able to do this in the beforeFilter method.

Body:
The params array (CakePHP >= 3.4) is deprecated The correct way to get the current action within a controller is :

$currentAction = $this->request->getParam('action');


问:
Bypass excel csv formula conversion on fields starting with + or -
I have a csv file with contents:

```<code>"x","y","-z"
</code>```

When I import it I get:

How can I bypass this conversion?

Update

If you try:

```<code>   "x","y",="-z,a"
</code>```

The ",a" is not imported.

If you put a space in front:

```<code>   "x","y",=" -z"
</code>```

or

```<code>   "x","y"," -z"
</code>```

it will work fine

答:
Find and replace every instance of
+
with
' +

A single quote and space at the beginning should cancel out any +, -, or =.

Body:
I have a csv file with contents:

"x","y","-z"

When I import it I get:

How can I bypass this conversion?

Update

If you try:

   "x","y",="-z,a"

The ",a" is not imported.

If you put a space in front:

   "x","y",=" -z"

or

   "x","y"," -z"

it will work fine