问:
How to get the local timezone given time and state info
I am using a combination of Python and Amazon Redshift.
I have hits from various users and some data around those hits. This may be visualized in the following format:

```<code>UTCTime    State    IP    Country
<time>    CA    10.1.1.1    US
<time>    AZ    10.1.1.2    US
<time>    NY    10.1.1.3    US
</code>```

I would like to convert this UTC time to the local time, as the above hits are from various time zones. There's a function in Amazon Redshift:

```<code>CONVERT_TIMEZONE ( ['source_timezone',] 'target_timezone', 'timestamp')
</code>```

But this requires Target timezone. How do I find this target timezone given this info.

If there's any other way to do this, I will be happy to know that too.

Any help will be greatly appreciated.

答:
You could approach this problem by using us package. Add it via pip:

```<code>$ pip install us
</code>```

The state lookup method allows matching by FIPS code, abbreviation, and name:

```<code>>>> us.states.lookup('24')
<State:Maryland>
>>> us.states.lookup('MD')
<State:Maryland>
>>> us.states.lookup('md')
<State:Maryland>
>>> us.states.lookup('maryland')
<State:Maryland>
</code>```

as mentioned in us package description, State object has time_zones and capital_tz attributes, which names are self explanitory:

```<code>>>> us.states.lookup('MD').capital_tz
'America/New_York'
</code>```

and

```<code>>>> us.states.lookup('MD').time_zones
['America/New_York']
</code>```

Now you can easily translate state abbreviation to full time zone name.

Body:
I am using a combination of Python and Amazon Redshift.
I have hits from various users and some data around those hits. This may be visualized in the following format:

UTCTime    State    IP    Country
<time>    CA    10.1.1.1    US
<time>    AZ    10.1.1.2    US
<time>    NY    10.1.1.3    US

I would like to convert this UTC time to the local time, as the above hits are from various time zones. There's a function in Amazon Redshift:

CONVERT_TIMEZONE ( ['source_timezone',] 'target_timezone', 'timestamp')

But this requires Target timezone. How do I find this target timezone given this info.

If there's any other way to do this, I will be happy to know that too.

Any help will be greatly appreciated.

Body:
You could approach this problem by using us package. Add it via pip:

$ pip install us

The state lookup method allows matching by FIPS code, abbreviation, and name:

>>> us.states.lookup('24')
<State:Maryland>
>>> us.states.lookup('MD')
<State:Maryland>
>>> us.states.lookup('md')
<State:Maryland>
>>> us.states.lookup('maryland')
<State:Maryland>

as mentioned in us package description, State object has time_zones and capital_tz attributes, which names are self explanitory:

>>> us.states.lookup('MD').capital_tz
'America/New_York'

and

>>> us.states.lookup('MD').time_zones
['America/New_York']

Now you can easily translate state abbreviation to full time zone name.


来源: stackexchange

问:
too high implementation for minSDK in build.gradle created by Android Studio
I've just created my first Android Studio project. I chose min SDK 15. I'm worried why then compile SDK by default is higher.. Is it secure? Will my app run on devices with API 15 in this configuration? But the real problem occurred when I switched my compileSdkVersion and targetSdkVersion to 24. Errors everywhere and info that implementation 'com.android.support:appcompat-v7:26.1.0' is too high for my target SDK. So why on earth Android Studio put there so high implementation if the min SDK is lower?

TL;DR:
Why implementation is so high? Will it work in this configuration with min API?? Why Android Studio works like this?

build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.q_back.audiocrator"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

答:
All android devices with SDK versions equal and above the minSDKVersion will be able to run the application.
it is best to use the same version of SDK tools as the version on your compileSDK, it won't really affect the devices that can run the applications. the major factor is that some Google APIs wont work on lower SDK levels.</p>

ContentLicense: CC BY-SA 3.0

Body:
I've just created my first Android Studio project. I chose min SDK 15. I'm worried why then compile SDK by default is higher.. Is it secure? Will my app run on devices with API 15 in this configuration? But the real problem occurred when I switched my compileSdkVersion and targetSdkVersion to 24. Errors everywhere and info that implementation 'com.android.support:appcompat-v7:26.1.0' is too high for my target SDK. So why on earth Android Studio put there so high implementation if the min SDK is lower?

TL;DR:
Why implementation is so high? Will it work in this configuration with min API?? Why Android Studio works like this?

build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.q_back.audiocrator"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}


问:
SQL - how to query to find if two columes are 1to1 1tomany manytomany relationship?
I want to draw a class diagram to describe the relationship between columes. how to query to find if two columes are 1to1 or 1tomany or manytomany relationship? for example, below table shows that column "name" is 1-to-many with colume "prod".

答:
The difficult part is detecting the many-many relationship which is similar to a circuit.  You need to find, for any column pair, if the value on either side has another pairing.  For the 1-many or many-1 it's more straightforward, just count matches by row in an outer apply(). This looks a little daunting, but seems to do the trick...</p>

```<code>    create table #relationships (col_a char(1), col_b int)

-- one to one
insert into #relationships select 'a', 1

-- one to many
insert into #relationships select 'b', 2
insert into #relationships select 'b', 3

-- many to many
insert into #relationships select 'c', 4
insert into #relationships select 'c', 5
insert into #relationships select 'd', 5

-- many to one
insert into #relationships select 'e', 6
insert into #relationships select 'f', 6

select  a.col_a,
        a.col_b,
        case when circuit.col_a is not null then 'Many-Many' -- order important
             when cnt1.cnt1 = 1 and cnt2.cnt2 = 1 then 'One-One'
             when cnt1.cnt1 = 2 and cnt2.cnt2 = 1 then 'One-Many'
             when cnt1.cnt1 = 1 and cnt2.cnt2 = 2 then 'Many-One'
        end
from #relationships a
cross apply( select count(*) cnt1
             from ( select distinct col_b
                    from #relationships b
                    where b.col_a = a.col_a )x) cnt1
cross apply( select count(*) cnt2
             from ( select distinct col_a
                    from #relationships b
                    where b.col_b = a.col_b )x) cnt2

left join ( select x.col_a,
                   x.col_b
            from #relationships a
            outer  apply ( select b.col_a,
                                  b.col_b
                           from #relationships b
                            where  a.col_a = b.col_a
                                    and exists ( select 1
                                                 from #relationships c
                                                 where b.col_b = c.col_b
                                                   and c.col_a <> a.col_a )
                              and ( a.col_b = b.col_b
                                    and exists ( select 1
                                                 from #relationships c
                                                 where b.col_a = c.col_a
                                                   and c.col_b <> a.col_b ))) x
        ) circuit
    on a.col_a = circuit.col_a
    or  a.col_b = circuit.col_b

col_a col_b
----- ----------- ---------
a     1           One-One
b     2           One-Many
b     3           One-Many
c     4           Many-Many
c     5           Many-Many
d     5           Many-Many
e     6           Many-One
f     6           Many-One
</code>```

Body:
The difficult part is detecting the many-many relationship which is similar to a circuit.  You need to find, for any column pair, if the value on either side has another pairing.  For the 1-many or many-1 it's more straightforward, just count matches by row in an outer apply(). This looks a little daunting, but seems to do the trick...

    create table #relationships (col_a char(1), col_b int)

-- one to one
insert into #relationships select 'a', 1

-- one to many
insert into #relationships select 'b', 2
insert into #relationships select 'b', 3

-- many to many
insert into #relationships select 'c', 4
insert into #relationships select 'c', 5
insert into #relationships select 'd', 5

-- many to one
insert into #relationships select 'e', 6
insert into #relationships select 'f', 6

select  a.col_a,
        a.col_b,
        case when circuit.col_a is not null then 'Many-Many' -- order important
             when cnt1.cnt1 = 1 and cnt2.cnt2 = 1 then 'One-One'
             when cnt1.cnt1 = 2 and cnt2.cnt2 = 1 then 'One-Many'
             when cnt1.cnt1 = 1 and cnt2.cnt2 = 2 then 'Many-One'
        end
from #relationships a
cross apply( select count(*) cnt1
             from ( select distinct col_b
                    from #relationships b
                    where b.col_a = a.col_a )x) cnt1
cross apply( select count(*) cnt2
             from ( select distinct col_a
                    from #relationships b
                    where b.col_b = a.col_b )x) cnt2

left join ( select x.col_a,
                   x.col_b
            from #relationships a
            outer  apply ( select b.col_a,
                                  b.col_b
                           from #relationships b
                            where  a.col_a = b.col_a
                                    and exists ( select 1
                                                 from #relationships c
                                                 where b.col_b = c.col_b
                                                   and c.col_a <> a.col_a )
                              and ( a.col_b = b.col_b
                                    and exists ( select 1
                                                 from #relationships c
                                                 where b.col_a = c.col_a
                                                   and c.col_b <> a.col_b ))) x
        ) circuit
    on a.col_a = circuit.col_a
    or  a.col_b = circuit.col_b

col_a col_b
----- ----------- ---------
a     1           One-One
b     2           One-Many
b     3           One-Many
c     4           Many-Many
c     5           Many-Many
d     5           Many-Many
e     6           Many-One
f     6           Many-One


问:
Git: Remove all revisions of a file in a repository, and replace with new file
I need to move current and ALL past revisions of a file in my repository, and then replace them with a new file.  Basically, without thinking, I forgot (and continuously forgot) to remove the mysql password for the database connection file, and would like to remove any traces of this.

The simplest fix would be to change the mysql password and from this point on, do not include the password in the file, however, I'd like to just clean up the revision history.

答:
See the previous answer: Remove sensitive files and their commits from Git history

git filter-branch to the rescue: http://git-scm.com/docs/git-filter-branch

Beware that this will change all of the SHA-hashes of your commits, but that's OK if it's a personal project.

ContentLicense: CC BY-SA 2.5


问:
Docker container not running properly. Exit status Code 255

I am trying to start my localhost server (http://localhost:8080) on my mac using docker. I created a docker image with the following Dockerfile:

Then run the following docker command to create the image from my directory:

```<code>docker build -t packt-chp6 .
</code>```

After the image was created, I ran the following docker command to start my localhost server:

```<code>docker run -d --name chat-app -v $PWD:/opt/app -p 8080:8080 packt-chp6
</code>```

The Problem

Localhost server is unable to connect. When I list all my containers with the -a flag, I see the following:

I have deleted containers and build again from the scratch, and I still get the same result.

Thank you for the help. I appreciate...

答:
I solved the problem by running the following docker command without the -d flag

```<code>docker run --name chat-app -v $PWD:/opt/app -p 8080:8080 packt-chp6
</code>```

Found out there was an error on my php server script, I wasn't including 'src/ChatComponent.php' file. Here is a sample of server.php

```<code>require_once 'vendor/autoload.php';
require_once 'src/ChatComponent.php';

$app = new \Ratchet\App('localhost', 8080, '0.0.0.0');
$app->route('/chat', new \Packt\Chp6\Chat\ChatComponent);
$app->run();
</code>```

After I included the file, it worked fine. Thanks

Body:
I am trying to start my localhost server (http://localhost:8080) on my mac using docker. I created a docker image with the following Dockerfile:

Then run the following docker command to create the image from my directory:

docker build -t packt-chp6 .

After the image was created, I ran the following docker command to start my localhost server:

docker run -d --name chat-app -v $PWD:/opt/app -p 8080:8080 packt-chp6

The Problem

Localhost server is unable to connect. When I list all my containers with the -a flag, I see the following:

I have deleted containers and build again from the scratch, and I still get the same result.

Thank you for the help. I appreciate...

Body:
I solved the problem by running the following docker command without the -d flag

docker run --name chat-app -v $PWD:/opt/app -p 8080:8080 packt-chp6

Found out there was an error on my php server script, I wasn't including 'src/ChatComponent.php' file. Here is a sample of server.php

require_once 'vendor/autoload.php';
require_once 'src/ChatComponent.php';

$app = new \Ratchet\App('localhost', 8080, '0.0.0.0');
$app->route('/chat', new \Packt\Chp6\Chat\ChatComponent);
$app->run();

After I included the file, it worked fine. Thanks


问:
Code brevity in C# - condensing a setter that throws if null
In prior versions of C#, if you wanted to prevent a null reference exception, you needed to build your setters defensively:

```<code>public Guid ItemId { get; set; } //foreign key, required

private Item _item;
public virtual Item Item {
  get {
    return _item;
  }
  set {
    if(value == null) throw new ArgumentNullException(nameof(value));
    _item = value;
    ItemId = value.ItemId;
  }
}
</code>```

With more modern implementations, this can be condensed a certain amount using the null-coalescing operator and expression bodies:

```<code>private Item _item;
public virtual Item Item {
  get => _item;
  set => _item = value ?? throw new ArgumentNullException(nameof(value));
}
</code>```

However, I am curious if this could not be condensed entirely down into a variation of the standard reference:

```<code>public virtual Item Item { get; set; }
</code>```

Such that you do not have to define a private item.

Suggestions? Or is the second code block as efficient/simple as I can get?

I am looking for a solution within the current C# framework, not something I have to spend money on. Right now my use case proposition does not support a paid product

答:
Disclaimer: Those are potential 'alternative' ways of filtering out invalid assignments into properties. This might not provide a straight answer to the question, but rather give ideas how to go on about doing it more generically without defining private properties and defining getters and setters explicitly.

Depending on what Item actually is, you could perhaps create a non-nullable type of Item by creating it as a struct.

Non nullable types are called structs. They are nothing new, they are value types which allow to store properties of type int, string, bool etc.

As on MSDN:

A struct type is a value type that is typically used to encapsulate
  small groups of related variables, such as the coordinates of a
  rectangle or the characteristics of an item in an inventory.

The following example shows a simple struct declaration:

```<code>public struct Book
{
    public decimal price{ get; set;}
    public string title;
    public string author;
}
</code>```

Reference

Edit (Struct should be sufficient if the object is supposed to be non-nullable type, however if we're talking properties of the class then read below.) :

Another way would be using OnPropertyChanged event which is part of the INotifyPropertyChanged interface.

While the event does not explicitly give you the value that has been changed to, you can grab it as it does provide you the property name. So you could run your validation post assignment and throw then, I suppose however it might not be the best option.

```<code>void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var propertyValue = sender.GetType().GetProperty(e.PropertyName).GetValue(sender);
}
</code>```

Another solution would be using DataAnnotations and add Required attributes on your properties. If I'm not mistaken they will not throw straight away, until you call your own validate function to validate the class, I guess, combined with the above method this would work pretty well and would be pretty generic. Once written you wouldn't have to write your getters and setters explicitly but rather attach just one event to your class and validate it once a property changes.

Here's a small example:

Your Item model for example...

```<code>public class Item
{
    [Required]
    public string Name { get; set; }
}
</code>```

You would then implement a generic function which would validate all properties.

```<code>public bool TryValidate(object @object, out ICollection < ValidationResult > results) {
   var context = new ValidationContext(@object, serviceProvider: null, items: null);

   results = new List <ValidationResult> ();

   return Validator.TryValidateObject(
    @object, context, results,
    validateAllProperties: true
   );
}
</code>```

Inside that function you would of course throw an exception if validation failed, your results array would contain properties that it failed on an default messages if I'm not mistaken. I believe this is a bit complex, but if you're looking for reducing the number of properties and setter implementations, this could be a step forward. I'm not sure on the overhead etc. Personally, I think on a larger scale, this would be super useful to validate models which are created on the fly from db data or any external source.

Validator Reference | Data Annotations Reference | ValidationResults Reference | PropertyChanged MSDN Sample

Body:
In prior versions of C#, if you wanted to prevent a null reference exception, you needed to build your setters defensively:

public Guid ItemId { get; set; } //foreign key, required

private Item _item;
public virtual Item Item {
  get {
    return _item;
  }
  set {
    if(value == null) throw new ArgumentNullException(nameof(value));
    _item = value;
    ItemId = value.ItemId;
  }
}

With more modern implementations, this can be condensed a certain amount using the null-coalescing operator and expression bodies:

private Item _item;
public virtual Item Item {
  get => _item;
  set => _item = value ?? throw new ArgumentNullException(nameof(value));
}

However, I am curious if this could not be condensed entirely down into a variation of the standard reference:

public virtual Item Item { get; set; }

Such that you do not have to define a private item.

Suggestions? Or is the second code block as efficient/simple as I can get?

I am looking for a solution within the current C# framework, not something I have to spend money on. Right now my use case proposition does not support a paid product

Body:
Disclaimer: Those are potential 'alternative' ways of filtering out invalid assignments into properties. This might not provide a straight answer to the question, but rather give ideas how to go on about doing it more generically without defining private properties and defining getters and setters explicitly.

Depending on what Item actually is, you could perhaps create a non-nullable type of Item by creating it as a struct.

Non nullable types are called structs. They are nothing new, they are value types which allow to store properties of type int, string, bool etc.

As on MSDN:

A struct type is a value type that is typically used to encapsulate
  small groups of related variables, such as the coordinates of a
  rectangle or the characteristics of an item in an inventory.

The following example shows a simple struct declaration:

public struct Book
{
    public decimal price{ get; set;}
    public string title;
    public string author;
}

Reference

Edit (Struct should be sufficient if the object is supposed to be non-nullable type, however if we're talking properties of the class then read below.) :

Another way would be using OnPropertyChanged event which is part of the INotifyPropertyChanged interface.

While the event does not explicitly give you the value that has been changed to, you can grab it as it does provide you the property name. So you could run your validation post assignment and throw then, I suppose however it might not be the best option.

void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var propertyValue = sender.GetType().GetProperty(e.PropertyName).GetValue(sender);
}

Another solution would be using DataAnnotations and add Required attributes on your properties. If I'm not mistaken they will not throw straight away, until you call your own validate function to validate the class, I guess, combined with the above method this would work pretty well and would be pretty generic. Once written you wouldn't have to write your getters and setters explicitly but rather attach just one event to your class and validate it once a property changes.

Here's a small example:

Your Item model for example...

public class Item
{
    [Required]
    public string Name { get; set; }
}

You would then implement a generic function which would validate all properties.

public bool TryValidate(object @object, out ICollection < ValidationResult > results) {
   var context = new ValidationContext(@object, serviceProvider: null, items: null);

   results = new List <ValidationResult> ();

   return Validator.TryValidateObject(
    @object, context, results,
    validateAllProperties: true
   );
}

Inside that function you would of course throw an exception if validation failed, your results array would contain properties that it failed on an default messages if I'm not mistaken. I believe this is a bit complex, but if you're looking for reducing the number of properties and setter implementations, this could be a step forward. I'm not sure on the overhead etc. Personally, I think on a larger scale, this would be super useful to validate models which are created on the fly from db data or any external source.

Validator Reference | Data Annotations Reference | ValidationResults Reference | PropertyChanged MSDN Sample


问:
In C ,we use %x.ys for string manipulation. What it will be in C++?
How can I replace printf() with cout?
My Code In C++:

```<code>    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main ()
    {
        char st[15]="United Kingdom";
        printf("%5s\n",st);
        printf("%15.6s\n",st);
        printf("%-15.6s\n",st);
        printf("%.3s\n",st); // prints "Uni"
        return 0;
    }
</code>```

The Code Prints:

```<code>United Kingdom

       United

United

Uni
</code>```

How can I manipulate like this in C++?

答:
You are looking for Boost.Format.

```<code>#include <iostream>
#include <string>

#include <boost/format.hpp>

int main()
{
    std::string st = "United Kingdom";
    std::cout << boost::format("%15s\n") % st;
    std::cout << boost::format("%5s\n") % st;
    std::cout << boost::format("%15.6s\n") % st;
    std::cout << boost::format("%-15.6s\n") % st;
    std::cout << boost::format("%15.0s\n") % st;
    std::cout << boost::format("%.3s\n") % st; // prints "Uni"
    std::cout << boost::format("%s\n") % st;
}
</code>```

Live example

Body:
How can I replace printf() with cout?
My Code In C++:

    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main ()
    {
        char st[15]="United Kingdom";
        printf("%5s\n",st);
        printf("%15.6s\n",st);
        printf("%-15.6s\n",st);
        printf("%.3s\n",st); // prints "Uni"
        return 0;
    }

The Code Prints:

United Kingdom

       United

United

Uni

How can I manipulate like this in C++?

Body:
You are looking for Boost.Format.

#include <iostream>
#include <string>

#include <boost/format.hpp>

int main()
{
    std::string st = "United Kingdom";
    std::cout << boost::format("%15s\n") % st;
    std::cout << boost::format("%5s\n") % st;
    std::cout << boost::format("%15.6s\n") % st;
    std::cout << boost::format("%-15.6s\n") % st;
    std::cout << boost::format("%15.0s\n") % st;
    std::cout << boost::format("%.3s\n") % st; // prints "Uni"
    std::cout << boost::format("%s\n") % st;
}

Live example


问:
C# loop - break vs. continue
In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?

Example:

```<code>foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}
</code>```

答:
When to use break vs continue?

Break - We're leaving the loop forever and breaking up forever.  Good bye.

Continue - means that you're gonna give today a rest and sort it all out tomorrow (i.e. skip the current iteration)!

(Corny stories ¯¯\(ツ)/¯¯ and pics solely to help you remember...hopefully you'll never forget)

Gripe Alert:

No idea why those words are being used. If you want to skip the iteration, why not use the word skip instead of continue? This entire Stack overflow question and 1000s of developers would not be confused if the proper name was given.)

ContentLicense: CC BY-SA 4.0

Title: C# loop - break vs. continue

Body:
In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?

Example:

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}


问:
CUDA 9 unsupported error with Visual Studio 2017
I've recently updated my VS 2017 and now I cannot even build a default CUDA project (the one with the vector addition).

I suspect that this is due to the following error:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   C1189   #error:  -- unsupported Microsoft Visual Studio version!
 Only the versions 2012, 2013, 2015 and 2017 are supported! ver2
c:\program files\nvidia gpu computing
toolkit\cuda\v9.0\include\crt\host_config.h 133
</code>```

The other errors are irrelevant and will disappear once I fix this one. Note, that I am able to build and run simpleCUFFT from CUDA samples.

Before the update I was able to build the default CUDA project but I was not able to build the CUDA Sample project. I've updated my VS2017 using VS installer and installed CUDA SDK 10.0.15063.0. Attached is the screenshot with the installed components.

Please let me know if any additional information is required. I am aware of the following topic and since I am using the latest CUDA toolkit, I don't need to make changes in host_config.h.

Thanks,
Mikhail

Edit:
My VS version (as displayed in VS installer) is 15.5.0
My nvcc version is release 9.0, V9.0.176

Edit2: I've tryied to change host_config.h line 133 to:

```<code>  #if _MSC_VER < 1600 || _MSC_VER > 1912
</code>```

This error does not show up anymore, however, a bunch of errors "expression must have a constant value" show up in the file type_trails. I have no clue how to fix it.

答:
After some painful time, I was able to solve the problem. Here is the answer for those who have a similar problem:

1) Make sure that you have VC++ 2015.3 v140 toolset (can be installed either from web or Visual Studio installer)

2) In the project properties (general) -> Platform toolset choose Visual Studio 2015 (v140).

Edit (5/21/2018): I've just updated Visual studio 2017 to the latest version 15.7.1. From now on, I can choose VS 2017 v141 toolset and it works fine.

Body:
I've recently updated my VS 2017 and now I cannot even build a default CUDA project (the one with the vector addition).

I suspect that this is due to the following error:

Severity    Code    Description Project File    Line    Suppression State
Error   C1189   #error:  -- unsupported Microsoft Visual Studio version!
 Only the versions 2012, 2013, 2015 and 2017 are supported! ver2
c:\program files\nvidia gpu computing
toolkit\cuda\v9.0\include\crt\host_config.h 133

The other errors are irrelevant and will disappear once I fix this one. Note, that I am able to build and run simpleCUFFT from CUDA samples.

Before the update I was able to build the default CUDA project but I was not able to build the CUDA Sample project. I've updated my VS2017 using VS installer and installed CUDA SDK 10.0.15063.0. Attached is the screenshot with the installed components.

Please let me know if any additional information is required. I am aware of the following topic and since I am using the latest CUDA toolkit, I don't need to make changes in host_config.h.

Thanks,
Mikhail

Edit:
My VS version (as displayed in VS installer) is 15.5.0
My nvcc version is release 9.0, V9.0.176

Edit2: I've tryied to change host_config.h line 133 to:

  #if _MSC_VER < 1600 || _MSC_VER > 1912

This error does not show up anymore, however, a bunch of errors "expression must have a constant value" show up in the file type_trails. I have no clue how to fix it.


问:
angular is not defined, why?
The following angular piece doesn't work, it seems that in the immediately invoked function the code breaks where I create my module because angular syntax is not recognised.

```<code><!DOCTYPE html>
<html ng-app="MyModule">
 <head>
    <script data-require="angular.js@*" data-semver="4.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2.min.js"></script>

  </head>
  <body ng-controller="MyCtrller">
    <h1>Hello!</h1>
    {{ cousin }}
  </body>

</html>

<script type="text/javascript">
(function() {
    var app = angular.module("MyModule", []);
    var MyCtrller = function($scope)          ///typo here in "MyCtrller"
    {
          $scope.cousin = "Karen";
    }
    app.controller("MyCtrller", ["$scope", MyCtrller]);
}());
</script>
</code>```

I expect the result to be Karen.

Instead, I see {{ cousin }}

The error I get in console is:

Uncaught ReferenceError: angular is not defined

on the line where I create my module:

var app = angular.module("MyModule", []);

答:
Your problem is that you are including the v2.0 version of angular (a.k.a. Angular), instead of 1.x version (a.k.a. AngularJS) while using the latter syntax. :)
Simply change your script to use the correct version and you should be good to go.

https://angularjs.org/

Title: angular is not defined, why?

Body:
The following angular piece doesn't work, it seems that in the immediately invoked function the code breaks where I create my module because angular syntax is not recognised.

<!DOCTYPE html>

Hello!

    {{ cousin }}

I expect the result to be Karen.

Instead, I see {{ cousin }}

The error I get in console is:

Uncaught ReferenceError: angular is not defined

on the line where I create my module:

var app = angular.module("MyModule", []);


问:
Akamai CDN - Whitelist service by Request header or User agent
We are using Akamai CDN as our load balancer and it also servers as a gatekeeper for requests.

We usually consume 3rd party services and in those cases whitelist their IP to be accessed in our servers.  The service we are currently using cannot share IP since it is on cloud and keeps changing. They can either provide host name or Custom request header or a user agent.

I tried adding host entry but that did not work. Any idea how to add custom request header or user agent?

答:
Depending on the product you're using to deliver with Akamai, the solution is to add a "Modify Outgoing Request Header" behavior.

This is what the "Add Behavior" tool looks like when you filter behaviors on "header".

By default, this allows you to specify a User-Agent header to go to your origin with the request. You can also specify a custom header name and value using that Behavior.

If you make it part of your Default Rule, then every single request that goes through that property will have the custom header.


问:
How to scale a Sprite2D in Urho3D without rescaling the entire node?
I want to scale a 2D sprite to be as large as the collision box for the node.

I have only managed to do it using Node::SetScale and some manual scaling calculation, but I would rather not do it with this method as it is convoluted, since I have to account for that scaling factor for the physical body as well.

However, I could not find a SetScale method for the StaticSprite2D class.

The key code part is:

```<code>#if 0
        // Sprite and collision have the same size,
        // like I want it, but I feel this is very convoluted.
        auto rect = boxSprite->GetRectangle();
        auto scaleX = PIXEL_SIZE * rect.Width();
        auto scaleY = PIXEL_SIZE * rect.Height();
        node->SetScale(Vector3(groundWidth / scaleX, groundHeight / scaleY, 0.0f));
        shape->SetSize(Vector2(scaleX, scaleY));
#else
        // Collision shape is correct, but the sprite is smaller
        // so not what I want.
        shape->SetSize(Vector2(groundWidth, groundHeight));
#endif
</code>```

Full runnable code below, tested with the following boilerplate: https://github.com/cirosantilli/Urho3D-cheat/blob/8c785b38481aa5af48837c5bc3706e46f704ef37/scale_sprite.cpp and Urho3D @ 5e8a275:

```<code>#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/Object.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Engine/EngineDefs.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Urho2D/CollisionBox2D.h>
#include <Urho3D/Urho2D/CollisionCircle2D.h>
#include <Urho3D/Urho2D/Drawable2D.h>
#include <Urho3D/Urho2D/PhysicsWorld2D.h>
#include <Urho3D/Urho2D/RigidBody2D.h>
#include <Urho3D/Urho2D/Sprite2D.h>
#include <Urho3D/Urho2D/StaticSprite2D.h>

using namespace Urho3D;

class Main : public Application {
    URHO3D_OBJECT(Main, Application);
public:
    Main(Context* context) : Application(context) {
    }
    virtual void Setup() override {
        engineParameters_[EP_FULL_SCREEN] = false;
    }
    void Start() {
        SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Main, HandlePostRenderUpdate));
        this->scene_ = new Scene(this->context_);
        scene_->CreateComponent<Octree>();
        scene_->CreateComponent<DebugRenderer>();
        scene_->CreateComponent<PhysicsWorld2D>();
        auto physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
        auto cameraNode_ = scene_->CreateChild("camera");
        cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -1.0f));
        auto camera = cameraNode_->CreateComponent<Camera>();
        camera->SetOrthographic(true);
        camera->SetOrthoSize(4.0);
        auto graphics = GetSubsystem<Graphics>();
        auto renderer = GetSubsystem<Renderer>();
        SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
        renderer->SetViewport(0, viewport);
        auto cache = GetSubsystem<ResourceCache>();
        auto boxSprite = cache->GetResource<Sprite2D>("Urho2D/Box.png");

        auto groundWidth = 2.0;
        auto groundHeight = 2.0;
        auto node = this->scene_->CreateChild("ground");
        node->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
        node->CreateComponent<RigidBody2D>();
        auto shape = node->CreateComponent<CollisionBox2D>();
#if 0
        // Sprite and collision have the same size,
        // like I want it, but I feel this is very convoluted.
        auto rect = boxSprite->GetRectangle();
        auto scaleX = PIXEL_SIZE * rect.Width();
        auto scaleY = PIXEL_SIZE * rect.Height();
        node->SetScale(Vector3(groundWidth / scaleX, groundHeight / scaleY, 0.0f));
        shape->SetSize(Vector2(scaleX, scaleY));
#else
        // Collision shape is correct, but the sprite is smaller
        // so not what I want.
        shape->SetSize(Vector2(groundWidth, groundHeight));
#endif
        auto staticSprite = node->CreateComponent<StaticSprite2D>();
        staticSprite->SetSprite(boxSprite);
    }
    void Stop() {}
private:
    SharedPtr<Scene> scene_;
    void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) {
        auto physicsWorld = this->scene_->GetComponent<PhysicsWorld2D>();
        physicsWorld->DrawDebugGeometry();
    }
};

URHO3D_DEFINE_APPLICATION_MAIN(Main);
</code>```

Interestingly, there is a SetScale for the Sprite class, which as far as I've seen in the examples, is used for the UI in 3D scenes.

Superset: arbitrary shaders in 2D:

https://discourse.urho3d.io/t/2d-lights-shaders-glow-shadows/251

https://github.com/urho3d/Urho3D/issues/462

Also asked at: https://discourse.urho3d.io/t/how-to-scale-a-sprite2d-in-urho3d-without-rescaling-the-entire-node/3785/1

答:
StaticSprite2D::SetDrawRect

This is the method I needed, it sets how big the sprite will be in world coordinates.

The rectangle it takes is centered on the origin, we just give the object lengths and ignore the position.

The full updated working code is present at: https://github.com/cirosantilli/Urho3D-cheat/blob/1905d1f4824c6b88aca867c5be8ccb5dfae957f3/scale_sprite.cpp

The key lines are:

```<code>void CreateBox(float x, float y, float width, float height) {
    auto node = this->scene->CreateChild("Box");
    node->SetPosition(Vector3(x, y, 0.0f));
    node->SetRotation(Quaternion(0.0f, 0.0f, 30.0f));
    auto box = node->CreateComponent<CollisionBox2D>();
    box->SetSize(Vector2(width, height));
    box->SetRestitution(0.8);
    box->SetFriction(0.5f);
    box->SetDensity(1.0f);
    auto body = node->CreateComponent<RigidBody2D>();
    body->SetBodyType(BT_DYNAMIC);
    auto staticSprite = node->CreateComponent<StaticSprite2D>();
    staticSprite->SetSprite(this->boxSprite);
    staticSprite->SetDrawRect(Rect(
        width / 2.0f,
        -height / 2.0f,
        -width / 2.0f,
        height / 2.0f
    ));
    staticSprite->SetUseDrawRect(true);
}
</code>```

Learned from: https://discourse.urho3d.io/t/how-to-scale-a-sprite2d-in-urho3d-without-rescaling-the-entire-node/3785/2

Body:
I want to scale a 2D sprite to be as large as the collision box for the node.

I have only managed to do it using Node::SetScale and some manual scaling calculation, but I would rather not do it with this method as it is convoluted, since I have to account for that scaling factor for the physical body as well.

However, I could not find a SetScale method for the StaticSprite2D class.

The key code part is:

#if 0
        // Sprite and collision have the same size,
        // like I want it, but I feel this is very convoluted.
        auto rect = boxSprite->GetRectangle();
        auto scaleX = PIXEL_SIZE * rect.Width();
        auto scaleY = PIXEL_SIZE * rect.Height();
        node->SetScale(Vector3(groundWidth / scaleX, groundHeight / scaleY, 0.0f));
        shape->SetSize(Vector2(scaleX, scaleY));
#else
        // Collision shape is correct, but the sprite is smaller
        // so not what I want.
        shape->SetSize(Vector2(groundWidth, groundHeight));
#endif

Full runnable code below, tested with the following boilerplate: https://github.com/cirosantilli/Urho3D-cheat/blob/8c785b38481aa5af48837c5bc3706e46f704ef37/scale_sprite.cpp and Urho3D @ 5e8a275:

#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/Object.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Engine/EngineDefs.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Urho2D/CollisionBox2D.h>
#include <Urho3D/Urho2D/CollisionCircle2D.h>
#include <Urho3D/Urho2D/Drawable2D.h>
#include <Urho3D/Urho2D/PhysicsWorld2D.h>
#include <Urho3D/Urho2D/RigidBody2D.h>
#include <Urho3D/Urho2D/Sprite2D.h>
#include <Urho3D/Urho2D/StaticSprite2D.h>

using namespace Urho3D;

class Main : public Application {
    URHO3D_OBJECT(Main, Application);
public:
    Main(Context* context) : Application(context) {
    }
    virtual void Setup() override {
        engineParameters_[EP_FULL_SCREEN] = false;
    }
    void Start() {
        SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Main, HandlePostRenderUpdate));
        this->scene_ = new Scene(this->context_);
        scene_->CreateComponent<Octree>();
        scene_->CreateComponent<DebugRenderer>();
        scene_->CreateComponent<PhysicsWorld2D>();
        auto physicsWorld = scene_->GetComponent<PhysicsWorld2D>();
        auto cameraNode_ = scene_->CreateChild("camera");
        cameraNode_->SetPosition(Vector3(0.0f, 0.0f, -1.0f));
        auto camera = cameraNode_->CreateComponent<Camera>();
        camera->SetOrthographic(true);
        camera->SetOrthoSize(4.0);
        auto graphics = GetSubsystem<Graphics>();
        auto renderer = GetSubsystem<Renderer>();
        SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
        renderer->SetViewport(0, viewport);
        auto cache = GetSubsystem<ResourceCache>();
        auto boxSprite = cache->GetResource<Sprite2D>("Urho2D/Box.png");

        auto groundWidth = 2.0;
        auto groundHeight = 2.0;
        auto node = this->scene_->CreateChild("ground");
        node->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
        node->CreateComponent<RigidBody2D>();
        auto shape = node->CreateComponent<CollisionBox2D>();
#if 0
        // Sprite and collision have the same size,
        // like I want it, but I feel this is very convoluted.
        auto rect = boxSprite->GetRectangle();
        auto scaleX = PIXEL_SIZE * rect.Width();
        auto scaleY = PIXEL_SIZE * rect.Height();
        node->SetScale(Vector3(groundWidth / scaleX, groundHeight / scaleY, 0.0f));
        shape->SetSize(Vector2(scaleX, scaleY));
#else
        // Collision shape is correct, but the sprite is smaller
        // so not what I want.
        shape->SetSize(Vector2(groundWidth, groundHeight));
#endif
        auto staticSprite = node->CreateComponent<StaticSprite2D>();
        staticSprite->SetSprite(boxSprite);
    }
    void Stop() {}
private:
    SharedPtr<Scene> scene_;
    void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) {
        auto physicsWorld = this->scene_->GetComponent<PhysicsWorld2D>();
        physicsWorld->DrawDebugGeometry();
    }
};

URHO3D_DEFINE_APPLICATION_MAIN(Main);

Interestingly, there is a SetScale for the Sprite class, which as far as I've seen in the examples, is used for the UI in 3D scenes.

Superset: arbitrary shaders in 2D:

https://discourse.urho3d.io/t/2d-lights-shaders-glow-shadows/251

https://github.com/urho3d/Urho3D/issues/462

Also asked at: https://discourse.urho3d.io/t/how-to-scale-a-sprite2d-in-urho3d-without-rescaling-the-entire-node/3785/1

Body:
StaticSprite2D::SetDrawRect

This is the method I needed, it sets how big the sprite will be in world coordinates.

The rectangle it takes is centered on the origin, we just give the object lengths and ignore the position.

The full updated working code is present at: https://github.com/cirosantilli/Urho3D-cheat/blob/1905d1f4824c6b88aca867c5be8ccb5dfae957f3/scale_sprite.cpp

The key lines are:

void CreateBox(float x, float y, float width, float height) {
    auto node = this->scene->CreateChild("Box");
    node->SetPosition(Vector3(x, y, 0.0f));
    node->SetRotation(Quaternion(0.0f, 0.0f, 30.0f));
    auto box = node->CreateComponent<CollisionBox2D>();
    box->SetSize(Vector2(width, height));
    box->SetRestitution(0.8);
    box->SetFriction(0.5f);
    box->SetDensity(1.0f);
    auto body = node->CreateComponent<RigidBody2D>();
    body->SetBodyType(BT_DYNAMIC);
    auto staticSprite = node->CreateComponent<StaticSprite2D>();
    staticSprite->SetSprite(this->boxSprite);
    staticSprite->SetDrawRect(Rect(
        width / 2.0f,
        -height / 2.0f,
        -width / 2.0f,
        height / 2.0f
    ));
    staticSprite->SetUseDrawRect(true);
}

Learned from: https://discourse.urho3d.io/t/how-to-scale-a-sprite2d-in-urho3d-without-rescaling-the-entire-node/3785/2


问:
Django Image Grid Gallery
I am trying to setup a grid gallery in my Django website similar to pinterest.com.

I have the following HTML code:

```<code><div class="row text-center text-lg-left">
    <div class="col-lg-3 col-md-4 col-xs-6">
      <a href="#" class="d-block mb-4 h-100">
        {% for img in imgs %}
        <img src="/static/img/{{ img }}" class="img-thumbnail" alt="">
        {% endfor %}
      </a>
    </div>
  </div>
</code>```

Here is my views.py

```<code>def gallery(request):
    path = "C:/Users/fela/Pictures/"
    img_list = os.listdir(path)
    return render(request, 'gallery.html', {'imgs': img_list})
</code>```

The above code shows the result line by line instead of next to each other. It displays one result (image) per line (https://image.ibb.co/bVAE9b/result_2.png).

The expected result should be similar to pinterest, it should be next to each other to fill up the screen.

I have tried using bootstrap 4 and bootstrap 3 with same results.

答:
It should be something like this

```<code><div class="row">
    {% for img in imgs %}
        <div class="col-lg-3 col-md-4 col-xs-6">
          <a href="#" class="d-block mb-4 h-100">
            <img src="/static/img/{{ img }}" class="img-thumbnail" alt="">
          </a>
        </div>
    {% endfor %}
  </div>
</code>```

You had one div with col-*, but each image should have its own.

Title: Django Image Grid Gallery

Body:
I am trying to setup a grid gallery in my Django website similar to pinterest.com.

I have the following HTML code:

        {% for img in imgs %}

        {% endfor %}

Here is my views.py

def gallery(request):
    path = "C:/Users/fela/Pictures/"
    img_list = os.listdir(path)
    return render(request, 'gallery.html', {'imgs': img_list})

The above code shows the result line by line instead of next to each other. It displays one result (image) per line (https://image.ibb.co/bVAE9b/result_2.png).

The expected result should be similar to pinterest, it should be next to each other to fill up the screen.

I have tried using bootstrap 4 and bootstrap 3 with same results.

Body:
It should be something like this

<div class="row">
    {% for img in imgs %}
        <div class="col-lg-3 col-md-4 col-xs-6">
          <a href="#" class="d-block mb-4 h-100">
            <img src="/static/img/{{ img }}" class="img-thumbnail" alt="">
          </a>
        </div>
    {% endfor %}
  </div>

You had one div with col-*, but each image should have its own.


问:
How to keep the reference of the singleton class object in the companion object, Kotlin
The code that I want to convert is the following;

```<code>public class AndroidLauncher extends AndroidApplication {

   public static AndroidLauncher androidLauncher;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       androidLauncher = this;
   }
}
</code>```

What android studio generated code is this;

```<code>class AndroidLauncher : AndroidApplication() {
   protected override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       androidLauncher = this
   }

   companion object {

       var androidLauncher: AndroidLauncher
   }
}
</code>```

This code gives me error, which is;

Property must be initialized or be abstract

I'm developing a game with libgdx, so I'll use this approach to use the Game object from anywhere I want. It's a singleton class so it won't leak any memory.

答:
Use lateinit to indicate that the field will be initialized later.

```<code>   companion object {
       lateinit var androidLauncher: AndroidLauncher
   }
</code>```

Body:
The code that I want to convert is the following;

public class AndroidLauncher extends AndroidApplication {

   public static AndroidLauncher androidLauncher;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       androidLauncher = this;
   }
}

What android studio generated code is this;

class AndroidLauncher : AndroidApplication() {
   protected override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       androidLauncher = this
   }

   companion object {

       var androidLauncher: AndroidLauncher
   }
}

This code gives me error, which is;

Property must be initialized or be abstract

I'm developing a game with libgdx, so I'll use this approach to use the Game object from anywhere I want. It's a singleton class so it won't leak any memory.

Body:
Use lateinit to indicate that the field will be initialized later.

   companion object {
       lateinit var androidLauncher: AndroidLauncher
   }


问:
How to read arrays to form a matrix from file using numpy
I have a file with data as:
2 arrays in each row. Total= 10,000 rows.

```<code>[1,2,3,4,5][2,4,6,8,10]
[3,6,9,12,24][6,12,18,24,48]
....]
</code>```

I am planning to give this input to Linear Regression in the fit command.
I am having issue how to construct a matrix with entries.

I am looking at constructing Array (2 by x) like:

```<code>x=[
    [1,2,3,4,5]
    [3,6,9,12,24]
    ....]

y=
  [[2,4,6,8,10]
   [6,12,18,24,48]
    ....]
</code>```

so that I can give to the fit command as input.

I see numpy.fromfile is used to get the binary data.
can I use it for lists?

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fromfile.html

答:
Solution using pandas</p>

```<code>import pandas as pd

df = pd.read_csv('input.txt', delimiter="\]\[", header=None, engine='python')
df[0] = (df[0] + ']')
df[1] = ('[' + df[1])
x = df[0].tolist()
y = df[1].tolist()
</code>```

Body:
I have a file with data as:
2 arrays in each row. Total= 10,000 rows.

[1,2,3,4,5][2,4,6,8,10]
[3,6,9,12,24][6,12,18,24,48]
....]

I am planning to give this input to Linear Regression in the fit command.
I am having issue how to construct a matrix with entries.

I am looking at constructing Array (2 by x) like:

x=[
    [1,2,3,4,5]
    [3,6,9,12,24]
    ....]

y=
  [[2,4,6,8,10]
   [6,12,18,24,48]
    ....]

so that I can give to the fit command as input.

I see numpy.fromfile is used to get the binary data.
can I use it for lists?

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fromfile.html

Body:
Solution using pandas

import pandas as pd

df = pd.read_csv('input.txt', delimiter="\]\[", header=None, engine='python')
df[0] = (df[0] + ']')
df[1] = ('[' + df[1])
x = df[0].tolist()
y = df[1].tolist()


问:
Drawing a circle on an image
I have a program for image segmentation in WinForms Application C#, and I have an image loaded in a pictureBox. I need to draw a small circle(or an ellipse, it does not matter) on that image (inside a region of interest, and allowing it to grow outwards until it reaches the desired boundary).

And the question is how can I draw that circle anywhere on that image? (and if it`s possible to draw that circle in a different color, red for example)

Thank you.

答:
reference: Answer by @Albin at draw-an-arrow-on-a-picturebox

```<code>public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private Dictionary<Point, Point> Circles = new Dictionary<Point, Point>();
    public Form1()
    {
        InitializeComponent();

        //
        // pictureBox1
        //
        this.pictureBox1.Name = "pictureBox1";
        this.pictureBox1.Size = new System.Drawing.Size(231, 235);
        this.pictureBox1.TabIndex = 0;
        this.pictureBox1.TabStop = false;
        this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
        this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
        this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);
        this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
        this.Controls.Add(this.pictureBox1);
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Pen p = new Pen(Color.Red);
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawEllipse(p, new Rectangle(mouseDownPosition, new Size(mouseMovePosition.X - mouseDownPosition.X, mouseMovePosition.Y - mouseDownPosition.Y)));
            foreach (var circle in Circles)
            {
                g.DrawEllipse(p, new Rectangle(circle.Key, new Size(circle.Value.X - circle.Key.X, circle.Value.Y - circle.Key.Y)));
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        pictureBox1.Cursor = Cursors.Cross;
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        pictureBox1.Cursor = Cursors.Default;
        if (isMoving)
        {
            Circles.Add(mouseDownPosition, mouseMovePosition);
        }
        isMoving = false;
    }
}
</code>```

Title: Drawing a circle on an image

Body:
reference: Answer by @Albin at draw-an-arrow-on-a-picturebox

public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private Dictionary<Point, Point> Circles = new Dictionary<Point, Point>();
    public Form1()
    {
        InitializeComponent();

        //
        // pictureBox1
        //
        this.pictureBox1.Name = "pictureBox1";
        this.pictureBox1.Size = new System.Drawing.Size(231, 235);
        this.pictureBox1.TabIndex = 0;
        this.pictureBox1.TabStop = false;
        this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
        this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
        this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);
        this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
        this.Controls.Add(this.pictureBox1);
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Pen p = new Pen(Color.Red);
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawEllipse(p, new Rectangle(mouseDownPosition, new Size(mouseMovePosition.X - mouseDownPosition.X, mouseMovePosition.Y - mouseDownPosition.Y)));
            foreach (var circle in Circles)
            {
                g.DrawEllipse(p, new Rectangle(circle.Key, new Size(circle.Value.X - circle.Key.X, circle.Value.Y - circle.Key.Y)));
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        pictureBox1.Cursor = Cursors.Cross;
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        pictureBox1.Cursor = Cursors.Default;
        if (isMoving)
        {
            Circles.Add(mouseDownPosition, mouseMovePosition);
        }
        isMoving = false;
    }
}


问:
Android gmail can't scale background image correctly

```

See code above.  On android, the image is not scaled correctly. See image attached.  Is there anyone who know how to fix it? Thanks!

答:
It is caused by gmail auto-sizing and could be fixed by applying min-width -- style="min-width:597px;"

Ideas from - https://www.campaignmonitor.com/forums/topic/7733/android-gmail-image-resizing-issues/


问:
SQL error when trying to update record in a database using PDO
I am getting the following error when trying to update a record in an SQL database...

Book not updated: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Adobe AIR (Adobe Integrated Runtime) with Ajax: Visual QuickPro Guide, bookYear ' at line 1.

Here is my code for the updateBooks.php file

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>updateBook.php - updating a book record to a database using PDO</title>
</head>
<body>

<?php
// Retrieve variables
$bookISBN = filter_has_var(INPUT_GET, 'bookISBN') ? $_GET['bookISBN'] : null;
$bookTitle = filter_has_var(INPUT_GET, 'bookTitle') ? $_GET['bookTitle'] : null;
$bookYear = filter_has_var(INPUT_GET, 'bookYear') ? $_GET['bookYear'] : null;
$catID = filter_has_var(INPUT_GET, 'catID') ? $_GET['catID'] : null;
$bookPrice = filter_has_var(INPUT_GET, 'bookPrice') ? $_GET['bookPrice'] : null;

$errors = false;

if (empty($bookISBN)) {
    echo "<p>You need to have selected a book.</p>\n";
    $errors = true;
}
if (empty($bookTitle)) {
    echo "<p>You need to choose a title.</p>\n";
    $errors = true;
}
if (empty($bookYear)) {
    echo "<p>You need to choose a year.</p>\n";
    $errors = true;
}
if (empty($catID)) {
    echo "<p>You need to choose a category.</p>\n";
    $errors = true;
}
if (empty($bookPrice)) {
    echo "<p>You need to choose a price.</p>\n";
    $errors = true;
}
if ($errors === true) {
    echo "<p>Please try <a href='chooseBookList.php'>again</a>.</p>\n";
}
else {
    try {
        //connects to database
        require_once("functions.php");
        $dbConn = getConnection();
        $bookPrice = $dbConn->quote($bookPrice);

        $updateSQL = "UPDATE nbc_books SET bookTitle = $ $bookTitle, bookYear = $bookYear, catID = $catID, bookPrice = $bookPrice WHERE bookISBN = $bookISBN";
        $dbConn->exec($updateSQL);
        echo "<p>Book updated</p>\n";
    } catch (Exception $e) {
        echo "<p>Book not updated: " . $e->getMessage() . "</p>\n";
    }
}
?>
</body>
</html>
</code>```

Here is my code for the bookQuery.php file

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>bookQuery.php - retrieving data from a database using PDO</title>
</head>
<body>
<h1>All Books</h1>
<?php
try {
    require_once("functions.php");
    $dbConn = getConnection();

    $sqlQuery = "SELECT bookTitle, catDesc, pubName
                 FROM nbc_books
                 INNER JOIN nbc_category
                 ON nbc_category.catID = nbc_books.catID
                 INNER JOIN nbc_publisher
                 ON nbc_publisher.pubID = nbc_books.pubID
                 ORDER BY bookTitle";
    $queryResult = $dbConn->query($sqlQuery);

    while ($rowObj = $queryResult->fetchObject()) {
        echo "<div class='book'>\n
                   <span class='bookTitle'>{$rowObj->bookTitle}</span>\n
                   <span class='bookYear'>{$rowObj->bookYear}</span>\n
                   <span class='catID'>{$rowObj->catID}</span>\n
                   <span class='bookPrice'>{$rowObj->bookPrice}</span>\n
              </div>\n";
    }
}
catch (Exception $e){
    echo "<p>Query failed: ".$e->getMessage()."</p>\n";
}
?>

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

Here is the code for the form aswell

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>editBookForm.php- script to display an edit form for the chosen book</title>
</head>
<body>
<?php
$bookISBN = filter_has_var(INPUT_GET, 'bookISBN') ? $_GET['bookISBN'] : null;

if (empty($bookISBN)) {
    echo "<p>Please <a href='chooseBookList.php'>choose</a> a book.</p>\n";
}
else {
    try {
        require_once("functions.php");
        $dbConn = getConnection();

        $sqlQuery = "SELECT bookISBN, bookTitle, bookYear,nbc_books.pubID, nbc_books.catID, bookPrice
                 FROM nbc_books
                 INNER JOIN nbc_category
                 ON nbc_category.catID = nbc_books.catID
                 INNER JOIN nbc_publisher
                 ON nbc_publisher.pubID = nbc_books.pubID
                 WHERE bookISBN = $bookISBN";
        $queryResult = $dbConn->query($sqlQuery);

        $rowObj = $queryResult->fetchObject();

        echo "
        <h1>Update '{$rowObj->bookTitle}'</h1>
        <form id='UpdateBook' action='updateBook.php' method='get'>
            <p>Book ISBN <input type='text' name='bookISBN' value='$bookISBN' readonly /></p>
            <p>Book Title <input type='text' name='bookTitle' size='50' value='{$rowObj->bookTitle}' /></p>
            <p>Book Year <input type='text' name='bookYear' size='10' value='{$rowObj->bookYear}' /></p>
            <p>Book Category <input type='text' name='catID' value='{$rowObj->catID}' /></p>
            <p>Book Price <input type='text' name='bookPrice' size='10' value='{$rowObj->bookPrice}' /></p>
            <br />

            <p><input type='submit' name='submit' value='Update Book'></p>
        </form>
        ";
    }
    catch (Exception $e){
        echo "<p>Book details not found: ".$e->getMessage()."</p>\n";
    }
}
?>
</body>
</html>
</code>```

答:
Your query syntax is invalid:

```<code>$updateSQL = "UPDATE nbc_books SET bookTitle = $ $bookTitle, bookYear = $bookYear, catID = $catID, bookPrice = $bookPrice WHERE bookISBN = $bookISBN";
</code>```

esp. this part: $ $bookTitle. Remove redundant $.

Body:
I am getting the following error when trying to update a record in an SQL database...

Book not updated: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Adobe AIR (Adobe Integrated Runtime) with Ajax: Visual QuickPro Guide, bookYear ' at line 1.

Here is my code for the updateBooks.php file

<!doctype html>

    <meta charset="UTF-8" />
    <title>updateBook.php - updating a book record to a database using PDO</title>

<?php
// Retrieve variables
$bookISBN = filter_has_var(INPUT_GET, 'bookISBN') ? $_GET['bookISBN'] : null;
$bookTitle = filter_has_var(INPUT_GET, 'bookTitle') ? $_GET['bookTitle'] : null;
$bookYear = filter_has_var(INPUT_GET, 'bookYear') ? $_GET['bookYear'] : null;
$catID = filter_has_var(INPUT_GET, 'catID') ? $_GET['catID'] : null;
$bookPrice = filter_has_var(INPUT_GET, 'bookPrice') ? $_GET['bookPrice'] : null;

$errors = false;

if (empty($bookISBN)) {
    echo "
You need to have selected a book.
\n";
    $errors = true;
}
if (empty($bookTitle)) {
    echo "
You need to choose a title.
\n";
    $errors = true;
}
if (empty($bookYear)) {
    echo "
You need to choose a year.
\n";
    $errors = true;
}
if (empty($catID)) {
    echo "
You need to choose a category.
\n";
    $errors = true;
}
if (empty($bookPrice)) {
    echo "
You need to choose a price.
\n";
    $errors = true;
}
if ($errors === true) {
    echo "
Please try again.
\n";
}
else {
    try {
        //connects to database
        require_once("functions.php");
        $dbConn = getConnection();
        $bookPrice = $dbConn->quote($bookPrice);

        $updateSQL = "UPDATE nbc_books SET bookTitle = $ $bookTitle, bookYear = $bookYear, catID = $catID, bookPrice = $bookPrice WHERE bookISBN = $bookISBN";
        $dbConn->exec($updateSQL);
        echo "
Book updated
\n";
    } catch (Exception $e) {
        echo "
Book not updated: " . $e->getMessage() . "
\n";
    }
}
?>

Here is my code for the bookQuery.php file

<!doctype html>

    <meta charset="UTF-8" />
    <title>bookQuery.php - retrieving data from a database using PDO</title>

All Books

<?php
try {
    require_once("functions.php");
    $dbConn = getConnection();

    $sqlQuery = "SELECT bookTitle, catDesc, pubName
                 FROM nbc_books
                 INNER JOIN nbc_category
                 ON nbc_category.catID = nbc_books.catID
                 INNER JOIN nbc_publisher
                 ON nbc_publisher.pubID = nbc_books.pubID
                 ORDER BY bookTitle";
    $queryResult = $dbConn->query($sqlQuery);

    while ($rowObj = $queryResult->fetchObject()) {
        echo "
\n
                   {$rowObj->bookTitle}\n
                   {$rowObj->bookYear}\n
                   {$rowObj->catID}\n
                   {$rowObj->bookPrice}\n

\n";
    }
}
catch (Exception $e){
    echo "
Query failed: ".$e->getMessage()."
\n";
}
?>

Here is the code for the form aswell

<!doctype html>

    <meta charset="UTF-8" />
    <title>editBookForm.php- script to display an edit form for the chosen book</title>

<?php
$bookISBN = filter_has_var(INPUT_GET, 'bookISBN') ? $_GET['bookISBN'] : null;

if (empty($bookISBN)) {
    echo "
Please choose a book.
\n";
}
else {
    try {
        require_once("functions.php");
        $dbConn = getConnection();

        $sqlQuery = "SELECT bookISBN, bookTitle, bookYear,nbc_books.pubID, nbc_books.catID, bookPrice
                 FROM nbc_books
                 INNER JOIN nbc_category
                 ON nbc_category.catID = nbc_books.catID
                 INNER JOIN nbc_publisher
                 ON nbc_publisher.pubID = nbc_books.pubID
                 WHERE bookISBN = $bookISBN";
        $queryResult = $dbConn->query($sqlQuery);

        $rowObj = $queryResult->fetchObject();

        echo "

Update '{$rowObj->bookTitle}'

        <form id='UpdateBook' action='updateBook.php' method='get'>

Book ISBN <input type='text' name='bookISBN' value='$bookISBN' readonly />

Book Title <input type='text' name='bookTitle' size='50' value='{$rowObj->bookTitle}' />

Book Year <input type='text' name='bookYear' size='10' value='{$rowObj->bookYear}' />

Book Category <input type='text' name='catID' value='{$rowObj->catID}' />

Book Price <input type='text' name='bookPrice' size='10' value='{$rowObj->bookPrice}' />

<input type='submit' name='submit' value='Update Book'>

        </form>
        ";
    }
    catch (Exception $e){
        echo "
Book details not found: ".$e->getMessage()."
\n";
    }
}
?>

Body:
Your query syntax is invalid:

$updateSQL = "UPDATE nbc_books SET bookTitle = $ $bookTitle, bookYear = $bookYear, catID = $catID, bookPrice = $bookPrice WHERE bookISBN = $bookISBN";

esp. this part: $ $bookTitle. Remove redundant $.


问:
Could we use AWS Glue just copy a file from one S3 folder to another S3 folder?
I need to copy a zipped file from one AWS S3 folder to another and would like to make that a scheduled AWS Glue job. I cannot find an example for such a simple task. Please help if you know the answer. May be the answer is in AWS Lambda, or other AWS tools.

Thank you very much!

答:
I think you can do it with Glue, but wouldn't it be easier to use the CLI?

You can do the following:

aws s3 sync s3://bucket_1 s3://bucket_2


问:
Webpack doesn't generate bundle.js
my webpack doesn't generate file though no errors shown. PLS help :D
i'm new to all this so dont be harsh pls :D

code in webpack.config.js

```<code>module.exports = {
    entry : ['./app/index.js'],
    output : {
        path : '/build',
        filename: 'bundle.js'
    }
}
</code>```

using npm run build, no errors returned.

package.json

```<code>{
  "name": "es6",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "webpack": "^3.10.0"
  },
  "description": ""
}
</code>```

答:
After making a fresh directory, copying in your code as is, I get the following:

```<code>Error: EACCES: permission denied, mkdir '/build'
    at Error (native)
</code>```

It's trying to access the root level /build directory (which doesn't exist, at least for me).

Tweaking the config a bit more leads to this:

```<code>const path = require('path')
module.exports = {
    entry : ['./app/index.js'],
    output : {
        // Get the path including the current directory node is running in
        path : path.resolve(__dirname, './build'),
        filename: 'bundle.js'
    }
}
</code>```

Which spits out a successful bundle.

There were no errors? Any output at all?

Title: Webpack doesn't generate bundle.js

Body:
my webpack doesn't generate file though no errors shown. PLS help :D
i'm new to all this so dont be harsh pls :D

code in webpack.config.js

module.exports = {
    entry : ['./app/index.js'],
    output : {
        path : '/build',
        filename: 'bundle.js'
    }
}

using npm run build, no errors returned.

package.json

{
  "name": "es6",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "webpack": "^3.10.0"
  },
  "description": ""
}

Body:
After making a fresh directory, copying in your code as is, I get the following:

Error: EACCES: permission denied, mkdir '/build'
    at Error (native)

It's trying to access the root level /build directory (which doesn't exist, at least for me).

Tweaking the config a bit more leads to this:

const path = require('path')
module.exports = {
    entry : ['./app/index.js'],
    output : {
        // Get the path including the current directory node is running in
        path : path.resolve(__dirname, './build'),
        filename: 'bundle.js'
    }
}

Which spits out a successful bundle.

There were no errors? Any output at all?


问:
Efficiently mapping unhashable objects to their index in a list
A Python list

```<code>f = [x0, x1, x2]
</code>```

may be seen as an efficient representation of a mapping from [0, 1, ..., len(f) - 1] to the set of its elements. By "efficient" I mean that f[i] returns the element associated with i in O(1) time.

The inverse mapping may be defined as follows:

```<code>class Inverse:
    def __init__(self, f):
        self.f = f

    def __getitem__(self, x):
        return self.f.index(x)
</code>```

This works, but Inverse(f)[x] takes O(n) time on average.

Alternatively, one may use a dict:

```<code>f_inv = {x: i for i, x in enumerate(f)}
</code>```

This has O(1) average time complexity, but it requires the objects in the list to be hashable.

Is there a way to define an inverse mapping that provides equality-based lookups, in O(1) average time, with unhashable objects?

Edit: sample input and expected output:

```<code>>>> f = [x0, x1, x2]
>>> f_inv = Inverse(f)  # this is to be defined
>>> f_inv[x0]  # in O(1) time
0
>>> f_inv[x2]  # in O(1) time
2
</code>```

答:
You can create an associated dictionary mapping the object ID's back to the list index.

The obvious disadvantage is that you will have to search the index for the identity object, not for on eobject that is merely equal.

On the upside, by creating a custom MutableSequence class using collections.abc, you can, with minimal code, write a class that keeps your data both as a sequence and as the reverse dictionary.

```<code>from collections.abc import MutableSequence
from threading import RLock

class MD(dict):
    # No need for a full MutableMapping subclass, as the use is limited
    def __getitem__(self, key):
        return super().__getitem__(id(key))

class Reversible(MutableSequence):
    def __init__(self, args):
        self.seq = list()
        self.reverse = MD()
        self.lock = RLock()
        for element in args:
            self.append(element)

    def __getitem__(self, index):
        return self.seq[index]

    def __setitem__(self, index, value):
        with self.lock:
            del self.reverse[id(self.seq[index])]
            self.seq[index] = value
            self.reverse[id(value)] = index

    def __delitem__(self, index):
        if index < 0:
            index += len(self)
        with self.lock:
            # Increase all mapped indexes
            for obj in self.seq[index:]:
                self.reverse[obj] -= 1
            del self.reverse[id(self.seq[index])]
            del self.seq[index]

    def __len__(self):
        return len(self.seq)

    def insert(self, index, value):
        if index < 0:
            index += len(self)
        with self.lock:
            # Increase all mapped indexes
            for obj in self.seq[index:]:
                self.reverse[obj] += 1
            self.seq.insert(index, value)
            self.reverse[id(value)] = index
</code>```

And voilá: just use this object in place of your list, and the public attribute "reverse" to get the index of identity objects.
Perceive you can augment the "intelligence" of the "MD" class by trying to use different strategies, like to use the objects themselves, if they are hashable, and only resort to id, or other custom key based on other object attributes, when needed. That way you could mitigate the need for the search to be for the same object.

So, for ordinary operations on the list, this class maintain the reverted dictionary synchronized. There is no support for slice indexing, though.
For more information, check the docs at https://docs.python.org/3/library/collections.abc.html

Body:
A Python list

f = [x0, x1, x2]

may be seen as an efficient representation of a mapping from [0, 1, ..., len(f) - 1] to the set of its elements. By "efficient" I mean that f[i] returns the element associated with i in O(1) time.

The inverse mapping may be defined as follows:

class Inverse:
    def __init__(self, f):
        self.f = f

    def __getitem__(self, x):
        return self.f.index(x)

This works, but Inverse(f)[x] takes O(n) time on average.

Alternatively, one may use a dict:

f_inv = {x: i for i, x in enumerate(f)}

This has O(1) average time complexity, but it requires the objects in the list to be hashable.

Is there a way to define an inverse mapping that provides equality-based lookups, in O(1) average time, with unhashable objects?

Edit: sample input and expected output:

>>> f = [x0, x1, x2]
>>> f_inv = Inverse(f)  # this is to be defined
>>> f_inv[x0]  # in O(1) time
0
>>> f_inv[x2]  # in O(1) time
2

Body:
You can create an associated dictionary mapping the object ID's back to the list index.

The obvious disadvantage is that you will have to search the index for the identity object, not for on eobject that is merely equal.

On the upside, by creating a custom MutableSequence class using collections.abc, you can, with minimal code, write a class that keeps your data both as a sequence and as the reverse dictionary.

from collections.abc import MutableSequence
from threading import RLock

class MD(dict):
    # No need for a full MutableMapping subclass, as the use is limited
    def __getitem__(self, key):
        return super().__getitem__(id(key))

class Reversible(MutableSequence):
    def __init__(self, args):
        self.seq = list()
        self.reverse = MD()
        self.lock = RLock()
        for element in args:
            self.append(element)

    def __getitem__(self, index):
        return self.seq[index]

    def __setitem__(self, index, value):
        with self.lock:
            del self.reverse[id(self.seq[index])]
            self.seq[index] = value
            self.reverse[id(value)] = index

    def __delitem__(self, index):
        if index < 0:
            index += len(self)
        with self.lock:
            # Increase all mapped indexes
            for obj in self.seq[index:]:
                self.reverse[obj] -= 1
            del self.reverse[id(self.seq[index])]
            del self.seq[index]

    def __len__(self):
        return len(self.seq)

    def insert(self, index, value):
        if index < 0:
            index += len(self)
        with self.lock:
            # Increase all mapped indexes
            for obj in self.seq[index:]:
                self.reverse[obj] += 1
            self.seq.insert(index, value)
            self.reverse[id(value)] = index

And voilá: just use this object in place of your list, and the public attribute "reverse" to get the index of identity objects.
Perceive you can augment the "intelligence" of the "MD" class by trying to use different strategies, like to use the objects themselves, if they are hashable, and only resort to id, or other custom key based on other object attributes, when needed. That way you could mitigate the need for the search to be for the same object.

So, for ordinary operations on the list, this class maintain the reverted dictionary synchronized. There is no support for slice indexing, though.
For more information, check the docs at https://docs.python.org/3/library/collections.abc.html


问:
How to properly mock and unit test
I'm basically trying to teach myself how to code and I want to follow good practices. There are obvious benefits to unit testing. There is also much zealotry when it comes to unit-testing and I prefer a much more pragmatic approach to coding and life in general. As context, I'm currently writing my first "real" application which is the ubiquitous blog engine using asp.net MVC. I'm loosely following the MVC Storefront architecture with my own adjustments. As such, this is my first real foray into mocking objects. I'll put the code example at the end of the question.

I'd appreciate any insight or outside resources that I could use to increase my understanding of the fundamentals of testing and mocking. The resources I've found on the net are typically geared towards the "how" of mocking and I need more understanding of the where, why and when of mocking. If this isn't the best place to ask this question, please point me to a better place.

I'm trying to understand the value that I'm getting from the following tests. The UserService is dependent upon the IUserRepository. The value of the service layer is to separate your logic from your data storage, but in this case most of the UserService calls are just passed straight to IUserRepository. The fact that there isn't much actual logic to test could be the source of my concerns as well. I have the following concerns.

It feels like the code is just testing that the mocking framework is working.

In order to mock out the dependencies, it makes my tests have too much knowledge of the IUserRepository implementation. Is this a necessary evil?

What value am I actually gaining from these tests? Is the simplicity of the service under test causing me to doubt the value of these tests.

I'm using NUnit and Rhino.Mocks, but it should be fairly obvious what I'm trying to accomplish.

```<code>    [SetUp]
    public void Setup()
    {
        userRepo = MockRepository.GenerateMock<IUserRepository>();
        userSvc = new UserService(userRepo);
        theUser = new User
        {
            ID = null,
            UserName = "http://joe.myopenid.com",
            EmailAddress = "joe@joeblow.com",
            DisplayName = "Joe Blow",
            Website = "http://joeblow.com"
        };
    }

    [Test]
    public void UserService_can_create_a_new_user()
    {
        // Arrange
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(true);

        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.True,
          "UserService.CreateUser(user) failed when it should have succeeded");
    }

    [Test]
    public void UserService_can_not_create_an_existing_user()
    {
        // Arrange
        userRepo.Stub(repo => repo.IsExistingUser(theUser)).Return(true);
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.False,
            "UserService.CreateUser() allowed multiple copies of same user to be created");
    }
</code>```

答:
If you write your tests before you write your code, you'll gain much more from your unit tests.  One of the reasons that it feels like your tests aren't worth much is that you're not deriving the value of having your tests drive the design.  Writing your tests afterwards is mostly just an exercise in seeing if you can remember everything that can go wrong.  Writing your tests first causes you to think about how you would actually implement the functionality.

These tests aren't all that interesting because the functionality that is being implemented is pretty basic.  The way you are going about mocking seems pretty standard -- mock the things the class under test depends on, not the class under test.  Testability (or good design sense) has already led you to implement interfaces and use dependency injection to reduce coupling.  You might want to think about changing the error handling, as other have suggested.  It would be nice to know why, if only to improve the quality of your tests, CreateUser has failed, for instance.  You could do this with exceptions or with an out parameter (which is how MembershipProvider works, if I remember correctly).

OwnerDisplayName: Ben Robbins

Title: How to properly mock and unit test

Body:
I'm basically trying to teach myself how to code and I want to follow good practices. There are obvious benefits to unit testing. There is also much zealotry when it comes to unit-testing and I prefer a much more pragmatic approach to coding and life in general. As context, I'm currently writing my first "real" application which is the ubiquitous blog engine using asp.net MVC. I'm loosely following the MVC Storefront architecture with my own adjustments. As such, this is my first real foray into mocking objects. I'll put the code example at the end of the question.

I'd appreciate any insight or outside resources that I could use to increase my understanding of the fundamentals of testing and mocking. The resources I've found on the net are typically geared towards the "how" of mocking and I need more understanding of the where, why and when of mocking. If this isn't the best place to ask this question, please point me to a better place.

I'm trying to understand the value that I'm getting from the following tests. The UserService is dependent upon the IUserRepository. The value of the service layer is to separate your logic from your data storage, but in this case most of the UserService calls are just passed straight to IUserRepository. The fact that there isn't much actual logic to test could be the source of my concerns as well. I have the following concerns.

It feels like the code is just testing that the mocking framework is working.

In order to mock out the dependencies, it makes my tests have too much knowledge of the IUserRepository implementation. Is this a necessary evil?

What value am I actually gaining from these tests? Is the simplicity of the service under test causing me to doubt the value of these tests.

I'm using NUnit and Rhino.Mocks, but it should be fairly obvious what I'm trying to accomplish.

    [SetUp]
    public void Setup()
    {
        userRepo = MockRepository.GenerateMock<IUserRepository>();
        userSvc = new UserService(userRepo);
        theUser = new User
        {
            ID = null,
            UserName = "http://joe.myopenid.com",
            EmailAddress = "joe@joeblow.com",
            DisplayName = "Joe Blow",
            Website = "http://joeblow.com"
        };
    }

    [Test]
    public void UserService_can_create_a_new_user()
    {
        // Arrange
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(true);

        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.True,
          "UserService.CreateUser(user) failed when it should have succeeded");
    }

    [Test]
    public void UserService_can_not_create_an_existing_user()
    {
        // Arrange
        userRepo.Stub(repo => repo.IsExistingUser(theUser)).Return(true);
        userRepo.Expect(repo => repo.CreateUser(theUser)).Return(false);
        // Act
        bool result = userSvc.CreateUser(theUser);

        // Assert
        userRepo.VerifyAllExpectations();
        Assert.That(result, Is.False,
            "UserService.CreateUser() allowed multiple copies of same user to be created");
    }

OwnerDisplayName: tvanfosson


问:
In Java, do methods that don't use static or class variables need to be synchronized?
Do methods that only use local variables inside suffer any threading issues ?. Somewhere it was mentioned that the method with local variables are copied to each thread stack frame to work with and do not need to synchronized for multithreaded implementation unless it uses class level or static references/variables ?</p>

答:
The question is very generic, so please do not expect any specificity from my answer.

1_ We need to more careful with static methods than say instance methods.

2_ @Justmycorrectopinion is about  right, but some of the terms he described needs to be more elaborated to be perfect. ( Even if the static method, only works on local variable, there is still possibility of race condition.)

3_ For me there are simple rules that have helped me analyze thread safety.

Understand if each components encapsulated within it is shareable or not. So the simplest solution is to reduce the scope of all variable and only increase scope if absolutely necessary and if component perform mutation on a object, its usually not thread safe.

4_ Use tooling support to perform static code analysis on thread safety. (Idea has checkthread plugin).

5_ Never use static method to perform object mutation. If calling static variable causes object mutation, then the developer is just circumventing OOPS.

6_ Always document  thread safety. Remember some method may not need to be synchronized when you develop, but can be made not thread safe very easily.

7_ Last but probably my most important point, make sure most of your objects are immutable. In my experience, most of the time, I never had to make many of my objects mutable. (In rare cases when object state needs to be changed, defensive copying / New Object Creation is almost always better. )


问:
How do you terminate a conversation based on user input evaluation through a webhook (api v2)
Let's say my bot has an ongoing conversation with the user and my webhook asks "Are you done?" and the user responds "Yes".
How do I close the conversation through the webhook?
I suspect it is through followupEventInput but I could not get anything to work.

I am not using a nodeJS library. Coding in C#.

Here is what I tried: I respond with an output context and an event: the event is associated with "End conversation" under the Google Assistant at the bottom of the intent window.

```<code> {
  "fulfillmentText": "OK. The note was recorded.",
  "fulfillmentMessages": [
  {
  "text": {
    "text": [
      "OK. The note was recorded."
    ]
  }
}
],
  "outputContexts": [
{
  "lifespanCount": 2,
  "name": "projects/xxx/agent/sessions/1512399774430/contexts/note-end"
}
],
"followupEventInput": {
"name": "end-event",
"languageCode": "en"
  }
}
</code>```

With the above code, the user never hears "OK. The note was recorded.", the session ends abruptly with Google Home saying "The app is not responding anymore" (or something similar). Works but not acceptable.

If I don't put the followupEvent, the user hears "OK. The note was recorded." but the conversation doesn't end... then I need to rely on the user to close it using another intent, which is what I want to avoid as it would be redundant.

答:
You have two options to end a Google Assistant conversation with Dialogflow:

Response defined in Dialogflow

Go to the intent defined in Dialogflow and scroll down and click on Google Assistant and check the box labeled End conversation

NOTE: this will only work with responses defined in Dialogflow console, not responses created by fulfillment.

Response defined in webhook

Respond to Dialogflow's webhook request with a response of the form:

{
  "fulfillmentMessages": [
    {
      {
        "platform": "ACTIONS_ON_GOOGLE",
        "paylaod":{
          {
            "expectUserResponse": false,
            ...
          }
        }
      }
    }
  ],
  ...
}
```

Using either of these methods your app will say whatever is specified in the console (for #1) or webhook (for #2) and end the conversation with the user.  Fill in values in the response section of the Dialogflow intent (for #1) or the payload object (for #2) to send a response to the user as you end the conversation.

Sources

Dialogflow Webhook Response v2 docs:https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/WebhookResponse

Action on Google webhook response docs: https://developers.google.com/actions/reference/rest/Shared.Types/AppResponse#FIELDS.expect_user_response

Body:
Let's say my bot has an ongoing conversation with the user and my webhook asks "Are you done?" and the user responds "Yes".
How do I close the conversation through the webhook?
I suspect it is through followupEventInput but I could not get anything to work.

I am not using a nodeJS library. Coding in C#.

Here is what I tried: I respond with an output context and an event: the event is associated with "End conversation" under the Google Assistant at the bottom of the intent window.

 {
  "fulfillmentText": "OK. The note was recorded.",
  "fulfillmentMessages": [
  {
  "text": {
    "text": [
      "OK. The note was recorded."
    ]
  }
}
],
  "outputContexts": [
{
  "lifespanCount": 2,
  "name": "projects/xxx/agent/sessions/1512399774430/contexts/note-end"
}
],
"followupEventInput": {
"name": "end-event",
"languageCode": "en"
  }
}

With the above code, the user never hears "OK. The note was recorded.", the session ends abruptly with Google Home saying "The app is not responding anymore" (or something similar). Works but not acceptable.

If I don't put the followupEvent, the user hears "OK. The note was recorded." but the conversation doesn't end... then I need to rely on the user to close it using another intent, which is what I want to avoid as it would be redundant.

Body:
You have two options to end a Google Assistant conversation with Dialogflow:

Response defined in Dialogflow

Go to the intent defined in Dialogflow and scroll down and click on Google Assistant and check the box labeled End conversation

NOTE: this will only work with responses defined in Dialogflow console, not responses created by fulfillment.

Response defined in webhook

Respond to Dialogflow's webhook request with a response of the form:

{
  "fulfillmentMessages": [
    {
      {
        "platform": "ACTIONS_ON_GOOGLE",
        "paylaod":{
          {
            "expectUserResponse": false,
            ...
          }
        }
      }
    }
  ],
  ...
}

Using either of these methods your app will say whatever is specified in the console (for #1) or webhook (for #2) and end the conversation with the user.  Fill in values in the response section of the Dialogflow intent (for #1) or the payload object (for #2) to send a response to the user as you end the conversation.

Sources

Dialogflow Webhook Response v2 docs:https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/WebhookResponse

Action on Google webhook response docs: https://developers.google.com/actions/reference/rest/Shared.Types/AppResponse#FIELDS.expect_user_response


问:
Combination Operators on Sensors Arrays Data
Is there any standardized operators over data from arrays of sensors?

I am normally dealing with sensors data in the form of time + channels. The time is a timestamp, and the channels are the available data for these timestamps. All these fields are numeric, no strings involved.

Normally I have to mix those data objects in different ways. Let's suppose M1 is size m1xn1 and M2 is size m2xn2:

Combine rows of data from the same channels and different timestamps (i.e. n1 == n2). This leads to a vertical concatenation [M1; M2].

Combine columns of data from the same timestamps and different channels, (i.e. m1 == m2). This leads to a horizontal concatenation [M1 M2].

These operators are trivial and well defined.

When I have slight differences, for example, a few additional samples in M1 or M2, everything turns complicated and I have to think in weird schemes to perform such operations, such as these:

Cleaning the exceeding samples on M1 or M2, for matching the dimensions.

Calculate an aggregated timestamp, obtaining a unique(sort()) on the timestamps, and then apply a union like in a SQL JOIN sentence.

Aggregate the data on M1 or M2, this is, reducing m1 or m2 to a smaller figure, resampling the timescale, and then apply an aggregation like in a SQL GROUP sentence.

I cannot think of a unique and definite function to combine this sort of data. How can I do this?

答:
Let's say you have an m1-element vector of time values t1 and and n1-element vector of channel values c1 for your m1-by-n1 matrix M1 (and likewise for M2). First and foremost, you will likely need to convert your time and channel values into equivalent index values. You can do this by expanding your time and channel values into grids using ndgrid, then converting them to index values using unique:

```<code>[t1, c1] = ndgrid(t1, c1);
[t2, c2] = ndgrid(t2, c2);
[tUnion, ~, tIndex] = unique([t1(:); t2(:)]);
[cUnion, ~, cIndex] = unique([c1(:); c2(:)]);
</code>```

Now there are two approaches you can take for aggregating the data using the above indices. If you know for certain that the matrices M1 and M2 will never contain repeated measurements (i.e. the same combination of time and channel will not appear in both), then you can build the final joined matrix by creating a linear index from tIndex and cIndex and combining the values from M1 and M2 like so:

```<code>MUnion = zeros(numel(tUnion), numel(cUnion));
MUnion(tIndex+numel(tUnion).*(cIndex-1)) = [M1(:); M2(:)];
</code>```

If the matrices M1 and M2 could contain repeated measurements at the same combination of time and channel values, then accumarray will be the way to go. You will have to decide how you want to combine the repeated measurements, such as taking the mean as shown here:

```<code>MUnion = accumarray([tIndex cIndex], [M1(:); M2(:)], [], @mean);
</code>```

Body:
Let's say you have an m1-element vector of time values t1 and and n1-element vector of channel values c1 for your m1-by-n1 matrix M1 (and likewise for M2). First and foremost, you will likely need to convert your time and channel values into equivalent index values. You can do this by expanding your time and channel values into grids using ndgrid, then converting them to index values using unique:

[t1, c1] = ndgrid(t1, c1);
[t2, c2] = ndgrid(t2, c2);
[tUnion, ~, tIndex] = unique([t1(:); t2(:)]);
[cUnion, ~, cIndex] = unique([c1(:); c2(:)]);

Now there are two approaches you can take for aggregating the data using the above indices. If you know for certain that the matrices M1 and M2 will never contain repeated measurements (i.e. the same combination of time and channel will not appear in both), then you can build the final joined matrix by creating a linear index from tIndex and cIndex and combining the values from M1 and M2 like so:

MUnion = zeros(numel(tUnion), numel(cUnion));
MUnion(tIndex+numel(tUnion).*(cIndex-1)) = [M1(:); M2(:)];

If the matrices M1 and M2 could contain repeated measurements at the same combination of time and channel values, then accumarray will be the way to go. You will have to decide how you want to combine the repeated measurements, such as taking the mean as shown here:

MUnion = accumarray([tIndex cIndex], [M1(:); M2(:)], [], @mean);